m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--__tests__/parser.test.js18
-rw-r--r--src/parser.js16
2 files changed, 32 insertions, 2 deletions
diff --git a/__tests__/parser.test.js b/__tests__/parser.test.js
index a741007..74ca442 100644
--- a/__tests__/parser.test.js
+++ b/__tests__/parser.test.js
@@ -73,6 +73,24 @@ describe('parse', () => {
})
})
+ it('parses negatives', () => {
+ expect(parse('-1 + (-(2d6))')).toEqual({
+ type: 'add',
+ left: {
+ type: 'negative',
+ value: { type: 'constant', value: 1 }
+ },
+ right: {
+ type: 'negative',
+ value: {
+ type: 'd',
+ left: { type: 'constant', value: 2 },
+ right: { type: 'constant', value: 6 }
+ }
+ }
+ })
+ })
+
describe('parsing parentheses', () => {
test('(1d6)d6', () => {
expect(parse('(1d6)d6')).toEqual({
diff --git a/src/parser.js b/src/parser.js
index 9f2c6ac..5b9b718 100644
--- a/src/parser.js
+++ b/src/parser.js
@@ -40,7 +40,12 @@ newSymbol('+', null, 20, (left, parser) => {
}
})
-newSymbol('-', null, 20, (left, parser) => {
+newSymbol('-', (parser) => {
+ return {
+ type: 'negative',
+ value: parser.expression(40)
+ }
+}, 20, (left, parser) => {
return {
type: 'subtract',
left: left,
@@ -56,10 +61,17 @@ const newParser = (tokens) => {
currentToken: 0,
token: function() { return this.tokens[this.currentToken] },
advanceToken: function() { this.currentToken++ },
+ match: function(token) {
+ if (this.token().type === token) {
+ this.advanceToken()
+ } else {
+ throw 'error'
+ }
+ },
expression: function(rbp) {
let symbol = this.token()
- let left = symbol.nud()
this.advanceToken()
+ let left = symbol.nud(this)
while (rbp < this.token().lbp) {
symbol = this.token()