// SPDX-License-Identifier: GPL-3.0-or-later // Copyright (C) 2026 ZiroEDA and contributors. // Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md. /** * `include/libeval_compiler/libeval_compiler.h` + * `common/libeval_compiler/libeval_compiler.cpp` + `grammar.lemon`: the * expression language of the custom DRC rules — tokenizer, parser, the * TREE_NODE tree, code generation to UOPs, and the stack machine that runs * them. * * The C++ parser is `grammar.c`, generated by lemon from grammar.lemon. What * is here is that grammar as a precedence-climbing parser building the SAME * TREE_NODE tree the lemon actions build (`newNode` per rule action, the * same op codes, the same leaf layout), with the lemon precedence table * followed exactly — including its oddities: `&&` binds LOOSER than `||`, * comparisons and `.` are nonassoc (a second one in a row is a syntax * error), `!` is right-associative at a level between comparisons and `+`. * * `srcPos` of a node is the compiler's source position when the node is * made, which for a lemon reduction is the start of the lookahead token; * this parser makes the node once it has seen the token after the * construct, so the positions the error messages subtract from agree. */ import { DoubleValueFromString, type EdaUnits } from '../eda_units.js'; import { wildCompareString } from '../string_utils.js'; export const TR_OP_BINARY_MASK = 0x200; export const TR_OP_UNARY_MASK = 0x100; export const TR_OP_MUL = 0x201; export const TR_OP_DIV = 0x202; export const TR_OP_ADD = 0x203; export const TR_OP_SUB = 0x204; export const TR_OP_LESS = 0x205; export const TR_OP_GREATER = 0x206; export const TR_OP_LESS_EQUAL = 0x207; export const TR_OP_GREATER_EQUAL = 0x208; export const TR_OP_EQUAL = 0x209; export const TR_OP_NOT_EQUAL = 0x20a; export const TR_OP_BOOL_AND = 0x20b; export const TR_OP_BOOL_OR = 0x20c; export const TR_OP_BOOL_NOT = 0x100; export const TR_OP_FUNC_CALL = 24; export const TR_OP_METHOD_CALL = 25; export const TR_UOP_PUSH_VAR = 1; export const TR_UOP_PUSH_VALUE = 2; export enum COMPILATION_STAGE { CST_PARSE = 0, CST_CODEGEN, CST_RUNTIME, } export interface ERROR_STATUS { pendingError: boolean; stage: COMPILATION_STAGE; message: string; srcPos: number; } export enum VAR_TYPE_T { VT_STRING = 1, VT_NUMERIC, VT_NUMERIC_DOUBLE, VT_UNDEFINED, VT_PARSE_ERROR, VT_NULL, } export enum TOKEN_TYPE_T { TR_UNDEFINED = 0, TR_NUMBER = 1, TR_IDENTIFIER = 2, TR_ASSIGN = 3, TR_STRUCT_REF = 4, TR_STRING = 5, TR_UNIT = 6, TR_ARG_LIST = 7, TR_NULL = 8, } /** The terminals of grammar.lemon (`grammar.h`). */ export enum G_TOKEN { G_ENDS = 0, G_IDENTIFIER, G_ASSIGN, G_SEMCOL, G_COMMA, G_BOOL_AND, G_BOOL_OR, G_BOOL_XOR, G_LESS_THAN, G_GREATER_THAN, G_LESS_EQUAL_THAN, G_GREATER_EQUAL_THAN, G_EQUAL, G_NOT_EQUAL, G_BOOL_NOT, G_PLUS, G_MINUS, G_DIVIDE, G_MULT, G_STRUCT_REF, G_UNIT, G_VALUE, G_STRING, G_PARENL, G_PARENR, } export type FUNC_CALL_REF = ((aCtx: CONTEXT, aSelf: VAR_REF | null) => void) | null; export interface T_TOKEN_VALUE { str: string | null; num: number; idx: number; } // Lemon can't handle c'tors and d'tors, so we provide a poor-man's version. export const defaultTokenValue: T_TOKEN_VALUE = { str: null, num: 0.0, idx: 0 }; export interface T_TOKEN { token: number; value: T_TOKEN_VALUE; } export class TREE_NODE { value: T_TOKEN_VALUE = { str: null, num: 0, idx: 0 }; op = 0; leaf: [TREE_NODE | null, TREE_NODE | null] = [null, null]; uop: UOP | null = null; valid = false; isTerminal = false; isVisited = false; srcPos = 0; SetUop(aOp: number, aValue: number, aUnits: EdaUnits): void; SetUop(aOp: number, aValue: string, aStringIsWildcard: boolean): void; SetUop(aOp: number, aRef?: VAR_REF | null): void; SetUop(aOp: number, aFunc: FUNC_CALL_REF, aRef?: VAR_REF | null): void; SetUop( aOp: number, a?: number | string | VAR_REF | FUNC_CALL_REF | null, b?: EdaUnits | boolean | VAR_REF | null, ): void { this.uop = null; if (typeof a === 'number') { const val = new VALUE(a); val.SetUnits(b as EdaUnits); this.uop = new UOP(aOp, val); } else if (typeof a === 'string') { const val = new VALUE(a, b as boolean); this.uop = new UOP(aOp, val); } else if (typeof a === 'function') { this.uop = UOP.MethodCall(aOp, a, (b as VAR_REF | null) ?? null); } else { this.uop = UOP.VarRef(aOp, (a as VAR_REF | null) ?? null); } } } export function newNode( compiler: COMPILER, op: number, value: T_TOKEN_VALUE = defaultTokenValue, ): TREE_NODE { const t2 = new TREE_NODE(); t2.valid = true; t2.value.str = value.str !== null ? value.str : null; t2.value.num = value.num; t2.value.idx = value.idx; t2.op = op; t2.leaf[0] = null; t2.leaf[1] = null; t2.isTerminal = false; t2.srcPos = compiler.GetSourcePos(); t2.uop = null; compiler.GcItem(t2); return t2; } function formatOpName(op: number): string { const simpleOps: [number, string][] = [ [TR_OP_MUL, 'MUL'], [TR_OP_DIV, 'DIV'], [TR_OP_ADD, 'ADD'], [TR_OP_SUB, 'SUB'], [TR_OP_LESS, 'LESS'], [TR_OP_GREATER, 'GREATER'], [TR_OP_LESS_EQUAL, 'LESS_EQUAL'], [TR_OP_GREATER_EQUAL, 'GREATER_EQUAL'], [TR_OP_EQUAL, 'EQUAL'], [TR_OP_NOT_EQUAL, 'NEQUAL'], [TR_OP_BOOL_AND, 'AND'], [TR_OP_BOOL_OR, 'OR'], [TR_OP_BOOL_NOT, 'NOT'], ]; for (const [o, mnemonic] of simpleOps) { if (o === op) return mnemonic; } return '???'; } export class UNIT_RESOLVER { GetSupportedUnits(): readonly string[] { return UNIT_RESOLVER.nullUnits; } private static readonly nullUnits: readonly string[] = []; GetSupportedUnitsTypes(): readonly EdaUnits[] { return UNIT_RESOLVER.nullUnitTypes; } private static readonly nullUnitTypes: readonly EdaUnits[] = []; GetSupportedUnitsMessage(): string { return ''; } Convert(_aString: string, _unitType: number): number { return 0.0; } } export class VALUE { private m_type: VAR_TYPE_T; private m_valueDbl: number; // mutable to support deferred evaluation private m_valueStr: string; // mutable to support deferred evaluation private m_stringIsWildcard: boolean; private m_isDeferredDbl: boolean; private m_lambdaDbl: (() => number) | null = null; private m_isDeferredStr: boolean; private m_lambdaStr: (() => string) | null = null; private m_units: EdaUnits; constructor(); constructor(aStr: string, aIsWildcard?: boolean); constructor(aVal: number); constructor(a?: string | number, aIsWildcard = false) { if (typeof a === 'string') { this.m_type = VAR_TYPE_T.VT_STRING; this.m_valueDbl = 0; this.m_valueStr = a; this.m_stringIsWildcard = aIsWildcard; } else if (typeof a === 'number') { this.m_type = VAR_TYPE_T.VT_NUMERIC; this.m_valueDbl = a; this.m_valueStr = ''; this.m_stringIsWildcard = false; } else { this.m_type = VAR_TYPE_T.VT_UNDEFINED; this.m_valueDbl = 0; this.m_valueStr = ''; this.m_stringIsWildcard = false; } this.m_isDeferredDbl = false; this.m_isDeferredStr = false; this.m_units = 'unscaled'; } static MakeNullValue(): VALUE { const v = new VALUE(); v.m_type = VAR_TYPE_T.VT_NULL; return v; } AsDouble(): number { if (this.m_isDeferredDbl) { this.m_valueDbl = this.m_lambdaDbl!(); this.m_isDeferredDbl = false; } return this.m_valueDbl; } AsString(): string { if (this.m_isDeferredStr) { this.m_valueStr = this.m_lambdaStr!(); this.m_isDeferredStr = false; } return this.m_valueStr; } EqualTo(aCtx: CONTEXT, b: VALUE): boolean { if (this.m_type === VAR_TYPE_T.VT_UNDEFINED || b.m_type === VAR_TYPE_T.VT_UNDEFINED) return false; if (this.m_type === VAR_TYPE_T.VT_NULL && b.m_type === VAR_TYPE_T.VT_NULL) return true; if (this.m_type === VAR_TYPE_T.VT_NUMERIC && b.m_type === VAR_TYPE_T.VT_NUMERIC) { return this.AsDouble() === b.AsDouble(); } else if (this.m_type === VAR_TYPE_T.VT_STRING && b.m_type === VAR_TYPE_T.VT_STRING) { if (b.m_stringIsWildcard) return wildCompareString(b.AsString(), this.AsString(), false); else return this.AsString().toLowerCase() === b.AsString().toLowerCase(); } return false; } // NB: this is not an inverse of EqualTo as they both return false for undefined values. NotEqualTo(aCtx: CONTEXT, b: VALUE): boolean { if (this.m_type === VAR_TYPE_T.VT_UNDEFINED || b.m_type === VAR_TYPE_T.VT_UNDEFINED) return false; return !this.EqualTo(aCtx, b); } GetType(): VAR_TYPE_T { return this.m_type; } Set(aValue: number): void; Set(aValue: string): void; Set(val: VALUE): void; Set(a: number | string | VALUE): void { if (typeof a === 'number') { this.m_type = VAR_TYPE_T.VT_NUMERIC; this.m_valueDbl = a; } else if (typeof a === 'string') { this.m_type = VAR_TYPE_T.VT_STRING; this.m_valueStr = a; } else { this.m_type = a.m_type; this.m_valueDbl = a.m_valueDbl; if (this.m_type === VAR_TYPE_T.VT_STRING) this.m_valueStr = a.m_valueStr; } } /** `SetDeferredEval( std::function )` */ SetDeferredEvalDbl(aLambda: () => number): void { this.m_type = VAR_TYPE_T.VT_NUMERIC; this.m_lambdaDbl = aLambda; this.m_isDeferredDbl = true; } /** `SetDeferredEval( std::function )` */ SetDeferredEvalStr(aLambda: () => string): void { this.m_type = VAR_TYPE_T.VT_STRING; this.m_lambdaStr = aLambda; this.m_isDeferredStr = true; } SetUnits(aUnits: EdaUnits): void { this.m_units = aUnits; } GetUnits(): EdaUnits { return this.m_units; } StringIsWildcard(): boolean { return this.m_stringIsWildcard; } } export abstract class VAR_REF { abstract GetType(): VAR_TYPE_T; abstract GetValue(aCtx: CONTEXT): VALUE; } export class CONTEXT { private m_ownedValues: VALUE[] = []; private m_stack: (VALUE | null)[] = new Array(100).fill(null); // std::stack not performant enough private m_stackPtr = 0; private m_errorCallback: ((aMessage: string, aOffset: number) => void) | null = null; AllocValue(): VALUE { const v = new VALUE(); this.m_ownedValues.push(v); return v; } StoreValue(aValue: VALUE): VALUE { this.m_ownedValues.push(aValue); return aValue; } Push(v: VALUE | null): void { this.m_stack[this.m_stackPtr++] = v; } Pop(): VALUE | null { if (this.m_stackPtr === 0) { this.ReportError('Malformed expression'); return this.AllocValue(); } return this.m_stack[--this.m_stackPtr]!; } SP(): number { return this.m_stackPtr; } SetErrorCallback(aCallback: ((aMessage: string, aOffset: number) => void) | null): void { this.m_errorCallback = aCallback; } HasErrorCallback(): boolean { return this.m_errorCallback !== null; } ReportError(aErrorMsg: string): void { if (this.m_errorCallback) this.m_errorCallback(aErrorMsg, -1); } } export class UCODE { protected m_ucode: UOP[] = []; AddOp(uop: UOP): void { this.m_ucode.push(uop); } Run(ctx: CONTEXT): VALUE { try { for (const op of this.m_ucode) op.Exec(ctx); } catch { // rules which fail outright should not be fired; return 0/false return ctx.StoreValue(new VALUE(0)); } if (ctx.SP() === 1) { return ctx.Pop()!; } else { // If stack is corrupted after execution it suggests a problem with the compiler, not // the rule.... // do not use "assert"; it crashes outright on OSX console.assert(ctx.SP() === 1); // non-well-formed rules should not be fired on a release build return ctx.StoreValue(new VALUE(0)); } } Dump(): string { let rv = ''; for (const op of this.m_ucode) { rv += op.Format(); rv += '\n'; } return rv; } CreateVarRef(_aVar: string, _aField: string): VAR_REF | null { return null; } CreateFuncCall(_aName: string): FUNC_CALL_REF { return null; } } export class UOP { private m_op: number; private m_func: FUNC_CALL_REF = null; private m_ref: VAR_REF | null = null; private m_value: VALUE | null = null; /** `UOP( int op, std::unique_ptr value )` */ constructor(op: number, value: VALUE | null) { this.m_op = op; this.m_value = value; } /** `UOP( int op, std::unique_ptr vref )` */ static VarRef(op: number, vref: VAR_REF | null): UOP { const u = new UOP(op, null); u.m_ref = vref; return u; } /** `UOP( int op, FUNC_CALL_REF func, std::unique_ptr vref = nullptr )` */ static MethodCall(op: number, func: FUNC_CALL_REF, vref: VAR_REF | null = null): UOP { const u = new UOP(op, null); u.m_func = func; u.m_ref = vref; return u; } Exec(ctx: CONTEXT): void { switch (this.m_op) { case TR_UOP_PUSH_VAR: { let value: VALUE | null = null; if (this.m_ref) value = ctx.StoreValue(this.m_ref.GetValue(ctx)); else value = ctx.AllocValue(); ctx.Push(value); break; } case TR_UOP_PUSH_VALUE: ctx.Push(this.m_value); return; case TR_OP_METHOD_CALL: if (this.m_func) this.m_func(ctx, this.m_ref); return; default: break; } const AS_DOUBLE = (arg: VALUE | null): number => (arg ? arg.AsDouble() : 0.0); if (this.m_op & TR_OP_BINARY_MASK) { const arg2 = ctx.Pop(); const arg1 = ctx.Pop(); let result: number; if (ctx.HasErrorCallback()) { if ( arg1 && arg1.GetType() === VAR_TYPE_T.VT_STRING && arg2 && arg2.GetType() === VAR_TYPE_T.VT_NUMERIC ) { ctx.ReportError( `Type mismatch between '${arg1.AsString()}' and ${formatLf(arg2.AsDouble())}`, ); } else if ( arg1 && arg1.GetType() === VAR_TYPE_T.VT_NUMERIC && arg2 && arg2.GetType() === VAR_TYPE_T.VT_STRING ) { ctx.ReportError( `Type mismatch between ${formatLf(arg1.AsDouble())} and '${arg2.AsString()}'`, ); } } // TODO: This doesn't fully calculate units correctly yet. We really need to work out the dimensional analysis // TODO: (and do this independently of unit specifics - e.g. MM + INCH needs to return one of the dimension // TODO: types, but our units framework doesn't currently allow this. Therefore, use some heuristics to // TODO: determine the resulting operation unit type for now const getOpResultUnits = (aVal1: VALUE | null, aVal2: VALUE | null): EdaUnits => { if (!(aVal1 && aVal2)) return 'unscaled'; // This condition can occur in, e.g., a unary negation operation if (aVal1.GetUnits() === 'unscaled' && aVal2.GetUnits() !== 'unscaled') return aVal2.GetUnits(); if (aVal1.GetUnits() !== 'unscaled' && aVal2.GetUnits() === 'unscaled') return aVal1.GetUnits(); return aVal2.GetUnits(); }; let resultUnits: EdaUnits = 'unscaled'; switch (this.m_op) { case TR_OP_ADD: result = AS_DOUBLE(arg1) + AS_DOUBLE(arg2); resultUnits = getOpResultUnits(arg1, arg2); break; case TR_OP_SUB: result = AS_DOUBLE(arg1) - AS_DOUBLE(arg2); resultUnits = getOpResultUnits(arg1, arg2); break; case TR_OP_MUL: result = AS_DOUBLE(arg1) * AS_DOUBLE(arg2); resultUnits = getOpResultUnits(arg1, arg2); break; case TR_OP_DIV: result = AS_DOUBLE(arg1) / AS_DOUBLE(arg2); resultUnits = getOpResultUnits(arg1, arg2); break; case TR_OP_LESS_EQUAL: result = AS_DOUBLE(arg1) <= AS_DOUBLE(arg2) ? 1 : 0; break; case TR_OP_GREATER_EQUAL: result = AS_DOUBLE(arg1) >= AS_DOUBLE(arg2) ? 1 : 0; break; case TR_OP_LESS: result = AS_DOUBLE(arg1) < AS_DOUBLE(arg2) ? 1 : 0; break; case TR_OP_GREATER: result = AS_DOUBLE(arg1) > AS_DOUBLE(arg2) ? 1 : 0; break; case TR_OP_EQUAL: if (!arg1 || !arg2) result = arg1 === arg2 ? 1 : 0; else if (arg2.GetType() === VAR_TYPE_T.VT_UNDEFINED) result = arg2.EqualTo(ctx, arg1) ? 1 : 0; else result = arg1.EqualTo(ctx, arg2) ? 1 : 0; break; case TR_OP_NOT_EQUAL: if (!arg1 || !arg2) result = arg1 !== arg2 ? 1 : 0; else if (arg2.GetType() === VAR_TYPE_T.VT_UNDEFINED) result = arg2.NotEqualTo(ctx, arg1) ? 1 : 0; else result = arg1.NotEqualTo(ctx, arg2) ? 1 : 0; break; case TR_OP_BOOL_AND: result = AS_DOUBLE(arg1) !== 0.0 && AS_DOUBLE(arg2) !== 0.0 ? 1 : 0; break; case TR_OP_BOOL_OR: result = AS_DOUBLE(arg1) !== 0.0 || AS_DOUBLE(arg2) !== 0.0 ? 1 : 0; break; default: result = 0.0; break; } const rp = ctx.AllocValue(); rp.Set(result); rp.SetUnits(resultUnits); ctx.Push(rp); return; } else if (this.m_op & TR_OP_UNARY_MASK) { const arg1 = ctx.Pop(); const ARG1VALUE = arg1 ? arg1.AsDouble() : 0.0; let result: number; const resultUnits: EdaUnits = arg1 ? arg1.GetUnits() : 'unscaled'; switch (this.m_op) { case TR_OP_BOOL_NOT: result = ARG1VALUE !== 0.0 ? 0 : 1; break; default: result = ARG1VALUE !== 0.0 ? 1 : 0; break; } const rp = ctx.AllocValue(); rp.Set(result); rp.SetUnits(resultUnits); ctx.Push(rp); return; } } Format(): string { let str: string; switch (this.m_op) { case TR_UOP_PUSH_VAR: str = 'PUSH VAR [ref]'; break; case TR_UOP_PUSH_VALUE: if (!this.m_value) str = 'PUSH nullptr'; else if (this.m_value.GetType() === VAR_TYPE_T.VT_NUMERIC) str = `PUSH NUM [${this.m_value.AsDouble().toFixed(10)}]`; else str = `PUSH STR [${this.m_value.AsString()}]`; break; case TR_OP_METHOD_CALL: str = 'MCALL'; break; case TR_OP_FUNC_CALL: str = 'FCALL'; break; default: str = `${formatOpName(this.m_op)} ${this.m_op}`; break; } return str; } } /** printf's `%lf` */ function formatLf(v: number): string { return v.toFixed(6); } export class TOKENIZER { private m_str = ''; private m_pos = 0; Restart(aStr: string): void { this.m_str = aStr; this.m_pos = 0; } Clear(): void { this.m_str = ''; this.m_pos = 0; } GetChar(): number { if (this.m_pos >= this.m_str.length) return 0; return this.m_str.charCodeAt(this.m_pos); } Done(): boolean { return this.m_pos >= this.m_str.length; } NextChar(aAdvance = 1): void { this.m_pos += aAdvance; } GetPos(): number { return this.m_pos; } GetString(): string { let rv = ''; while (this.m_pos < this.m_str.length && this.m_str[this.m_pos] !== "'") { if ( this.m_str[this.m_pos] === '\\' && this.m_pos + 1 < this.m_str.length && this.m_str[this.m_pos + 1] === "'" ) this.m_pos++; rv += this.m_str[this.m_pos++]; } this.m_pos++; return rv; } GetChars(cond: (c: number) => boolean): string { let rv = ''; let p = this.m_pos; while (p < this.m_str.length && cond(this.m_str.charCodeAt(p))) { rv += this.m_str[p]; p++; } return rv; } MatchAhead(match: string, stopCond: (c: number) => boolean): boolean { const remaining = this.m_str.length - this.m_pos; if (remaining < match.length) return false; if (this.m_str.substr(this.m_pos, match.length) === match) return ( remaining === match.length || stopCond(this.m_str.charCodeAt(this.m_pos + match.length)) ); return false; } } // on a wxUniChar cast to int: ASCII classes only const isdigit = (c: number): boolean => c >= 0x30 && c <= 0x39; const isalpha = (c: number): boolean => (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a); const isalnum = (c: number): boolean => isdigit(c) || isalpha(c); enum LEXER_STATE { LS_DEFAULT = 0, LS_STRING = 1, } /** A token with the source position the compiler held when it was read. */ interface LEXED { tok: T_TOKEN; pos: number; } /** `pEval->parseError( "Syntax error" )`, thrown out of the parser. */ class SYNTAX_ERROR extends Error {} /** * The grammar.lemon precedence table, lowest first. The lemon rule gets the * precedence of its last terminal with one; a token not in the table has none. */ enum ASSOC { LEFT, RIGHT, NONASSOC, } const PREC_COMMA = 1; const PREC_BOOL_AND = 2; const PREC_BOOL_OR = 3; // const PREC_BOOL_XOR = 4; // no rule uses G_BOOL_XOR const PREC_COMPARE = 5; const PREC_BOOL_NOT = 6; const PREC_ADDITIVE = 7; const PREC_MULTIPLICATIVE = 8; const PREC_STRUCT_REF = 9; // const PREC_UNIT = 10; // `nt ::= G_VALUE G_UNIT` is handled at the primary interface BINARY_OP { prec: number; assoc: ASSOC; /** The TREE_NODE op the rule's action makes. */ op: number; } const BINARY_OPS: Partial> = { [G_TOKEN.G_COMMA]: { prec: PREC_COMMA, assoc: ASSOC.LEFT, op: TOKEN_TYPE_T.TR_ARG_LIST }, [G_TOKEN.G_BOOL_AND]: { prec: PREC_BOOL_AND, assoc: ASSOC.LEFT, op: TR_OP_BOOL_AND }, [G_TOKEN.G_BOOL_OR]: { prec: PREC_BOOL_OR, assoc: ASSOC.LEFT, op: TR_OP_BOOL_OR }, [G_TOKEN.G_LESS_THAN]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_LESS }, [G_TOKEN.G_GREATER_THAN]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_GREATER }, [G_TOKEN.G_LESS_EQUAL_THAN]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_LESS_EQUAL }, [G_TOKEN.G_GREATER_EQUAL_THAN]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_GREATER_EQUAL, }, [G_TOKEN.G_EQUAL]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_EQUAL }, [G_TOKEN.G_NOT_EQUAL]: { prec: PREC_COMPARE, assoc: ASSOC.NONASSOC, op: TR_OP_NOT_EQUAL }, [G_TOKEN.G_PLUS]: { prec: PREC_ADDITIVE, assoc: ASSOC.LEFT, op: TR_OP_ADD }, [G_TOKEN.G_MINUS]: { prec: PREC_ADDITIVE, assoc: ASSOC.LEFT, op: TR_OP_SUB }, [G_TOKEN.G_MULT]: { prec: PREC_MULTIPLICATIVE, assoc: ASSOC.LEFT, op: TR_OP_MUL }, [G_TOKEN.G_DIVIDE]: { prec: PREC_MULTIPLICATIVE, assoc: ASSOC.LEFT, op: TR_OP_DIV }, [G_TOKEN.G_STRUCT_REF]: { prec: PREC_STRUCT_REF, assoc: ASSOC.NONASSOC, op: TOKEN_TYPE_T.TR_STRUCT_REF, }, }; export class COMPILER { protected m_lexerState: LEXER_STATE = LEXER_STATE.LS_DEFAULT; protected m_tokenizer = new TOKENIZER(); protected m_localeDecimalSeparator = '.'; protected m_unitResolver: UNIT_RESOLVER = new UNIT_RESOLVER(); protected m_sourcePos = 0; protected m_parseFinished = false; protected m_errorStatus: ERROR_STATUS = { pendingError: false, stage: COMPILATION_STAGE.CST_PARSE, message: '', srcPos: 0, }; protected m_errorCallback: ((aMessage: string, aOffset: number) => void) | null = null; protected m_tree: TREE_NODE | null = null; protected m_gcItems: TREE_NODE[] = []; /** The lemon parser's state: the tokens read so far and the one being looked at. */ private m_tokens: LEXED[] = []; private m_tokenIndex = 0; /* * clear() should be invoked by the client if a new input string is to be processed. It * will reset the parser. User defined variables are retained. */ Clear(): void { this.m_tokenizer.Clear(); if (this.m_tree) { this.freeTree(this.m_tree); this.m_tree = null; } this.m_tree = null; this.m_gcItems = []; this.m_tokens = []; this.m_tokenIndex = 0; } /* Used by the lemon parser */ parseError(s: string): void { this.reportError(COMPILATION_STAGE.CST_PARSE, s); } parseOk(): void { this.m_parseFinished = true; } GetSourcePos(): number { return this.m_sourcePos; } setRoot(root: TREE_NODE): void { this.m_tree = root; } freeTree(tree: TREE_NODE): void { if (tree.leaf[0]) this.freeTree(tree.leaf[0]); if (tree.leaf[1]) this.freeTree(tree.leaf[1]); tree.uop = null; } Compile(aString: string, aCode: UCODE, aPreflightContext: CONTEXT): boolean { // Feed parser token after token until end of input. this.newString(aString); if (this.m_tree) { this.freeTree(this.m_tree); this.m_tree = null; } this.m_tree = null; this.m_parseFinished = false; if (aString.length === 0) { this.m_parseFinished = true; return this.generateUCode(aCode, aPreflightContext); } // The lemon parser consumes the tokens as they are lexed and reports a // syntax error at the token it cannot take; ours lexes on demand from the // same stream and throws at that token. A lexer error stops it just as the // C++'s pending-error check after each token does. try { this.parseInput(); } catch (e) { if (!(e instanceof SYNTAX_ERROR)) throw e; } if (this.m_errorStatus.pendingError) return false; return this.generateUCode(aCode, aPreflightContext); } SetErrorCallback(aCallback: ((aMessage: string, aOffset: number) => void) | null): void { this.m_errorCallback = aCallback; } IsErrorPending(): boolean { return this.m_errorStatus.pendingError; } GetError(): ERROR_STATUS { return this.m_errorStatus; } GcItem(aItem: TREE_NODE): void { this.m_gcItems.push(aItem); } protected reportError(stage: COMPILATION_STAGE, aErrorMsg: string, aPos = -1): void { if (aPos === -1) aPos = this.m_sourcePos; this.m_errorStatus.pendingError = true; this.m_errorStatus.stage = stage; this.m_errorStatus.message = aErrorMsg; this.m_errorStatus.srcPos = aPos; if (this.m_errorCallback) this.m_errorCallback(aErrorMsg, aPos); } /* Begin processing of a new input string */ protected newString(aString: string): void { this.Clear(); this.m_lexerState = LEXER_STATE.LS_DEFAULT; this.m_tokenizer.Restart(aString); this.m_parseFinished = false; } /* Tokenizer: Next token/value taken from input string. */ protected getToken(): T_TOKEN { const rv: T_TOKEN = { token: 0, value: { ...defaultTokenValue } }; let done = false; do { switch (this.m_lexerState) { case LEXER_STATE.LS_DEFAULT: done = this.lexDefault(rv); break; case LEXER_STATE.LS_STRING: done = this.lexString(rv); break; } } while (!done); return rv; } protected lexString(aToken: T_TOKEN): boolean { aToken.token = G_TOKEN.G_STRING; aToken.value.str = this.m_tokenizer.GetString(); this.m_lexerState = LEXER_STATE.LS_DEFAULT; return true; } protected resolveUnits(): number { let unitId = 0; for (const unitName of this.m_unitResolver.GetSupportedUnits()) { if (this.m_tokenizer.MatchAhead(unitName, (c: number): boolean => !isalnum(c))) { this.m_tokenizer.NextChar(unitName.length); return unitId; } unitId++; } return -1; } protected lexDefault(aToken: T_TOKEN): boolean { const retval: T_TOKEN = { token: G_TOKEN.G_ENDS, value: { str: null, num: 0.0, idx: -1 } }; let current = ''; let convertFrom: number; if (this.m_tokenizer.Done()) { aToken.token = retval.token; aToken.value = retval.value; return true; } const isDecimalSeparator = (ch: number): boolean => ch === this.m_localeDecimalSeparator.charCodeAt(0) || ch === 0x2e || ch === 0x2c; // Lambda: get value as string, store into clToken.token and update current index. const extractNumber = (): void => { let haveSeparator = false; let ch = this.m_tokenizer.GetChar(); do { if (isDecimalSeparator(ch) && haveSeparator) break; current += String.fromCharCode(ch); if (isDecimalSeparator(ch)) haveSeparator = true; this.m_tokenizer.NextChar(); ch = this.m_tokenizer.GetChar(); } while (isdigit(ch) || isDecimalSeparator(ch)); // Ensure that the systems decimal separator is used let fixed = ''; for (let i = 0; i < current.length; i++) { fixed += isDecimalSeparator(current.charCodeAt(i)) ? this.m_localeDecimalSeparator : current[i]; } current = fixed; }; let ch: number; // Start processing of first/next token: Remove whitespace for (;;) { ch = this.m_tokenizer.GetChar(); if (ch === 0x20) this.m_tokenizer.NextChar(); else break; } if (ch === 0) { /* End of input */ } else if (isdigit(ch)) { // VALUE extractNumber(); retval.token = G_TOKEN.G_VALUE; retval.value.str = current; } else if ( // biome-ignore lint/suspicious/noAssignInExpressions: the C++'s `( convertFrom = resolveUnits() ) >= 0` (convertFrom = this.resolveUnits()) >= 0 ) { // UNIT // Units are appended to a VALUE. // Determine factor to default unit if unit for value is given. // Example: Default is mm, unit is inch: factor is 25.4 // The factor is assigned to the terminal UNIT. The actual // conversion is done within a parser action. retval.token = G_TOKEN.G_UNIT; retval.value.idx = convertFrom; } else if (ch === 0x27) { // string literal this.m_lexerState = LEXER_STATE.LS_STRING; this.m_tokenizer.NextChar(); return false; } else if (isalpha(ch) || ch === 0x5f) { current = this.m_tokenizer.GetChars((c: number): boolean => isalnum(c) || c === 0x5f); retval.token = G_TOKEN.G_IDENTIFIER; retval.value.str = current; this.m_tokenizer.NextChar(current.length); } else if (this.m_tokenizer.MatchAhead('==', (c: number): boolean => c !== 0x3d)) { retval.token = G_TOKEN.G_EQUAL; this.m_tokenizer.NextChar(2); } else if (this.m_tokenizer.MatchAhead('!=', (c: number): boolean => c !== 0x3d)) { retval.token = G_TOKEN.G_NOT_EQUAL; this.m_tokenizer.NextChar(2); } else if (this.m_tokenizer.MatchAhead('<=', (c: number): boolean => c !== 0x3d)) { retval.token = G_TOKEN.G_LESS_EQUAL_THAN; this.m_tokenizer.NextChar(2); } else if (this.m_tokenizer.MatchAhead('>=', (c: number): boolean => c !== 0x3d)) { retval.token = G_TOKEN.G_GREATER_EQUAL_THAN; this.m_tokenizer.NextChar(2); } else if (this.m_tokenizer.MatchAhead('&&', (c: number): boolean => c !== 0x26)) { retval.token = G_TOKEN.G_BOOL_AND; this.m_tokenizer.NextChar(2); } else if (this.m_tokenizer.MatchAhead('||', (c: number): boolean => c !== 0x7c)) { retval.token = G_TOKEN.G_BOOL_OR; this.m_tokenizer.NextChar(2); } else { // Single char tokens switch (String.fromCharCode(ch)) { case '+': retval.token = G_TOKEN.G_PLUS; break; case '!': retval.token = G_TOKEN.G_BOOL_NOT; break; case '-': retval.token = G_TOKEN.G_MINUS; break; case '*': retval.token = G_TOKEN.G_MULT; break; case '/': retval.token = G_TOKEN.G_DIVIDE; break; case '<': retval.token = G_TOKEN.G_LESS_THAN; break; case '>': retval.token = G_TOKEN.G_GREATER_THAN; break; case '(': retval.token = G_TOKEN.G_PARENL; break; case ')': retval.token = G_TOKEN.G_PARENR; break; case ';': retval.token = G_TOKEN.G_SEMCOL; break; case '.': retval.token = G_TOKEN.G_STRUCT_REF; break; case ',': retval.token = G_TOKEN.G_COMMA; break; default: if (this.m_tokenizer.MatchAhead('${', (c: number): boolean => c !== 0x7b)) this.reportError( COMPILATION_STAGE.CST_PARSE, 'Unresolved text variable reference', this.m_sourcePos + 2, ); else this.reportError( COMPILATION_STAGE.CST_PARSE, `Unrecognized character '${String.fromCharCode(ch)}'`, ); break; } this.m_tokenizer.NextChar(); } aToken.token = retval.token; aToken.value = retval.value; return true; } // ----- the parser: grammar.lemon -------------------------------------------- /** The lemon driver loop's read of the next token: `m_sourcePos = GetPos(); tok = getToken()`. */ private lexNext(): LEXED { this.m_sourcePos = this.m_tokenizer.GetPos(); const tok = this.getToken(); const lexed = { tok, pos: this.m_sourcePos }; this.m_tokens.push(lexed); if (this.m_errorStatus.pendingError) throw new SYNTAX_ERROR(); return lexed; } /** The lookahead token, lexing it if the parser has not looked yet. */ private peek(): LEXED { while (this.m_tokenIndex >= this.m_tokens.length) this.lexNext(); const t = this.m_tokens[this.m_tokenIndex]!; // the compiler's position is where the lookahead was read: a reduction // makes its nodes there this.m_sourcePos = t.pos; return t; } private advance(): LEXED { const t = this.peek(); this.m_tokenIndex++; return t; } private syntaxError(at: LEXED): never { this.m_sourcePos = at.pos; this.parseError('Syntax error'); throw new SYNTAX_ERROR(); } /** * main ::= in. in ::= stmt | in stmt. stmt ::= G_ENDS | nt G_ENDS. * * G_ENDS is only ever the last token, so the input is one expression, or * nothing, before it. */ private parseInput(): void { const first = this.peek(); if (first.tok.token !== G_TOKEN.G_ENDS) { const root = this.parseExpr(0); const end = this.peek(); if (end.tok.token !== G_TOKEN.G_ENDS) this.syntaxError(end); this.advance(); this.setRoot(root); } else { this.advance(); } this.parseOk(); } /** The `nt` rules with a binary operator, by precedence climbing. */ private parseExpr(aMinPrec: number): TREE_NODE { let lhs = this.parsePrefix(); let lastNonassoc = -1; for (;;) { const look = this.peek(); const bin = BINARY_OPS[look.tok.token as G_TOKEN]; if (!bin || bin.prec < aMinPrec) return lhs; // a nonassoc operator following one of the same precedence is a // conflict lemon resolves as a syntax error if (bin.assoc === ASSOC.NONASSOC && bin.prec === lastNonassoc) this.syntaxError(look); this.advance(); const rhs = this.parseExpr(bin.assoc === ASSOC.RIGHT ? bin.prec : bin.prec + 1); // the reduction: the node is made with the lookahead in hand this.peek(); const node = newNode(this, bin.op); node.leaf[0] = lhs; node.leaf[1] = rhs; lhs = node; lastNonassoc = bin.assoc === ASSOC.NONASSOC ? bin.prec : -1; } } /** The prefix and primary `nt` rules. */ private parsePrefix(): TREE_NODE { const t = this.peek(); switch (t.tok.token) { case G_TOKEN.G_BOOL_NOT: { // nt ::= G_BOOL_NOT nt. (%right, above the comparisons) this.advance(); const B = this.parseExpr(PREC_BOOL_NOT); this.peek(); const A = newNode(this, TR_OP_BOOL_NOT); A.leaf[0] = B; return A; } case G_TOKEN.G_PLUS: { // nt ::= G_PLUS nt. (the rule has G_PLUS's precedence, %left) this.advance(); const B = this.parseExpr(PREC_ADDITIVE + 1); this.peek(); const A = newNode(this, B.op, B.value); A.leaf[0] = B.leaf[0]; A.leaf[1] = B.leaf[1]; return A; } case G_TOKEN.G_MINUS: { // nt ::= G_MINUS nt. this.advance(); const B = this.parseExpr(PREC_ADDITIVE + 1); this.peek(); const A = newNode(this, TR_OP_SUB); A.leaf[0] = newNode(this, TOKEN_TYPE_T.TR_NUMBER); A.leaf[1] = B; return A; } case G_TOKEN.G_PARENL: { // nt ::= G_PARENL nt G_PARENR. this.advance(); const B = this.parseExpr(0); const close = this.peek(); if (close.tok.token !== G_TOKEN.G_PARENR) this.syntaxError(close); this.advance(); this.peek(); const A = newNode(this, B.op, B.value); A.leaf[0] = B.leaf[0]; A.leaf[1] = B.leaf[1]; return A; } case G_TOKEN.G_VALUE: { // nt ::= G_VALUE. nt ::= G_VALUE G_UNIT. const B = this.advance(); const next = this.peek(); if (next.tok.token === G_TOKEN.G_UNIT) { const C = this.advance(); this.peek(); const A = newNode(this, TOKEN_TYPE_T.TR_NUMBER, B.tok.value); A.leaf[0] = newNode(this, TOKEN_TYPE_T.TR_UNIT, C.tok.value); return A; } return newNode(this, TOKEN_TYPE_T.TR_NUMBER, B.tok.value); } case G_TOKEN.G_STRING: { // nt ::= G_STRING. const B = this.advance(); this.peek(); return newNode(this, TOKEN_TYPE_T.TR_STRING, B.tok.value); } case G_TOKEN.G_IDENTIFIER: { // nt ::= G_IDENTIFIER. // nt ::= G_IDENTIFIER G_PARENL nt G_PARENR. // nt ::= G_IDENTIFIER G_PARENL G_PARENR. const F = this.advance(); const next = this.peek(); if (next.tok.token === G_TOKEN.G_PARENL) { this.advance(); const inner = this.peek(); let B: TREE_NODE; if (inner.tok.token === G_TOKEN.G_PARENR) { this.advance(); this.peek(); B = newNode(this, TOKEN_TYPE_T.TR_NULL); } else { B = this.parseExpr(0); const close = this.peek(); if (close.tok.token !== G_TOKEN.G_PARENR) this.syntaxError(close); this.advance(); this.peek(); } const A = newNode(this, TR_OP_FUNC_CALL); A.leaf[0] = newNode(this, TOKEN_TYPE_T.TR_IDENTIFIER, F.tok.value); A.leaf[1] = B; return A; } return newNode(this, TOKEN_TYPE_T.TR_IDENTIFIER, F.tok.value); } default: return this.syntaxError(t); } } // ----- code generation ------------------------------------------------------ protected generateUCode(aCode: UCODE, aPreflightContext: CONTEXT): boolean { const stack: TREE_NODE[] = []; let msg: string; let numericValueCount = 0; let missingUnitsMsg = ''; let missingUnitsSrcPos = 0; if (!this.m_tree) { const val = new VALUE(1.0); // Empty expression returns true aCode.AddOp(new UOP(TR_UOP_PUSH_VALUE, val)); return true; } prepareTree(this.m_tree); stack.push(this.m_tree); while (stack.length > 0) { const node = stack[stack.length - 1]!; // process terminal nodes first switch (node.op) { case TR_OP_FUNC_CALL: // Function call's uop was generated inside TR_STRUCT_REF if (!node.uop) { // This function call is bare so we don't know who to apply it to // Set a safe default value to exit gracefully with an error this.reportError( COMPILATION_STAGE.CST_CODEGEN, 'Unknown parent of function parameters', node.srcPos, ); node.SetUop(TR_UOP_PUSH_VALUE, 0.0, 'unscaled'); } node.isTerminal = true; break; case TOKEN_TYPE_T.TR_STRUCT_REF: { // leaf[0]: object // leaf[1]: field (TR_IDENTIFIER) or TR_OP_FUNC_CALL if (node.leaf[0]!.op !== TOKEN_TYPE_T.TR_IDENTIFIER) { let pos = node.leaf[0]!.srcPos; if (node.leaf[0]!.value.str) pos -= formatNode(node.leaf[0]!).length; this.reportError(COMPILATION_STAGE.CST_CODEGEN, 'Unknown parent of property', pos); node.leaf[0]!.isVisited = true; node.leaf[1]!.isVisited = true; node.SetUop(TR_UOP_PUSH_VALUE, 0.0, 'unscaled'); node.isTerminal = true; break; } switch (node.leaf[1]!.op) { case TOKEN_TYPE_T.TR_IDENTIFIER: { // leaf[0]: object // leaf[1]: field const itemName = formatNode(node.leaf[0]!); const propName = formatNode(node.leaf[1]!); const vref = aCode.CreateVarRef(itemName, propName); if (!vref) { msg = `Unrecognized item '${itemName}'`; this.reportError( COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[0]!.srcPos - itemName.length, ); } else if (vref.GetType() === VAR_TYPE_T.VT_PARSE_ERROR) { msg = `Unrecognized property '${propName}'`; this.reportError( COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[1]!.srcPos - propName.length, ); } node.leaf[0]!.isVisited = true; node.leaf[1]!.isVisited = true; node.SetUop(TR_UOP_PUSH_VAR, vref); node.isTerminal = true; break; } case TR_OP_FUNC_CALL: { // leaf[0]: object // leaf[1]: TR_OP_FUNC_CALL // leaf[0]: function name // leaf[1]: parameter const itemName = formatNode(node.leaf[0]!); const vref = aCode.CreateVarRef(itemName, ''); if (!vref) { msg = `Unrecognized item '${itemName}'`; this.reportError( COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[0]!.srcPos - itemName.length, ); } const functionName = formatNode(node.leaf[1]!.leaf[0]!); const func = aCode.CreateFuncCall(functionName); const params = squashParamList(node.leaf[1]!.leaf[1]); if (!func) { msg = `Unrecognized function '${functionName}'`; this.reportError(COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[0]!.srcPos + 1); } if (func) { // Preflight the function call for (const pnode of params) { const param = aPreflightContext.AllocValue(); param.Set(formatNode(pnode)); aPreflightContext.Push(param); } aPreflightContext.SetErrorCallback((aMessage: string, _aOffset: number) => { const loc = node.leaf[1]!.leaf[1]!.srcPos; this.reportError(COMPILATION_STAGE.CST_CODEGEN, aMessage, loc - 1); }); try { func(aPreflightContext, vref); aPreflightContext.Pop(); // return value } catch { // the C++ swallows whatever the preflight throws } } node.leaf[0]!.isVisited = true; node.leaf[1]!.isVisited = true; node.leaf[1]!.leaf[0]!.isVisited = true; node.leaf[1]!.leaf[1]!.isVisited = true; // Our non-terminal-node stacking algorithm can't handle doubly-nested // structures so we need to pop a level by replacing the TR_STRUCT_REF with // a TR_OP_FUNC_CALL and its function parameter stack.pop(); stack.push(node.leaf[1]!); for (const pnode of params) stack.push(pnode); node.leaf[1]!.SetUop(TR_OP_METHOD_CALL, func, vref); node.isTerminal = false; break; } default: { // leaf[0]: object // leaf[1]: malformed syntax const itemName = formatNode(node.leaf[0]!); const propName = formatNode(node.leaf[1]!); const vref = aCode.CreateVarRef(itemName, propName); if (!vref) { msg = `Unrecognized item '${itemName}'`; this.reportError( COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[0]!.srcPos - itemName.length, ); } msg = `Unrecognized property '${propName}'`; this.reportError(COMPILATION_STAGE.CST_CODEGEN, msg, node.leaf[0]!.srcPos + 1); node.leaf[0]!.isVisited = true; node.leaf[1]!.isVisited = true; node.SetUop(TR_UOP_PUSH_VALUE, 0.0, 'unscaled'); node.isTerminal = true; break; } } break; } case TOKEN_TYPE_T.TR_NUMBER: { const son = node.leaf[0]; let value: number; let unitsType: EdaUnits = 'unscaled'; if (node.value.str === null) { value = 0.0; } else if (son && son.op === TOKEN_TYPE_T.TR_UNIT) { if (this.m_unitResolver.GetSupportedUnits().length === 0) { msg = `Unexpected units for '${formatNode(node)}'`; this.reportError(COMPILATION_STAGE.CST_CODEGEN, msg, node.srcPos); } const units = son.value.idx; unitsType = this.m_unitResolver.GetSupportedUnitsTypes()[units]!; value = this.m_unitResolver.Convert(formatNode(node), units); son.isVisited = true; } else { if (this.m_unitResolver.GetSupportedUnitsMessage().length > 0) { missingUnitsMsg = `Missing units for '${formatNode(node)}'| (${this.m_unitResolver.GetSupportedUnitsMessage()})`; missingUnitsSrcPos = node.srcPos; } value = DoubleValueFromString(formatNode(node)); } node.SetUop(TR_UOP_PUSH_VALUE, value, unitsType); node.isTerminal = true; numericValueCount++; break; } case TOKEN_TYPE_T.TR_STRING: { const str = formatNode(node); const isWildcard = str.includes('?') || str.includes('*'); node.SetUop(TR_UOP_PUSH_VALUE, str, isWildcard); node.isTerminal = true; break; } case TOKEN_TYPE_T.TR_IDENTIFIER: { const vref = aCode.CreateVarRef(formatNode(node), ''); if (!vref) { msg = `Unrecognized item '${formatNode(node)}'`; this.reportError( COMPILATION_STAGE.CST_CODEGEN, msg, node.srcPos - formatNode(node).length, ); } node.SetUop(TR_UOP_PUSH_VAR, vref); node.isTerminal = true; break; } default: node.SetUop(node.op); node.isTerminal = (!node.leaf[0] || node.leaf[0].isVisited) && (!node.leaf[1] || node.leaf[1].isVisited); break; } if (!node.isTerminal) { if (node.leaf[0] && !node.leaf[0].isVisited) { stack.push(node.leaf[0]); node.leaf[0].isVisited = true; } else if (node.leaf[1] && !node.leaf[1].isVisited) { stack.push(node.leaf[1]); node.leaf[1].isVisited = true; } continue; } node.isVisited = true; if (node.uop) { aCode.AddOp(node.uop); node.uop = null; } stack.pop(); } // Report the common error condition of a single numeric value with no units (which will result in // nanometers, and rarely leads to anything useful). // Reporting missing units with multiple numeric values is far more complicated as we have to // separate comparison operators from multiplicative operators from additive operators. Consider: // 2 * 1.5mm // 2mm + 105um // 2mm > 20um // (2mm + 1.5mm) * 3 if (missingUnitsMsg.length > 0 && numericValueCount === 1) this.reportError(COMPILATION_STAGE.CST_CODEGEN, missingUnitsMsg, missingUnitsSrcPos); return true; } } export function formatNode(node: TREE_NODE): string { return node.value.str !== null ? node.value.str : ''; } export function dumpNode(buf: { s: string }, tok: TREE_NODE | null, depth = 0): void { if (!tok) return; buf.s += `\n[node L0:${tok.leaf[0] ? 'x' : '-'} L1:${tok.leaf[1] ? 'x' : '-'}] `; for (let i = 0; i < 2 * depth; i++) buf.s += ' '; if (tok.op & TR_OP_BINARY_MASK) { buf.s += formatOpName(tok.op); dumpNode(buf, tok.leaf[0], depth + 1); dumpNode(buf, tok.leaf[1], depth + 1); } switch (tok.op) { case TOKEN_TYPE_T.TR_NUMBER: buf.s += 'NUMERIC: '; buf.s += formatNode(tok); if (tok.leaf[0]) dumpNode(buf, tok.leaf[0], depth + 1); break; case TOKEN_TYPE_T.TR_ARG_LIST: buf.s += 'ARG_LIST: '; buf.s += formatNode(tok); if (tok.leaf[0]) dumpNode(buf, tok.leaf[0], depth + 1); if (tok.leaf[1]) dumpNode(buf, tok.leaf[1], depth + 1); break; case TOKEN_TYPE_T.TR_STRING: buf.s += 'STRING: '; buf.s += formatNode(tok); break; case TOKEN_TYPE_T.TR_IDENTIFIER: buf.s += 'ID: '; buf.s += formatNode(tok); break; case TOKEN_TYPE_T.TR_STRUCT_REF: buf.s += 'SREF: '; dumpNode(buf, tok.leaf[0], depth + 1); dumpNode(buf, tok.leaf[1], depth + 1); break; case TR_OP_FUNC_CALL: buf.s += "CALL '"; buf.s += formatNode(tok.leaf[0]!); buf.s += "': "; dumpNode(buf, tok.leaf[1], depth + 1); break; case TOKEN_TYPE_T.TR_UNIT: buf.s += `UNIT: ${tok.value.idx} `; break; } } function prepareTree(node: TREE_NODE): void { node.isVisited = false; // fixme: for reasons I don't understand the lemon parser isn't initializing the // leaf node pointers of function name nodes. -JY if (node.op === TR_OP_FUNC_CALL && node.leaf[0]) { node.leaf[0].leaf[0] = null; node.leaf[0].leaf[1] = null; } if (node.leaf[0]) prepareTree(node.leaf[0]); if (node.leaf[1]) prepareTree(node.leaf[1]); } function squashParamList(root: TREE_NODE | null): TREE_NODE[] { const args: TREE_NODE[] = []; if (!root) return args; if (root.op !== TOKEN_TYPE_T.TR_ARG_LIST && root.op !== TOKEN_TYPE_T.TR_NULL) { args.push(root); } else { let n: TREE_NODE | null = root; do { if (n.leaf[1]) args.push(n.leaf[1]); n = n.leaf[0]; } while (n && n.op === TOKEN_TYPE_T.TR_ARG_LIST); if (n) args.push(n); } args.reverse(); return args; }