数式をpeggedで構文木生成
2021/9/8 6:14:00
文法:
Arithmetic:
Term < Factor (Add / Sub)*
Add < "+" Factor
Sub < "-" Factor
Factor < Primary (Mul / Div)*
Mul < "*" Primary
Div < "/" Primary
Primary < Parens / Neg / Pos / Number / Variable
Parens < "(" Term ")"
Neg < "-" Primary
Pos < "+" Primary
Number < ~([0-9]+)
Variable <- identifier
数式
1 + 2 - (3*x-5)*6
生成結果:
Arithmetic("1 + 2 - (3*x-5)*6").writeln;
=>
Arithmetic [0, 17]["1", "+", "2", "-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Term [0, 17]["1", "+", "2", "-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Factor [0, 2]["1"]
| +-Arithmetic.Primary [0, 2]["1"]
| +-Arithmetic.Number [0, 2]["1"]
+-Arithmetic.Add [2, 6]["+", "2"]
| +-Arithmetic.Factor [4, 6]["2"]
| +-Arithmetic.Primary [4, 6]["2"]
| +-Arithmetic.Number [4, 6]["2"]
+-Arithmetic.Sub [6, 17]["-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Factor [8, 17]["(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Primary [8, 15]["(", "3", "*", "x", "-", "5", ")"]
| +-Arithmetic.Parens [8, 15]["(", "3", "*", "x", "-", "5", ")"]
| +-Arithmetic.Term [9, 14]["3", "*", "x", "-", "5"]
| +-Arithmetic.Factor [9, 12]["3", "*", "x"]
| | +-Arithmetic.Primary [9, 10]["3"]
| | | +-Arithmetic.Number [9, 10]["3"]
| | +-Arithmetic.Mul [10, 12]["*", "x"]
| | +-Arithmetic.Primary [11, 12]["x"]
| | +-Arithmetic.Variable [11, 12]["x"]
| +-Arithmetic.Sub [12, 14]["-", "5"]
| +-Arithmetic.Factor [13, 14]["5"]
| +-Arithmetic.Primary [13, 14]["5"]
| +-Arithmetic.Number [13, 14]["5"]
+-Arithmetic.Mul [15, 17]["*", "6"]
+-Arithmetic.Primary [16, 17]["6"]
+-Arithmetic.Number [16, 17]["6"]