|
1 | 1 | // tinymath parsing grammar |
2 | 2 |
|
3 | 3 | { |
4 | | - function simpleLocation (location) { |
5 | | - // Returns an object representing the position of the function within the expression, |
6 | | - // demarcated by the position of its first character and last character. We calculate these values |
7 | | - // using the offset because the expression could span multiple lines, and we don't want to deal |
8 | | - // with column and line values. |
9 | | - return { |
10 | | - min: location.start.offset, |
11 | | - max: location.end.offset |
| 4 | + function simpleLocation (location) { |
| 5 | + // Returns an object representing the position of the function within the expression, |
| 6 | + // demarcated by the position of its first character and last character. We calculate these values |
| 7 | + // using the offset because the expression could span multiple lines, and we don't want to deal |
| 8 | + // with column and line values. |
| 9 | + return { |
| 10 | + min: location.start.offset, |
| 11 | + max: location.end.offset |
| 12 | + } |
12 | 13 | } |
13 | | - } |
14 | 14 | } |
15 | 15 |
|
16 | 16 | start |
@@ -74,26 +74,34 @@ Expression |
74 | 74 | = AddSubtract |
75 | 75 |
|
76 | 76 | AddSubtract |
77 | | - = _ left:MultiplyDivide rest:(('+' / '-') MultiplyDivide)* _ { |
78 | | - return rest.reduce((acc, curr) => ({ |
| 77 | + = _ left:MultiplyDivide rest:(('+' / '-') MultiplyDivide)+ _ { |
| 78 | + const topLevel = rest.reduce((acc, curr) => ({ |
79 | 79 | type: 'function', |
80 | 80 | name: curr[0] === '+' ? 'add' : 'subtract', |
81 | 81 | args: [acc, curr[1]], |
82 | | - location: simpleLocation(location()), |
83 | | - text: text() |
84 | | - }), left) |
| 82 | + }), left); |
| 83 | + if (typeof topLevel === 'object') { |
| 84 | + topLevel.location = simpleLocation(location()); |
| 85 | + topLevel.text = text(); |
| 86 | + } |
| 87 | + return topLevel; |
85 | 88 | } |
| 89 | + / MultiplyDivide |
86 | 90 |
|
87 | 91 | MultiplyDivide |
88 | 92 | = _ left:Factor rest:(('*' / '/') Factor)* _ { |
89 | | - return rest.reduce((acc, curr) => ({ |
| 93 | + const topLevel = rest.reduce((acc, curr) => ({ |
90 | 94 | type: 'function', |
91 | 95 | name: curr[0] === '*' ? 'multiply' : 'divide', |
92 | 96 | args: [acc, curr[1]], |
93 | | - location: simpleLocation(location()), |
94 | | - text: text() |
95 | | - }), left) |
| 97 | + }), left); |
| 98 | + if (typeof topLevel === 'object') { |
| 99 | + topLevel.location = simpleLocation(location()); |
| 100 | + topLevel.text = text(); |
| 101 | + } |
| 102 | + return topLevel; |
96 | 103 | } |
| 104 | + / Factor |
97 | 105 |
|
98 | 106 | Factor |
99 | 107 | = Group |
|
0 commit comments