Barnack
Barnack

Reputation: 941

logic suggestions for interpreter ast building

i'm in the process of making an interpreter, and i started with the ast classes. The code is object oriented in c++. Each action is a "statement", a block is a statement itself and it contains a list of statements. Blocks also define different scopes, keeping record of what variables have been allocated within that scope and deleting them at the end of it. The execution consists in the main block calling "execute" for every statement it contains, where each statement can consist in another block, a simple instruction or a function call. With this structure i could think of how to implement most constructs, (while, if-else) but i don't understand how could i make a goto. Despite the fact gotos are almost not used anyway, i'd need the goto as a starting base to implement break and continue for loops.

Does anyone have a conceptual suggestion? (conceptually speaking, not actual code needed).

NOTE: the code is not executed line by line while being parsed, it's first entirely parsed into an ast, and then executed.

Upvotes: 0

Views: 73

Answers (1)

3Dave
3Dave

Reputation: 29051

If you're gotoing to line numbers, just add an attribute to your AST node class indicating on which line it's declared in the source. When executing a goto node, find the highest node in the tree with that line number, and link that as your goto target.

For labels, you have a few options. You could turn the labels into an AST node, itself, or add an attribute to the node class which is only set if the previous statement is a label. When processing your goto, do the same thing as you'd do with line numbers. Find the top-most node that has the label attribute set.

This assumes that your targets appear in the source before the goto. Otherwise, you'll have to do a fixup pass to resolve the invocation targets, much like function calls.

There are probably better ways; this is just what comes to mind.

Essentially, your goto is a jmp, and you need a way to resolve the target address. I'd just parse the source, then do a second pass to fixup any gotos, which would have a pointer to the first AST node after the label.

Upvotes: 2

Related Questions