-
I am struggling to find an efficient way to enforce distinct (unique) keys when parsing my configuration file and I was hoping to see an example somewhere. my initial solution suggests a simple gate that looks somewhat like this: function isKeyExist(type) {
let max = $.input.length * -1;
for (let i = 0; i >= max; i--) {
const current = $.LA(i);
if (current.tokenType === EOF || current.tokenType === LCurly) return false;
if (current.tokenType === type) return true;
}
} and combined with this rule, it works well enough: $.RULE("settingsOptions", () => {
$.MANY_SEP({
SEP: Comma,
DEF: () => {
$.OR([
{ GATE: !isKeyExist(Id), ALT: () => { $.SUBRULE($.id) } },
{ GATE: !isKeyExist(Version), ALT: () => { $.SUBRULE($.version) } },
{ GATE: !isKeyExist(Env), ALT: () => { $.SUBRULE($.env) } }
]);
}
}) it is still a work in progress and I haven't built the visitor yet, but I was wondering if I got it wrong and it is not the parser responsibility to enforce distinct keys but the visitor's. or maybe there is a standard way of doing it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
If you are parsing a CST, it is simpler to check this in a second pass. This allows you to output much more helpful errors. Use the https://chevrotain.io/docs/tutorial/step3a_adding_actions_visitor.html#the-cst-visitor to add a check to the relevant node. |
Beta Was this translation helpful? Give feedback.
If you are parsing a CST, it is simpler to check this in a second pass. This allows you to output much more helpful errors.
Use the https://chevrotain.io/docs/tutorial/step3a_adding_actions_visitor.html#the-cst-visitor to add a check to the relevant node.