Discuss Simple interpreter with Lex/YACC in the Other Programming Languages forum on Dev Shed. Simple interpreter with Lex/YACC A place for discussing programming languages not covered in specific forums such as Assembler, COBOL, etc. - you get the idea.
Posts: 737
Time spent in forums: 3 Weeks 5 Days 8 m 19 sec
Reputation Power: 928
Normally you have a parser (possibly constructed with lex/yacc) which reduces the source code to a data structure (usually some sort of tree). You can then execute the source code directly from the structure or convert it into some other form.
For example an if statement might turn into a structure like
You might want to start off with a language with a simpler structure (like a Lisp/Scheme variant) to get the principle down without having to worry about too many variations in syntax.
Posts: 12
Time spent in forums: 4 h 24 m 50 sec
Reputation Power: 0
That makes sense, just one thing that confuses me is the exact structure of the tree: How to store the name/type of the node, how to manage child nodes/literals, etc.
Also, I was considering an alternative to Lex/YACC, mostly this:
EDIT: since I can't post URLs, I wrote this Perl one-liner that will print the URL:
Posts: 12
Time spent in forums: 4 h 24 m 50 sec
Reputation Power: 0
I came up with a nice solution for the AST, but it requires an OO language:
Have a class Node that contains an eval() function and a list of children. The eval() function would return the value that the node evaluates to.
For example, an IntegerLiteralNode would store its value and its eval() would return that. Then, an AdditionNode can, for example, have two IntegerLiteralNodes as children, and its eval() would call eval() on the two chirdren and return the sum.
I just wonder how would I handle multiple data types? But I'll probably play around with a language containing only integers for now to test my AST concept.
Posts: 737
Time spent in forums: 3 Weeks 5 Days 8 m 19 sec
Reputation Power: 928
You can write OO in C. You just don't get fancy keywords to make the compiler do all the work for you.
Code:
enum TermType { INT, FLOAT };
union TermData {
int i;
double d;
};
struct Term {
TermType type;
TermData data;
};
double eval( struct Term *a ) {
if( a->type == INT ) {
return a->data.i;
}
// . . .
}
- or if you prefer function pointers -
Code:
union TermData {
int i;
double d;
};
struct Term {
double (*eval)(struct Term*);
TermData data
};
void eval_int( struct Term *this ) {
return this->data.i;
}
struct Term zero { eval_int, 0 };