I am creating an interpreted programming language in C# (kind of for the lulz, no real purpose other than to have fun and learn about compilers), and ran into a problem. In my lexer, I remember where the token was in the original file to give more useful debug errors. I keep this “TokenPosition” object around, copying it along as the program goes through compile steps, until it winds up in the same object that runs interpreted code (for example, my “Identifier” class for named variables has a TokenPosition member).
My question: If an exception gets thrown, I want to look at the stack, find the topmost object with a TokenPosition member, and print its location. Or, more generally, “How do I get objects that are/were on the stack after an exception? Is this even possible?” (I can do the checking if it has a TokenPosition object / getting it easily, I’m not asking how to do that)
Last resorts that I do not want to have to do: Every single call to a behavior (which happens A LOT) assign a static tokenPosition variable somewhere with this.tokenPosition. I also could surround EVERYTHING with try/catches, but again, I don’t really want to do this.
Parameters to methods are ephemeral. They may be overwritten by local variables when they are no longer live, or optimized out by the JIT compiler as unused, or even garbage collected while the method is running. You will have to track this information yourself, for example, by having a separate stack data structure for “currently active object” that is automatically unwound by a
usingclause.