DSL for parsing bas tag:client title:magic #2034
Answered
by
msujew
gaborbernat
asked this question in
Q&A
-
I am trying to parse a text where keys can have fields attached to it: import { CstParser, Lexer, createToken } from "chevrotain";
const WhiteSpace = createToken({ name: "WhiteSpace", pattern: /\s+/, group: Lexer.SKIPPED });
const Value = createToken({ name: "Identifier", pattern: /[-a-zA-Z0-9]+/ });
const FieldSpecifier = createToken({ name: "Identifier", pattern: /(tag|title):/ });
const allTokens = [WhiteSpace, Value, FieldSpecifier];
const lexer = new Lexer([FieldSpecifier, Value, WhiteSpace]);
class SelectParser extends CstParser {
constructor() {
super(allTokens);
// biome-ignore lint/complexity/noUselessThisAlias: required for chevrotain
const $ = this;
$.RULE("element", () => {
$.OPTION(() => {
$.CONSUME(FieldSpecifier);
});
$.CONSUME2(Value);
});
$.RULE("search", () => {
$.MANY_SEP({
SEP: WhiteSpace,
DEF: () => {
$.SUBRULE($.element);
},
});
});
this.performSelfAnalysis();
}
}
const parser = new SelectParser();
export function parse(text: string) {
const lexingResult = lexer.tokenize(text);
// "input" is a setter which will reset the parser's state.
parser.input = lexingResult.tokens;
parser.search();
if (parser.errors.length > 0) {
throw parser.errors[0];
}
} Ideas? |
Beta Was this translation helpful? Give feedback.
Answered by
msujew
Jun 20, 2024
Replies: 1 comment 1 reply
-
Hey @gaborbernat, I tried reproducing this in the playground and noticed that you're using |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
gaborbernat
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @gaborbernat,
I tried reproducing this in the playground and noticed that you're using
Lexer.SKIPPED
for theWhiteSpace
token. This will completely discard the token from the token stream and prevents you from actually consuming it. After removing the group, everything seems to parse correctly :)