Repository navigation
Define charset once and reference from both rules and semantic actions? #401
Unanswered
pcafstockf
asked this question in
Q&A
Replies: 1 comment
|
Peggy can't reference a character class from JavaScript, and an action can't call a rule. You can go the other way, though: define the set once as a regex in the global initializer ( {{
const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
}}
Start = Comment
Comment = "/*" body:$(!"*/" .)* "*/" {
return { body, multiLine: LINE_TERMINATOR.test(body) };
}
LineTerminator "line terminator" = c:. &{ return LINE_TERMINATOR.test(c); } { return c; }I checked this with peggy 5.1.1: parser.parse('/* one */') // { body: ' one ', multiLine: false }
parser.parse('/* a\nb */') // { body: ' a\nb ', multiLine: true }
parser.parse('/* a\u2028b */') // { body: ' a\u2028b ', multiLine: true }
// startRule: 'LineTerminator'
'\n', '\r', '\u2029' -> matched
'x' -> Expected line terminator but "x" found.Two notes:
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I would like to define a charset in one location and use it both in the definition of grammar rules and within semantic actions.
This is a bit of a contrived example, so please don't take it too literally.
I have this rule in my grammar:
LineTerminator = [\n\r\u2028\u2029]
There are many other rules in my grammar which collect text (for example multi line comment blocks).
Is it possible in the semantic actions of those other rules, to test for these line terminators characters within text(), without having to retype my "regex"?
Perhaps for example checking for the difference between:
/*a one line block comment*/and
/*a multi-line
block comment
*/I do realize I could look at the line numbers in location() for this particular example. But like I said I'm looking for a way to re-use charset definitions, not solve comment specific problem.
All reactions