tricu

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

expression.js (1463B)


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