dmajda/pegjs — Issue #65: Provide a convenient way to get the range matched by a rule
Author: mcasimir
Created: 2012-01-22 10:54:43+00:00
State: open

Looking in the sources and examples I could not find another way to get the range matched by a rule than this:
{
function range(cacheKey){
startPos = parseInt(cacheKey.match(/[0-9]+$/)[0])
return [startPos, pos - 1]
}
}

Rule = ...
{
return {someProperty: "...", range: range(cacheKey)}
}

I've also tryied to do this:
{
prev = 0;
function range(){
startPos = prev
return [startPos, pos - 1]
prev = pos
}
}

but in this case i should call 'range()' in every single rule to hope i could have a meaningful result but even doing so the resulting ranges will be wrong.

Another global variable just as 'pos' (eg 'prev') should be fine to support this behavior.

This is particularly useful if you want to delegate to a later time some changes on the input that are based on the AST. Take this as example (sorry for the 'pseudo-code'):

function syntaxHighlightMyGrammar(input) {
ast = parse(input)
traverse = function(node){
input.insertAt(node.range.endPos, endElementForRule(node.type))
for child in node.children {traverse(child)}
input.insertAt(node.range.startPos, startElementForRule(node.type))
}
traverse(ast.root);
return input;
}