Skip to content

Commit

Permalink
Revise term output function
Browse files Browse the repository at this point in the history
  • Loading branch information
robsimmons committed Aug 9, 2024
1 parent 5257a1a commit b12c6ec
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
16 changes: 16 additions & 0 deletions src/termoutput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { test, expect } from 'vitest';
import { dataToTerm, termToData, termToString } from './termoutput.js';

test('termToString', () => {
expect(termToString(dataToTerm(termToData(null)))).toBe('()');
expect(termToString(dataToTerm(termToData(-12)))).toBe('-12');
expect(termToString(dataToTerm(termToData(12n)))).toBe('12');
expect(termToString(dataToTerm(termToData(false)))).toBe('bool#false');
expect(termToString(dataToTerm(termToData('hello world')))).toBe('"hello world"');
expect(
termToString(
dataToTerm(termToData({ name: 's', args: [{ name: 's', args: [{ name: 'z' }] }] })),
),
).toBe('s (s z)');
expect(termToString(dataToTerm(termToData({ name: 'const', args: [] })))).toBe('const');
});
27 changes: 11 additions & 16 deletions src/termoutput.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Data, TRIVIAL, expose, hide } from './datastructures/data.js';
import { Data, TRIVIAL, escapeString, expose, hide } from './datastructures/data.js';

export type Term =
| null // Trivial type ()
Expand Down Expand Up @@ -52,19 +52,14 @@ export function termToData(tm: InputTerm): Data {
return hide({ type: 'int', value: BigInt(tm) });
}

export function termToString(t: Term) {
let s = '';
if (t.name) {
s += t.name;
}
if (t.args) {
s = '(' + s;
for (const t2 of t.args) s += ' ' + termToString(t2);
s += ')';
}
if (!t.name && !t.args) {
// it's a base type like int or string that js already knows how to print
return t;
}
return s;
export function termToString(tm: Term, parens = false): String {

Check failure on line 55 in src/termoutput.ts

View workflow job for this annotation

GitHub Actions / run-static-tests

Don't use `String` as a type. Use string instead
if (tm === null) return '()';
if (typeof tm === 'boolean') return `bool#${tm}`;
if (typeof tm === 'string') return `"${escapeString(tm)}"`;
if (typeof tm === 'bigint') return `${tm}`;
if (tm.name === null) return `ref#${tm.value}`;
if (!tm.args) return tm.name;
const tmStr = `${tm.name} ${tm.args.map((arg) => termToString(arg, true)).join('')}`;
if (!parens) return tmStr;
return `(${tmStr})`;
}

0 comments on commit b12c6ec

Please sign in to comment.