tricu

An interpreted language for exploring Tree Calculus
Log | Files | Refs | README | LICENSE

expression.ts (1049B)


      1 import { sourceText } from './compiler.js';
      2 
      3 // Use the shipped definition compiler, not a second expression parser. Preserve
      4 // relative layout and isolate the expression in a single, collision-free binding.
      5 export function expressionUnit(input: unknown, names: Iterable<string>): { name: string; source: string } {
      6   const expression = sourceText(input), occupied = new Set(names);
      7   let i = 0, name: string;
      8   do { name = `browserExpression${i++}`; } while (occupied.has(name) || expression.includes(name));
      9   return { name, source: sourceText(`${name} = (\n${expression.split('\n').map(line => '  ' + line).join('\n')}\n)`) };
     10 }
     11 export function expressionDiagnostic(error: unknown): unknown {
     12   if (!(error instanceof Error) || !/Compiler diagnostic \d+ at \d+:\d+/.test(error.message)) return error;
     13   return new Error(error.message.replace(/(Compiler diagnostic \d+) at (\d+):(\d+)/,
     14     (_match, label: string, line: string, column: string) => `${label} at expression ${Math.max(1, Number(line) - 1)}:${Math.max(1, Number(column) - 2)}`));
     15 }