% $Id: ExpressionParser.oz,v 1.1 2007/11/26 21:17:26 leavens Exp leavens $ % An grammar for simple expressions. % The parsers return parse trees. Compare figures 9.5 and 9.6 of CTM. % ::= % | % | 'if' 'then' 'else' % | 'if' 'then' % ::= '+' | '*' | '-' | '>' % ::= | declare fun {Expression I ?U} choice {BasicExp I U} [] local R1 R2 LeftTree OpTree RightTree in LeftTree={BasicExp I R1} OpTree={Operator LeftTree RightTree R1 R2} RightTree={Expression R2 U} OpTree end [] local K1 K2 K3 R1 R2 TestTree ThenTree ElseTree in {Check 'if' I K1} TestTree={Expression K1 R1} {Check 'then' R1 K2} ThenTree={Expression K2 R2} {Check 'else' R2 K3} ElseTree={Expression K3 U} ifExp(TestTree ThenTree ElseTree) end [] local K1 K2 R TestTree ThenTree in {Check 'if' I K1} TestTree={Expression K1 R} {Check 'then' R K2} ThenTree={Expression K2 U} ifExp(TestTree ThenTree numExp(0)) end end end fun {Operator LeftTree RightTree I ?U} choice {Check '+' I U} plusExp(LeftTree RightTree) [] {Check '*' I U} timesExp(LeftTree RightTree) [] {Check '-' I U} subExp(LeftTree RightTree) [] {Check '>' I U} gtExp(LeftTree RightTree) end end fun {BasicExp I ?U} What in I=What|U choice {IsAtom What}=true idExp(What) [] {IsNumber What}=true numExp(What) end end % A helping procedure to check for reserved words proc {Check KW I ?U} I=KW|U end