26 lines
1.1 KiB
Text
26 lines
1.1 KiB
Text
def ops: ['+','-','*','/'];
|
||
|
||
data binaryExpression <{left: <node>, op: <?($ops <[<=$::raw>]>)>, right: <node>}>
|
||
data node <binaryExpression|"1">
|
||
|
||
composer parseArithmetic
|
||
(<WS>?) <addition|multiplication|term> (<WS>?)
|
||
rule addition: {left:<addition|multiplication|term> (<WS>?) op:<'[+-]'> (<WS>?) right:<multiplication|term>}
|
||
rule multiplication: {left:<multiplication|term> (<WS>?) op:<'[*/]'> (<WS>?) right:<term>}
|
||
rule term: <INT"1"|parentheses>
|
||
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
|
||
end parseArithmetic
|
||
|
||
templates evaluateArithmetic
|
||
<´node´ {op: <='+'>}> ($.left -> evaluateArithmetic) + ($.right -> evaluateArithmetic) !
|
||
<´node´ {op: <='-'>}> ($.left -> evaluateArithmetic) - ($.right -> evaluateArithmetic) !
|
||
<´node´ {op: <='*'>}> ($.left -> evaluateArithmetic) * ($.right -> evaluateArithmetic) !
|
||
<´node´ {op: <='/'>}> ($.left -> evaluateArithmetic) ~/ ($.right -> evaluateArithmetic) !
|
||
otherwise $ !
|
||
end evaluateArithmetic
|
||
|
||
def ast: '(100 - 5 * (2+3*4) + 2) / 2' -> parseArithmetic;
|
||
'$ast;
|
||
' -> !OUT::write
|
||
'$ast -> evaluateArithmetic;
|
||
' -> !OUT::write
|