tricu

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

expression.ts (1520B)


      1 import { sourceLiteral, compiledDefinitions, compilerDescriptor, COMPILER_EXPORT } from '../compiler.js';
      2 import { fetchBytes, fetchBundle, loadBundle, COMPILER_BUNDLE_LIMIT } from '../bundle.js';
      3 import { list, text } from '../codecs.js';
      4 import type { Graph, NodeId } from '../graph.js';
      5 
      6 import { expressionUnit, expressionDiagnostic } from '../expression.js';
      7 export async function compileExpression(graph: Graph, definitions: ReadonlyMap<string, NodeId>, input: unknown): Promise<NodeId> {
      8   const unit = expressionUnit(input, definitions.keys());
      9   const base = new URL('../../', import.meta.url);
     10   const descriptor = await fetchBytes(new URL('compiler.json', base), 4096);
     11   const { hash } = compilerDescriptor(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(descriptor)) as unknown);
     12   const library = loadBundle(graph, await fetchBundle(new URL(`/_arboricx/bundle/hash/${hash}`, base), hash, COMPILER_BUNDLE_LIMIT));
     13   const compiler = library.get(COMPILER_EXPORT);
     14   if (compiler === undefined) throw new Error('Missing stable compiler entrypoint');
     15   const environment = list(graph, [...definitions].map(([name, tree]) => graph.fork(text(graph, name), tree)));
     16   try {
     17     const values = compiledDefinitions(graph, graph.apply(compiler, [environment, sourceLiteral(graph, unit.source)]));
     18     if (values.size !== 1 || !values.has(unit.name)) throw new Error('Enter one expression, not a source unit');
     19     return values.get(unit.name)!;
     20   } catch (error) { throw expressionDiagnostic(error); }
     21 }