122 lines
7.1 KiB
JavaScript
122 lines
7.1 KiB
JavaScript
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
// The program a compiled reference of the library is run as (scripts/library.mjs harness): it holds no case. Its
|
|
// cases arrive at run time on one line of stdin, so no runner's answer is the compiler working out a call on
|
|
// literal arguments while it builds (Mojo folds such a call with arithmetic of its own; built with contraction on,
|
|
// its fold does not fuse a multiply-add as the built code does: library/mojo/probes/float-contract-runtime). The
|
|
// line carries every value exactly.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { checkMojo } from '../dist/mojo/check.js';
|
|
import { runMojo } from '../dist/mojo/interp.js';
|
|
import { harness, harnessInput, floatWords, referencePrograms } from '../scripts/library.mjs';
|
|
|
|
/** Another value of the same type: other numbers, other text, a list one item longer. */
|
|
function other(v, t) {
|
|
switch (t?.k) {
|
|
case 'FLOAT': return Number(v) * 3 + 1.5;
|
|
case 'INTEGER': return typeof v === 'bigint' ? v + 7n : Number(v) + 7;
|
|
case 'BOOL': return !v;
|
|
case 'CHAR': return v === 'Q' ? 'R' : 'Q';
|
|
case 'STRING': return `${v}x y`;
|
|
case 'LIST': case 'ARRAY': { const xs = Array.isArray(v) ? v : v?.data ?? []; return [...xs.map((x) => other(x, t.of)), other(xs[0] ?? (t.of.k === 'STRING' ? '' : 0), t.of)]; }
|
|
default: throw new Error(`no other value for ${t?.k}`);
|
|
}
|
|
}
|
|
|
|
test('a compiled reference\'s program is the same whatever its cases are: they arrive on stdin', async () => {
|
|
const programs = (await referencePrograms()).filter((p) => p.ref.lang === 'mojo' || p.ref.lang === 'c');
|
|
assert.ok(programs.filter((p) => p.ref.lang === 'mojo').length >= 17, 'every Mojo reference');
|
|
assert.ok(programs.filter((p) => p.ref.lang === 'c').length >= 4, 'every C reference');
|
|
for (const p of programs) {
|
|
const id = `${p.id} ${p.ref.lang}/${p.ref.level}`;
|
|
const src = p.make();
|
|
const changed = p.calls.map((c) => ({ args: c.args.map((v, i) => other(v, p.sub.params[i].type)) }));
|
|
assert.equal(harness(p.ref.lang, p.ref, p.fname, p.sub, changed), src, `${id}: the program changes with the cases' arguments, so they are written into it`);
|
|
assert.equal(harness(p.ref.lang, p.ref, p.fname, p.sub, p.calls.slice(0, 1)), src, `${id}: the program changes with the number of cases`);
|
|
assert.notEqual(harnessInput(p.ref.lang, p.sub, changed), p.input(), `${id}: the input line does not carry the arguments`);
|
|
assert.match(p.input(), new RegExp(`^${p.calls.length} .* end\\n$`), id);
|
|
assert.ok(src.includes(p.ref.source.replace(/\s+$/, '')), `${id}: the reference's own text is in its program unchanged`);
|
|
}
|
|
});
|
|
|
|
test('a FLOAT is sent as m and e with x = m * 2^e exactly, m odd and below 2^53', () => {
|
|
const dv = new DataView(new ArrayBuffer(8));
|
|
const xs = [0.1, 1e-16, 1e300, 5e-324, 2.2250738585072014e-308, -1.5, 1, 2 ** 53 + 2, Number.MAX_VALUE];
|
|
for (let i = 0; i < 2000; i++) { dv.setUint32(0, (Math.random() * 2 ** 32) >>> 0); dv.setUint32(4, (Math.random() * 2 ** 32) >>> 0); const x = dv.getFloat64(0); if (Number.isFinite(x)) xs.push(x); }
|
|
for (const x of xs) {
|
|
const [m, e] = floatWords(x);
|
|
const big = BigInt(m);
|
|
assert.ok((big < 0n ? -big : big) < 2n ** 53n && (big % 2n !== 0n), `${x}: m = ${m}`);
|
|
assert.equal(Number(big) * 2 ** Number(e), x, `${x}: ${m} * 2^${e}`);
|
|
}
|
|
assert.deepEqual(floatWords(-0), ['-0', '0']);
|
|
assert.deepEqual(floatWords(Infinity), ['1', '1024']);
|
|
assert.throws(() => floatWords(NaN));
|
|
});
|
|
|
|
// A routine taking every kind of argument a reference can, and cases with the values a line could mangle
|
|
const EVERY = { params: ['FLOAT', 'INTEGER', 'BOOL', 'STRING', { k: 'LIST', of: { k: 'FLOAT' } }, { k: 'LIST', of: { k: 'STRING' } }].map((k) => ({ type: typeof k === 'string' ? { k } : k })), returns: { k: 'STRING' } };
|
|
const CASES = [
|
|
{ args: [0.1, -5, true, 'a b', [1e-16, -0, 5e-324], ['', '100%', 'x%20y']] },
|
|
{ args: [1e300, 4611686018427387904n, false, '', [], ['tab\there', 'end']] },
|
|
{ args: [-Infinity, 0, true, ' ', [2.5], []] },
|
|
];
|
|
|
|
test('core\'s Mojo interpreter runs a harness with every kind of argument and gets each value back exactly', () => {
|
|
const ref = { source: `def every(x: Float64, n: Int, b: Bool, s: String, xs: List[Float64], ss: List[String]) -> String:
|
|
var out = String(x) + "|" + String(n) + "|" + String(b) + "|[" + s + "]|"
|
|
for i in range(len(xs)):
|
|
out += String(xs[i]) + ","
|
|
out += "|"
|
|
for i in range(len(ss)):
|
|
out += "[" + ss[i] + "]"
|
|
return out
|
|
` };
|
|
const src = harness('mojo', ref, 'every', EVERY, CASES);
|
|
const ck = checkMojo(src);
|
|
assert.deepEqual(ck.diagnostics.filter((d) => d.severity === 'error').map((d) => `L${d.line} ${d.message}`), []);
|
|
const run = runMojo(ck.module, src, { input: [harnessInput('mojo', EVERY, CASES).replace(/\n$/, '')], maxSteps: 400000 });
|
|
assert.ok(!run.refused, `the interpreter declines ${run.refused}`);
|
|
assert.equal(run.exitCode, 0, run.stdout);
|
|
assert.equal(run.stdout, [
|
|
'0.1|-5|True|[a b]|1e-16,-0.0,5e-324,|[][100%][x%20y]',
|
|
'1e+300|4611686018427387904|False|[]||[tab\there][end]',
|
|
'-inf|0|True|[ ]|2.5,|',
|
|
].join('\n') + '\n');
|
|
// a line that holds more or fewer words than its cases announce stops the program
|
|
const short = runMojo(ck.module, src, { input: ['1 1 0'], maxSteps: 400000 });
|
|
assert.notEqual(short.exitCode, 0);
|
|
});
|
|
|
|
test('a C harness gets each value back exactly, at -O0 and -O2', (t) => {
|
|
if (spawnSync('cc', ['--version']).status !== 0) { assert.ok(!process.env.CI, 'cc is not installed, and CI must run this'); t.skip('no cc'); return; }
|
|
const sub = { params: ['FLOAT', 'INTEGER', 'STRING', 'CHAR', { k: 'LIST', of: { k: 'FLOAT' } }].map((k) => ({ type: typeof k === 'string' ? { k } : k })), returns: { k: 'INTEGER' } };
|
|
const ref = { source: `long every(double x, long n, const char *s, char c, const double *xs, long count) {
|
|
printf("%.17g %ld [%s] %c", x, n, s, c);
|
|
for (long i = 0; i < count; i++) printf(" %.17g", xs[i]);
|
|
printf(" | ");
|
|
return count;
|
|
}
|
|
` };
|
|
const cases = [
|
|
{ args: [0.1, -5, 'a b%', 'Z', [1e-16, -0, 5e-324]] },
|
|
{ args: [-Infinity, 4611686018427387904n, '', ' ', []] },
|
|
];
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-harness-'));
|
|
try {
|
|
fs.writeFileSync(path.join(dir, 'every.c'), harness('c', ref, 'every', sub, cases));
|
|
for (const level of ['-O0', '-O2']) {
|
|
const c = spawnSync('cc', ['-std=c11', '-Wall', '-Wextra', '-Werror', level, '-o', path.join(dir, 'every'), path.join(dir, 'every.c'), '-lm'], { encoding: 'utf8' });
|
|
assert.equal(c.status, 0, c.stderr);
|
|
const r = spawnSync(path.join(dir, 'every'), [], { input: harnessInput('c', sub, cases), encoding: 'utf8' });
|
|
assert.equal(r.status, 0, r.stderr);
|
|
assert.equal(r.stdout, '0.10000000000000001 -5 [a b%] Z 9.9999999999999998e-17 -0 4.9406564584124654e-324 | 3\n-inf 4611686018427387904 [] | 0\n', level);
|
|
}
|
|
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
|
});
|