diff --git a/README.md b/README.md index ca8e16d..c3ad4c3 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,10 @@ The `start` and `end` properties both refer to the current parse position. The `offset` property contains an offset as a zero-based index and `line` and `column` properties contain a line and a column as one-based indices. +Line and column are somewhat expensive to compute, so if you just need the +offset, there's also a function `offset` that returns just the start offset, +and a function `range` that returns the array `[start, end]` offsets. + The code inside the predicate can also access options passed to the parser using the `options` variable. diff --git a/lib/compiler/passes/generate-js.js b/lib/compiler/passes/generate-js.js index acd55fe..8adeaa0 100644 --- a/lib/compiler/passes/generate-js.js +++ b/lib/compiler/passes/generate-js.js @@ -1035,6 +1035,14 @@ function generateJS(ast, options) { " return input.substring(peg$savedPos, peg$currPos);", " }", "", + " function offset() {", + " return peg$savedPos;", + " }", + "", + " function range() {", + " return [peg$savedPos, peg$currPos];", + " }", + "", " function location() {", " return peg$computeLocation(peg$savedPos, peg$currPos);", " }", diff --git a/test/behavior/generated-parser-behavior.spec.js b/test/behavior/generated-parser-behavior.spec.js index 0ef1d56..e50d1a6 100644 --- a/test/behavior/generated-parser-behavior.spec.js +++ b/test/behavior/generated-parser-behavior.spec.js @@ -583,6 +583,24 @@ describe("generated parser behavior", function() { end: { offset: 3, line: 2, column: 1 } }); }); + + it("|offset| returns current start offset", function() { + let parser = peg.generate([ + "start = [0-9]+ val:mark { return val; }", + "mark = 'xx' { return offset(); }" + ].join("\n"), options); + + expect(parser).to.parse("0123456xx", 7); + }); + + it("|range| returns current range", function() { + let parser = peg.generate([ + "start = [0-9]+ val:mark { return val; }", + "mark = 'xx' { return range(); }" + ].join("\n"), options); + + expect(parser).to.parse("0123456xx", [7, 9]); + }); }); });