Reimplement offset() and add range(). (#528)

* Reimplement offset()
* Implement range()

Fixes #526, thanks @felix9
master
felix 7 years ago committed by Futago-za Ryuu
parent 5cde815341
commit 958e15879d

@ -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.

@ -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);",
" }",

@ -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]);
});
});
});

Loading…
Cancel
Save