Operator-precedence parser: Difference between revisions

Content deleted Content added
Format code
Line 17:
 
<syntaxhighlight lang="ebnf">
expression ::= equality-expression
equality-expression ::= additive-expression ( ( '==' | '!=' ) additive-expression ) *
additive-expression ::= multiplicative-expression ( ( '+' | '-' ) multiplicative-expression ) *
multiplicative-expression ::= primary ( ( '*' | '/' ) primary ) *
primary ::= '(' expression ')' | NUMBER | VARIABLE | '-' primary
</syntaxhighlight>
 
Line 34:
The pseudo-code for the algorithm is as follows. The parser starts at function ''parse_expression''. Precedence levels are greater than or equal to 0.
 
''parse_expression'' ()
'''return ''parse_expression_1'' parse_expression_1(''parse_primary'' (), 0)
 
''parse_expression_1 (lhs, min_precedence)
''lookahead'' := peek next token
'''while''' ''lookahead'' is a binary operator whose precedence is >= ''min_precedence''
''op'' := ''lookahead''
advance to next token
''rhs'' := ''parse_primary'' ()
''lookahead'' := peek next token
'''while''' ''lookahead'' is a binary operator whose precedence is greater
than ''op''<nowiki>'</nowiki>s, or a right-associative operator
whose precedence is equal to ''op'''s
Line 50:
''lookahead'' := peek next token
''lhs'' := the result of applying ''op'' with operands ''lhs'' and ''rhs''
'''return''' ''lhs''
 
Note that in the case of a production rule like this (where the operator can only appear once):
 
<syntaxhighlight lang="bnf">
equality-expression ::= additive-expression ( '==' | '!=' ) additive-expression
</syntaxhighlight>
 
Line 113:
#include <string.h>
 
int main(int argc, char *argv[]) {
int i;
printf("((((");
for (i=1;i!=argc;i++) {
if (argv[i] && !argv[i][1]) {
switch (*argv[i]) {
case '(': printf("(((("); continue;
case ')': printf("))))"); continue;