Open leonardoaraujosantos opened 8 years ago
Backus Normal Form is one notation techniques for context-free grammars, often used to describe the syntax of programming languages like C, or Python
Example: This translates into English as:
stmt: var_decl | func_decl | expr { /* Any Action*/ }
Read as ”stmt is a var_decl or func_decl or expr” and if this grammar match execute something on the ”action block”. Inside the action block we mount our AST Tree
if_stmt : IF '(' condition ')' block { /* do stuff when this rule is encountered */ }
| IF '(' condition ')' { /*do some other stuff on this other rule*/ }
;
This would create the grammar for the if statement, like if (condition) block, or if (condition)
Introduction
The parser’s job is to figure out the relationship(grammar) among the input tokens. Those tokens come from the scanner (flex). A grammar is a series of rules that the parser uses to recognize syntactically valid input.
Bison only deal with the syntax no the semantic, for instance the code bellow has a valid syntax but is invalid, bison will think that this is fine
Consider the following grammar on bison. NAME, NUMBER, '+', '-', are tokens that flex gives to us.
Every line here is a rule, so the rule for a statement is the pattern "NAME = expression". And the rule for expression is the pattern "NUMBER+NUMBER" OR "NUMBER-NUMBER"
Every grammar includes a start symbol, the one that has to be at the root of the parse tree. In this grammar, statement is the start symbol.
So the following source code line:
Would produce from the scanner the following tokens: NAME,'=',NUMBER,'+',NUMBER
This AST tree would be created:
Where "fred =" is a statement. And "12+13" is an expression.
Now what would happen if we would want to parse a longer instruction
To solve this can use a Recursive rule, where the rule call itself.
Now the tree would grow to this:
To start use our token inputs, starting from a simple example.
Tokens generated with out scanner
And build an AST tree
Class diagram for parser Nodes
Considering the class diagram bellow, we need to create a rule for every class that inherites from Node.
References