Answer the question
In order to leave comments, you need to log in
Parser for if-else constructs based on context-free grammar in BNF?
Greetings!
I need to build a parser that would produce a parse tree for an expression like this:
if ( arr[i, j+5, j*j+1] >= 5 + a )
a = a * b + 1;
else a = 2 * b;
Id = {Letter}{AlphaNumeric}*
Integer = {Digit}+
<Condition> ::= <Condition IF> <Condition ELSE>
<IF> ::= 'if'
<ELSE> ::= 'else'
<Condition IF> ::= <IF> '(' <Boolean Exp> ')' <Expression> '=' <Expression> ';'
<Condition ELSE> ::= <ELSE> <Expression> '=' <Expression> ';'
<Expression> ::= <Expression> '+' <Mult Exp>
| <Expression> '-' <Mult Exp>
| <Mult Exp>
<Array Expression> ::= <Expression>
| <Array Expression> ',' <Expression>
<Mult Exp> ::= <Mult Exp> '*' <Negate Exp>
| <Mult Exp> '/' <Negate Exp>
| <Negate Exp>
<Negate Exp> ::= '-' <Value>
| <Value>
<Value> ::= ID
| Integer
| '(' <Expression> ')'
<BoolOperator> ::= '>'|'<'|'>='|'<='|'=='
<Boolean Exp> ::= <Expression> | ID'['<Array Expression>']' <BoolOperator> <Expression> | ID'['<Array Expression>']'
Answer the question
In order to leave comments, you need to log in
1) Yes, you built the BNF correctly - there is nothing supernatural there.
But this Expression := Expression;
, generally speaking, is still not true, because. a + b = 5
cannot be assigned :
And for my taste:
Expression := Expression | ID=Expression
Block := Expression; | Expression; Block
ArrayExpression := { Block }
BoolExp, как и в С, можно отдельно не выделять, 0 - false, !0 - true
1. (\d)+ - Integer
2. \w (\w | \d )* - identificator
3. + | - | * | / | % | := | < | > | <= | >= | != | == | ( | ) | ... - arithmetic sign
4. ; | [ | ] | { | } | ... - separators
( Expression )
it - this is some kind of arithmetic expression:(a + b) * c + d = +*+abcd
. Expression | ArrayExpressions
, you parse them too. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question