|
I've got a homework assignment that's driving me nuts. I'm implementing a compiler for a custom language that translates to C. This language supports nested functions that can reference variables in their parent functions. From what I understand, the best way to implement this is to pass a static link (a pointer to the stack frame of the enclosing function) to each function, from which you can find the variable you want by applying a constant offset. The problem I'm having is that I can't seem to figure out a way to consistently get the correct offset for a given variable. Here's a quick example: code:
First of all, am I on the right track with this? I'm not sure if using a pointer to the parent function's first parameter is the "proper" way to implement a static link. Second, how can I determine the offset of a given local variable from the static link at compile time? It'd be a heck of a lot easier if I knew exactly what a given function's stack frame looked like, but I'm not sure how to figure that out. A nudge in the right direction would be greatly appreciated.
|
# ¿ May 6, 2011 09:29 |
|
|
# ¿ May 14, 2024 05:56 |
|
Ugg boots posted:Just figure out which variables from the parent function are being used in the nested function and pass references/pointers to all of them when calling the nested function. I guess that would work, though when we were going over the assignment in class the professor specifically mentioned that we should use a static link. Wikipedia and other places online also mention that as being the way nested functions are typically implemented. I'll probably do it this way as a last resort though. pseudorandom name posted:You can't predict anything about the layout of stack variables. The compiler can (and will) place them in any order it feels like, sometimes combining multiple variables into a single stack slot or never allocating any stack space at all. That makes sense. I suppose the solution is to figure out the offset at run time then? rjmccall posted:There are tons of different ways to implement nested functions. There are several key points of language design which influence the choice: Variables are captured by reference and functions aren't first-class objects, so all you can do with a function is call it, and you can never reference a function outside of the scope in which it was declared. I think I'm going to try out figuring out the static link offset at run time for now, and if that doesn't work out I'll go with Ugg Boots's suggestion. Edit: Well it looks like poo poo but it works. woop dizzywhip fucked around with this message at 21:17 on May 6, 2011 |
# ¿ May 6, 2011 18:47 |