From 3a7d50924d190896053a20a783a758da237100bf Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Tue, 7 Oct 2025 22:59:50 +0200 Subject: [PATCH] refactor: add op_precedence to express & with desugar_ops --- packages/mondo/mondo.mjs | 36 ++++++++---------------------------- 1 file changed, 8 insertions(+), 28 deletions(-) diff --git a/packages/mondo/mondo.mjs b/packages/mondo/mondo.mjs index d419eaff4..00a3b4011 100644 --- a/packages/mondo/mondo.mjs +++ b/packages/mondo/mondo.mjs @@ -21,14 +21,14 @@ export class MondoParser { close_curly: /^\}/, number: /^-?[0-9]*\.?[0-9]+/, // before pipe! // TODO: better error handling when "-" is used as rest, e.g "s [- bd]" - op: /^[*/:!@%?+-]|^\.{2}/, // * / : ! @ % ? .. - and: /^&/, + op: /^[*\/:!@%?+\-&]|^\.{2}/, // * / : ! @ % ? .. // dollar: /^\$/, pipe: /^#/, stack: /^[,$]/, or: /^[|]/, plain: /^[a-zA-Z0-9-~_^#]+/, }; + op_precedence = [['*', '/', ':', '!', '@', '%', '?', '+', '-', '..'], ['&']]; // matches next token next_token(code, offset = 0) { for (let type in this.token_types) { @@ -151,30 +151,9 @@ export class MondoParser { } return children; } - desugar_ands(children) { + desugar_ops(children, types) { while (true) { - let opIndex = children.findIndex((child) => child.type === 'and'); - if (opIndex === -1) break; - if (opIndex === children.length - 1) { - throw new Error(`cannot use & as last child.`); - } - if (opIndex === 0) { - throw new Error(`cannot use & as first child.`); - } - // convert infix to prefix notation - const op = { type: 'plain', value: children[opIndex].value }; - const left = children[opIndex - 1]; - const right = children[opIndex + 1]; - const call = { type: 'list', children: [op, right, left] }; - // insert call while keeping other siblings - children = [...children.slice(0, opIndex - 1), call, ...children.slice(opIndex + 2)]; - children = this.unwrap_children(children); - } - return children; - } - desugar_ops(children) { - while (true) { - let opIndex = children.findIndex((child) => child.type === 'op'); + let opIndex = children.findIndex((child) => child.type === 'op' && types.includes(child.value)); if (opIndex === -1) break; const op = { type: 'plain', value: children[opIndex].value }; if (opIndex === children.length - 1) { @@ -285,9 +264,10 @@ export class MondoParser { // the type we've removed before splitting needs to be added back children = [{ type: 'plain', value: type }, ...children]; } - children = this.desugar_ops(children); - children = this.desugar_ands(children); - // children = this.desugar_pipes(children, (children) => this.desugar_dollars(children)); + // for each precendence group, call desugar_ops once + this.op_precedence.forEach((ops) => { + children = this.desugar_ops(children, ops); + }); children = this.desugar_pipes(children); return children; }),