3 ms·
Remember that a yacc file builds an AST tree and paying attention to the AST tree goes a long way in understanding yacc file. Language ambiguity due to context
by ww520 14y ago
Remember that a yacc file builds an AST tree and paying attention to the AST tree goes a long way in understanding yacc file.
Language ambiguity due to context is pretty common. The way to deal with them is with nested scope symbol tables. And determine the semantic of a symbol usage based on previous declaration of the symbol, tracked in the symbol tables.
In the article's example, x + 3, it confuses the stages of the lexer and the parser. The lexer only knows x as a symbol. Its output is symbol('x') op('+') num(3). It doesn't know it's a function call or a variable reference. It is the parser's job to figure out the semantic of x based on context and to build the AST.
In this case if x has been declared as a variable before, its symbol and type info are recorded in the symbol table. When x + 3 is encountered, it's a simple lookup on the symbol table to see if it's a declared variable and generate the AST node with op('+', var('x'), num(3)).
If x has been declared as function in the symbol table, the lookup will generate the funcall AST node.
For special declaration rule like usage before declaration (as in Ruby), the lack of definition in the symbol table can be defaulted to a funcall.