527 lines
37 KiB
JavaScript
527 lines
37 KiB
JavaScript
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
// Stage 4: pseudo -> Mojo. The generated Mojo must be accepted by the checker, run in the interpreter, and
|
|
// print what the pseudo prints; its style is pinned by a snapshot per exercise; every standard-library name
|
|
// it writes is in the harvested index. Programs it cannot yet hold to that are listed below, each with its reason.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { EXERCISES } from '../dist/exercises/index.js';
|
|
import { studyOf, runPseudo } from '../dist/services/pseudo.js';
|
|
import { checkMojo } from '../dist/mojo/check.js';
|
|
import { runMojo } from '../dist/mojo/interp.js';
|
|
import { pseudoToMojo, GENERATED_HEADER, USED_STDLIB, USED_PRELUDE } from '../dist/sync/pseudo-to-mojo.js';
|
|
import { formatAsMojo, sameOutput, outputDistance } from '../dist/sync/compare.js';
|
|
import { MOJO_STD_EXPORTS } from '../dist/mojo/generated/stdlib.js';
|
|
import { MOJO_STD_STRUCTS } from '../dist/mojo/generated/types.js';
|
|
|
|
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const corpusDir = path.join(here, '..', 'library', 'pseudo', 'programs');
|
|
const snapDir = path.join(here, 'snapshots', 'sync-mojo');
|
|
|
|
/**
|
|
* Programs that do not (yet) get the full check, and why. A program leaves this list when it passes;
|
|
* the test fails if a listed program passes, so the list can only shrink.
|
|
* declined: the Mojo interpreter declines the construct (it declines what it has not been verified
|
|
* against godbolt on); the translation is still checked, and the run is not.
|
|
* differs: the notation and Mojo disagree by design, and a literal translation keeps Mojo's behavior.
|
|
* checker: the checker's error is the right answer for what the pseudo says.
|
|
*/
|
|
const KNOWN_GAPS = {
|
|
'23-dice.pseudo': ['declined', 'random_si64 draws from Mojo\'s own generator, whose numbers the interpreter cannot know'],
|
|
'42-numerics.pseudo': ['declined', 'sin is Mojo\'s own routine (or the C library\'s), not reproduced digit for digit'],
|
|
'46-projectile.pseudo': ['declined', 'cos is Mojo\'s own routine (or the C library\'s), not reproduced digit for digit'],
|
|
'47-binomial-and-ph.pseudo': ['declined', 'log10 is Mojo\'s own routine, not reproduced digit for digit'],
|
|
'33-stops-div.pseudo': ['differs', 'dividing by zero stops the notation; a Float64 division in Mojo gives nan'],
|
|
'44-parallel-race.pseudo': ['differs', 'the notation detects a data race in PARALLEL FOR; Mojo runs the passes in order and prints a result'],
|
|
'45-parallel-neighbor-race.pseudo': ['differs', 'the notation detects a data race in PARALLEL FOR; Mojo runs the passes in order and prints a result'],
|
|
'50-float32.pseudo': ['gap', 'EXACT has no Mojo spelling: Mojo prints the shortest decimal that rounds back, never the exact value'],
|
|
'51-ieee.pseudo': ['declined', 'log is Mojo\'s own routine, not reproduced digit for digit'],
|
|
'52-elementary.pseudo': ['declined', 'cbrt and the other transcendental functions are Mojo\'s own routines, which the interpreter declines on purpose (docs/trust.md); hypot it runs'],
|
|
'35-stops-unset.pseudo': ['checker', 'the pseudo reads a variable that was never given a value; the checker reports exactly that, as the compiler would'],
|
|
'36-stops-counter.pseudo': ['checker', 'the pseudo reads a FOR counter after its loop, where it has no value; the checker reports exactly that'],
|
|
};
|
|
|
|
/** Programs whose pseudo does not parse, by design. The translator must say so, not crash. */
|
|
const NO_PSEUDO = new Set(['ex:five-bugs', '37-static-errors.pseudo', '41-reserved-name.pseudo']);
|
|
|
|
const AGREE_AT_LEAST = 57; // raise as the interpreter learns more; counted below
|
|
|
|
function programs() {
|
|
const out = [];
|
|
for (const e of EXERCISES) if (e.sources.pseudo) out.push({ id: `ex:${e.id}`, name: e.id, pseudo: e.sources.pseudo, call: e.call ?? null, input: [] });
|
|
for (const f of fs.readdirSync(corpusDir).filter((x) => x.endsWith('.pseudo')).sort()) {
|
|
const src = fs.readFileSync(path.join(corpusDir, f), 'utf8');
|
|
out.push({ id: f, name: f, pseudo: src, call: null, input: [...src.matchAll(/^\/\/ INPUT: (.*)$/gm)].map((m) => m[1]) });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** How one program fares: what the translator, the checker, the interpreter, and the pseudo run say. */
|
|
function judge(p) {
|
|
const st = studyOf(p.pseudo);
|
|
if (!st.ok) return { verdict: 'no-pseudo', result: pseudoToMojo(p.pseudo, { call: p.call }) };
|
|
const tr = runPseudo(st, { call: p.call, input: p.input, maxSteps: 200000 });
|
|
const result = pseudoToMojo(p.pseudo, { call: p.call });
|
|
assert.ok(!('unsupported' in result), `${p.id}: ${JSON.stringify(result.unsupported)}`);
|
|
const gaps = result.notes.filter((n) => n.id === 'translate-gap');
|
|
const checked = checkMojo(result.source);
|
|
const errors = checked.diagnostics.filter((d) => d.severity === 'error');
|
|
if (gaps.length) return { verdict: 'gap', detail: gaps.map((g) => `line ${g.line}: ${g.message}`).join('; '), result };
|
|
if (errors.length) return { verdict: 'checker', detail: errors.map((d) => `L${d.line} ${d.message}`).join(' | '), result };
|
|
const run = runMojo(checked.module, result.source, { input: p.input, maxSteps: 400000 });
|
|
if (run.refused) return { verdict: 'declined', detail: run.refused, result };
|
|
const stops = run.exitCode !== 0 || run.limited;
|
|
if (tr.error) return stops ? { verdict: 'agree', result } : { verdict: 'differs', detail: `pseudo stops (${tr.error.kind}); Mojo ran to the end and printed ${JSON.stringify(run.stdout.slice(0, 80))}`, result };
|
|
if (stops) return { verdict: 'differs', detail: `Mojo stopped (exit ${run.exitCode}); pseudo printed ${JSON.stringify(tr.output.slice(0, 2))}`, result };
|
|
const want = p.call && tr.raw.result !== undefined
|
|
? [...tr.raw.output, formatAsMojo(tr.raw.result)].join('\n')
|
|
: tr.raw.output.join('\n');
|
|
return sameOutput(want, run.stdout)
|
|
? { verdict: 'agree', result }
|
|
: { verdict: 'differs', detail: `pseudo printed ${JSON.stringify(want.slice(0, 100))}, Mojo printed ${JSON.stringify(run.stdout.slice(0, 100))}`, result };
|
|
}
|
|
|
|
const verdicts = new Map();
|
|
test('every exercise and corpus program: the generated Mojo checks, runs, and agrees with the pseudo, or is a listed gap', () => {
|
|
const unexpected = [];
|
|
let agree = 0;
|
|
for (const p of programs()) {
|
|
const j = judge(p);
|
|
verdicts.set(p.id, j);
|
|
if (j.verdict === 'no-pseudo') {
|
|
if (!NO_PSEUDO.has(p.id)) unexpected.push(`${p.id}: the pseudo does not parse, and the program is not listed in NO_PSEUDO`);
|
|
continue;
|
|
}
|
|
if (NO_PSEUDO.has(p.id)) { unexpected.push(`${p.id}: listed in NO_PSEUDO but its pseudo parses`); continue; }
|
|
const known = KNOWN_GAPS[p.id];
|
|
if (j.verdict === 'agree') {
|
|
agree++;
|
|
if (known) unexpected.push(`${p.id}: now agrees; take it off KNOWN_GAPS (${known[1]})`);
|
|
continue;
|
|
}
|
|
if (!known) { unexpected.push(`${p.id}: ${j.verdict}: ${j.detail}`); continue; }
|
|
if (known[0] !== j.verdict) unexpected.push(`${p.id}: listed as ${known[0]} but is ${j.verdict}: ${j.detail}`);
|
|
}
|
|
assert.deepEqual(unexpected, []);
|
|
assert.ok(agree >= AGREE_AT_LEAST, `${agree} programs agree, fewer than ${AGREE_AT_LEAST}`);
|
|
});
|
|
|
|
test('the pseudo that does not parse gets a reason, not a crash', () => {
|
|
for (const id of NO_PSEUDO) {
|
|
const p = programs().find((x) => x.id === id);
|
|
const r = pseudoToMojo(p.pseudo, { call: p.call });
|
|
assert.ok('unsupported' in r, id);
|
|
assert.ok(r.unsupported.length > 0 && r.unsupported.every((d) => d.severity === 'error'), id);
|
|
}
|
|
});
|
|
|
|
test('every exercise with pseudo has its generated Mojo pinned by a snapshot (UPDATE_SNAPSHOTS=1 rewrites them for review)', () => {
|
|
fs.mkdirSync(snapDir, { recursive: true });
|
|
const wanted = new Set();
|
|
for (const p of programs().filter((x) => x.id.startsWith('ex:'))) {
|
|
const r = pseudoToMojo(p.pseudo, { call: p.call });
|
|
if ('unsupported' in r) continue; // five-bugs: its pseudo has mistakes by design
|
|
const file = path.join(snapDir, `${p.name}.mojo`);
|
|
wanted.add(`${p.name}.mojo`);
|
|
if (process.env.UPDATE_SNAPSHOTS) fs.writeFileSync(file, r.source);
|
|
assert.ok(fs.existsSync(file), `no snapshot for ${p.name}; run with UPDATE_SNAPSHOTS=1 and review the new file`);
|
|
assert.equal(r.source, fs.readFileSync(file, 'utf8'), `the generated Mojo for ${p.name} changed; if the change is wanted, run with UPDATE_SNAPSHOTS=1 and review the diff`);
|
|
}
|
|
for (const f of fs.readdirSync(snapDir)) assert.ok(wanted.has(f), `snapshot ${f} belongs to no exercise`);
|
|
});
|
|
|
|
test('the translation is literal: the declare-then-assign, index-loop, and total = total + 1 habits are kept', () => {
|
|
const ex = EXERCISES.find((e) => e.id === 'count-base');
|
|
const r = pseudoToMojo(ex.sources.pseudo, { call: ex.call });
|
|
for (const line of [' var n: Int', ' var total: Int', ' n = t.count_codepoints()', ' total = 0', ' for i in range(n):', ' if String(t[codepoint=i]) == b:', ' total = total + 1', ' return total']) {
|
|
assert.ok(r.source.split('\n').includes(line), `missing: ${line}`);
|
|
}
|
|
assert.ok(!r.source.includes('+='), 'the translator never rewrites total = total + 1');
|
|
});
|
|
|
|
test('the translator does not import or mention the best-practices helper', () => {
|
|
const text = fs.readFileSync(path.join(here, '..', 'src', 'sync', 'pseudo-to-mojo.ts'), 'utf8');
|
|
assert.ok(!/practices/i.test(text), 'src/sync/pseudo-to-mojo.ts refers to the helper');
|
|
});
|
|
|
|
test('every generated source starts with the generated-code header and has a line map that fits', () => {
|
|
for (const p of programs()) {
|
|
const r = pseudoToMojo(p.pseudo, { call: p.call });
|
|
if ('unsupported' in r) continue;
|
|
const lines = r.source.replace(/\n$/, '').split('\n');
|
|
assert.equal(lines[0], GENERATED_HEADER, p.id);
|
|
assert.equal(r.map.length, lines.length, `${p.id}: one map entry per line`);
|
|
assert.equal(r.map[0], null, p.id);
|
|
const pseudoLines = p.pseudo.split('\n').length;
|
|
for (const m of r.map) assert.ok(m === null || (Number.isInteger(m) && m >= 1 && m <= pseudoLines), `${p.id}: map entry ${m}`);
|
|
}
|
|
});
|
|
|
|
test('the map links Mojo lines to the pseudo lines they came from', () => {
|
|
const ex = EXERCISES.find((e) => e.id === 'count-base');
|
|
const r = pseudoToMojo(ex.sources.pseudo, { call: ex.call });
|
|
const lines = r.source.split('\n');
|
|
const pseudo = ex.sources.pseudo.split('\n');
|
|
const at = lines.findIndex((l) => l.includes('total = total + 1'));
|
|
assert.ok(pseudo[r.map[at] - 1].includes('Total <- Total + 1'), pseudo[r.map[at] - 1]);
|
|
});
|
|
|
|
test('grounding: every standard-library name the translator writes is in the harvested index, with the module it imports from', () => {
|
|
const structs = MOJO_STD_STRUCTS;
|
|
const exported = (n) => MOJO_STD_EXPORTS[n] ?? (structs[n] ? 'std' : undefined);
|
|
for (const [name, mod] of Object.entries(USED_STDLIB)) assert.equal(MOJO_STD_EXPORTS[name], mod, `${name} should come from ${mod}`);
|
|
// names the index leaves out are named here, with why: Float64 is a SIMD alias, abs is exported from two modules
|
|
const NOT_INDEXED = { Float64: 'an alias of SIMD', abs: 'exported from two modules, so the index leaves it out', Int: 'a builtin type' };
|
|
for (const name of USED_PRELUDE) assert.ok(exported(name) || NOT_INDEXED[name], `${name} is not in the harvested index`);
|
|
});
|
|
|
|
test('every import in a generated source is one the translator knows, and no import is unused', () => {
|
|
for (const p of programs()) {
|
|
const r = pseudoToMojo(p.pseudo, { call: p.call });
|
|
if ('unsupported' in r) continue;
|
|
const body = r.source.split('\n').filter((l) => !l.startsWith('from ')).join('\n');
|
|
for (const m of r.source.matchAll(/^from (\S+) import (.+)$/gm)) {
|
|
for (const name of m[2].split(', ')) {
|
|
assert.equal(USED_STDLIB[name], m[1], `${p.id}: ${m[0]}`);
|
|
assert.ok(new RegExp(`\\b${name}\\b`).test(body), `${p.id}: ${name} is imported and never used`);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
test('main is written from the call: literals follow the parameter types (TRUE, character literals, floats, lists)', () => {
|
|
const pseudo = `FUNCTION F(B : BOOL, C : CHAR, X : FLOAT, L : LIST OF INTEGER) RETURNS BOOL
|
|
RETURN B AND C == 'A' AND X > 0.5 AND LENGTH(L) > 1
|
|
ENDFUNCTION
|
|
`;
|
|
const r = pseudoToMojo(pseudo, { call: "F(TRUE, 'A', 1, [3, 4])" });
|
|
// a list argument is written in brackets and takes the parameter's type; List[Int](3, 4) is not a constructor (pixi run mojo-local)
|
|
assert.ok(r.source.includes(' print(f(True, "A", 1.0, [3, 4]))'), r.source);
|
|
assert.equal(checkMojo(r.source).diagnostics.filter((d) => d.severity === 'error').length, 0);
|
|
const run = runMojo(checkMojo(r.source).module, r.source, {});
|
|
assert.equal(run.stdout, 'True\n');
|
|
});
|
|
|
|
/**
|
|
* Spellings the pinned compiler asked for. Each was Mojo the checker and the interpreter accepted and the compiler
|
|
* rejected, or Mojo that printed something else than the pseudo; `pixi run mojo-local` and `pixi run mojo-fuzz`
|
|
* found them and hold them. Here the text itself is pinned, so a change to it is seen without a compiler.
|
|
*/
|
|
const mojoOf = (pseudo, call = null) => { const r = pseudoToMojo(pseudo, { call }); assert.ok(!('unsupported' in r), JSON.stringify(r.unsupported)); return r; };
|
|
const has = (r, ...lines) => { for (const l of lines) assert.ok(r.source.split('\n').some((x) => x.trim() === l), `missing: ${l}\n${r.source}`); };
|
|
const gaps = (r) => r.notes.filter((n) => n.id === 'translate-gap');
|
|
|
|
test('a list in brackets takes its type from where it lands; where nothing gives it one, it is named first', () => {
|
|
const r = mojoOf('DECLARE L : LIST OF FLOAT <- [1.5, 2]\nDECLARE G : LIST OF LIST OF INTEGER\nDECLARE N : INTEGER <- 3\nG <- [[1, 2], [N]]\nL <- [N, 0.5]\nOUTPUT LENGTH([4, 5, 6]), " ", SUM_OF([N, N])\nWHILE LENGTH([1, 2]) > N\n N <- N + 1\nENDWHILE\nOUTPUT L, G');
|
|
has(r, 'var l: List[Float64] = [1.5, 2]', 'g = [[1, 2], [n]]', 'l = [Float64(n), 0.5]', 'var _list1: List[Int] = [4, 5, 6]', 'var _list2: List[Int] = [n, n]');
|
|
assert.ok(!/List\[\w+\]\([^)]/.test(r.source), `List[T](a, b) is not a constructor:\n${r.source}`);
|
|
// a list of literals cannot change between two checks of a loop condition, so it may be named ahead of the loop
|
|
assert.deepEqual(gaps(r), []);
|
|
assert.equal(checkMojo(r.source).diagnostics.filter((d) => d.severity === 'error').length, 0);
|
|
assert.equal(runMojo(checkMojo(r.source).module, r.source, {}).stdout, '3 6\n[3.0, 0.5][[1, 2], [3]]\n');
|
|
});
|
|
|
|
test('numbers of both kinds meet the way Mojo lets them: a literal on the left is written in the other side\'s type', () => {
|
|
const r = mojoOf('DECLARE X : FLOAT <- 95.5\nDECLARE S : FLOAT32 <- 0.1\nDECLARE N : INTEGER <- 3\nOUTPUT 90 <= X < 101, " ", 1 == X, " ", -1 < X, " ", 2 ^ X, " ", (-2) ^ 8, " ", (X ^ 2) ^ 3, " ", X ^ 2 ^ 3\nOUTPUT 0.1 == S, " ", N < X <= 100, " ", N IN [0, 5), " ", MIN(100, 1e10), " ", MAX(N, X)\nCASE OF X\n 0 TO 50: OUTPUT "low"\n OTHERWISE: OUTPUT "high"\nENDCASE');
|
|
const text = r.source;
|
|
for (const piece of ['90.0 <= x < 101.0', '1.0 == x', '-1.0 < x', '2.0 ** x', '(-2) ** 8', '(x ** 2) ** 3', 'x ** Float64(2 ** 3)', 'Float32(0.1) == s', 'Float64(n) < x <= 100.0', '0 <= n < 5', 'min(100.0, 10000000000.0)', 'max(Float64(n), x)', 'if 0.0 <= x < 50.0:']) {
|
|
assert.ok(text.includes(piece), `missing: ${piece}\n${text}`);
|
|
}
|
|
});
|
|
|
|
test('ROUND spells out its halves, INT of a number known at compile time goes through Float64, and -0.0 keeps its sign', () => {
|
|
const r = mojoOf('DECLARE X : FLOAT <- 2.5\nOUTPUT ROUND(X), " ", ROUND(7), " ", INT(0.1), " ", INT(PI()), " ", INT(X), " ", COPYSIGN(2.0, -0.0)');
|
|
has(r, 'var _x1 = x', 'var _rounded2 = Int(_x1)', 'if _x1 - Float64(_rounded2) >= 0.5:', '_rounded2 += 1', 'elif _x1 - Float64(_rounded2) <= -0.5:', '_rounded2 -= 1');
|
|
for (const piece of ['Int(Float64(0.1))', 'Int(Float64(pi))', 'Int(x)', 'copysign(Float64(2.0), Float64(-0.0))']) assert.ok(r.source.includes(piece), `missing: ${piece}\n${r.source}`);
|
|
assert.ok(!r.source.includes('round('), 'Mojo\'s round() takes a half to the even neighbor');
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-round'));
|
|
});
|
|
|
|
test('MIN and MAX of a list are loops, a BOOL made into text is TRUE or FALSE, and brackets survive where Mojo binds tighter', () => {
|
|
const r = mojoOf('DECLARE L : LIST OF INTEGER <- [4, 1, 9]\nDECLARE S : STRING <- "ab"\nDECLARE P : BOOL <- TRUE\nOUTPUT MIN(L), " ", MAX(L), " ", TO_STRING(P), " ", LENGTH(S & "c"), " ", BIT_NOT(5 MOD 3), " ", UPPER(S & S), " ", REPLACE("a,b" & "c", ",", S)');
|
|
has(r, 'var _least2 = l[0]', 'if _x1 < _least2:', 'var _most4 = l[0]', 'if _x3 > _most4:');
|
|
for (const piece of ['String("TRUE" if p else "FALSE")', '(s + "c").count_codepoints()', '~(5 % 3)', '(s + s).upper()', 'String("a,b" + "c").replace(",", s)']) assert.ok(r.source.includes(piece), `missing: ${piece}\n${r.source}`);
|
|
// ** binds tighter than ~ as it does than a minus sign
|
|
assert.ok(mojoOf('DECLARE N : INTEGER <- 5\nOUTPUT BIT_NOT(N) ^ 3').source.includes('(~n) ** 3'));
|
|
});
|
|
|
|
test('a variable handed to a BYREF parameter before it has a value starts at zero; one that has a value is left as declared', () => {
|
|
const r = mojoOf('PROCEDURE Half(N : INTEGER, BYREF Out : INTEGER)\n Out <- N DIV 2\nENDPROCEDURE\nDECLARE A : INTEGER\nDECLARE B : INTEGER\nB <- 1\nCALL Half(10, A)\nCALL Half(4, B)\nOUTPUT A, " ", B');
|
|
has(r, 'var a: Int = 0', 'var b: Int', 'b = 1', 'half(10, a)');
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-out-argument'));
|
|
assert.equal(runMojo(checkMojo(r.source).module, r.source, {}).stdout, '5 2\n');
|
|
});
|
|
|
|
test('a record or a list put into a list is a copy of its own', () => {
|
|
const r = mojoOf('TYPE Point\n DECLARE X : INTEGER\nENDTYPE\nDECLARE P : Point\nDECLARE Ps : LIST OF Point\nDECLARE Row : LIST OF INTEGER <- [1]\nDECLARE Grid : LIST OF LIST OF INTEGER\nP.X <- 3\nAPPEND(Ps, P)\nAPPEND(Grid, Row)\nINSERT(Grid, 0, Row)\nOUTPUT LENGTH(Ps), LENGTH(Grid)');
|
|
has(r, 'ps.append(p.copy())', 'grid.append(row.copy())', 'grid.insert(0, row.copy())');
|
|
});
|
|
|
|
test('what the notation computes only sometimes is never written ahead of the line: the right of AND and OR, the end of a chain, a CASE label', () => {
|
|
const guard = mojoOf('DECLARE L : LIST OF FLOAT\nDECLARE N : INTEGER <- 0\nIF N > 0 AND MEAN_OF(L) > 2.0 THEN\n OUTPUT "big"\nENDIF\nOUTPUT "done"');
|
|
assert.equal(gaps(guard).length, 1, 'MEAN_OF is a loop; ahead of the IF it would run where the notation skips it');
|
|
assert.equal(gaps(guard)[0].line, 3);
|
|
const left = mojoOf('DECLARE L : LIST OF FLOAT <- [1.0, 5.0]\nIF MEAN_OF(L) > 2.0 AND LENGTH(L) > 1 THEN\n OUTPUT "big"\nENDIF');
|
|
assert.deepEqual(gaps(left), [], 'the left side is always computed, so its loop may be written first');
|
|
const chain = mojoOf('DECLARE L : LIST OF FLOAT\nDECLARE X : FLOAT <- 1.0\nOUTPUT 2.0 <= X <= MEAN_OF(L)');
|
|
assert.equal(gaps(chain).length, 1);
|
|
const range = mojoOf('DECLARE X : FLOAT <- 0.3\nOUTPUT X IN [0, 12)');
|
|
assert.equal(gaps(range).length, 1, 'a range holds whole numbers: 0.3 IN [0, 12) is FALSE, and 0.0 <= x < 12.0 would say True');
|
|
});
|
|
|
|
test('outputDistance tells a rounding difference from another answer', () => {
|
|
assert.equal(outputDistance('3 TRUE [1, 2]', '3.0 True [1, 2]'), 0);
|
|
assert.equal(outputDistance('infinity -infinity not a number', 'inf -inf nan'), 0);
|
|
const far = outputDistance('x 0.34641016151377535', 'x 0.3464101615137754');
|
|
assert.ok(far > 0 && far < 1e-15, String(far));
|
|
assert.equal(outputDistance('1.0 2.0', '1.0'), Infinity, 'another count of numbers');
|
|
assert.equal(outputDistance('yes 1.0', 'no 1.0'), Infinity, 'other text');
|
|
assert.ok(outputDistance('-256', '256') > 1);
|
|
assert.equal(outputDistance('0.0', '1e-300'), 1, 'nothing is close to zero relatively: the caller decides what near zero means');
|
|
});
|
|
|
|
test('main follows the pseudo\'s own lines, and a procedure call is not printed', () => {
|
|
const r = pseudoToMojo('PROCEDURE SHOW(N : INTEGER)\n OUTPUT N\nENDPROCEDURE\n', { call: 'SHOW(4)' });
|
|
assert.ok(r.source.includes('def main():\n show(4)\n'), r.source);
|
|
const none = pseudoToMojo('FUNCTION F(N : INTEGER) RETURNS INTEGER\n RETURN N\nENDFUNCTION\n');
|
|
assert.ok(!none.source.includes('def main'), 'with no call and no lines of its own there is nothing to run');
|
|
});
|
|
|
|
test('raises is inferred through dictionary reads and through callers, and nothing else raises', () => {
|
|
const pseudo = `FUNCTION GET(M : HASHMAP OF STRING : INTEGER, K : STRING) RETURNS INTEGER
|
|
RETURN M[K]
|
|
ENDFUNCTION
|
|
FUNCTION TWICE(M : HASHMAP OF STRING : INTEGER, K : STRING) RETURNS INTEGER
|
|
RETURN GET(M, K) * 2
|
|
ENDFUNCTION
|
|
FUNCTION PLAIN(N : INTEGER) RETURNS INTEGER
|
|
RETURN N + 1
|
|
ENDFUNCTION
|
|
`;
|
|
const r = pseudoToMojo(pseudo, { call: null });
|
|
assert.ok(r.source.includes('def get(m: Dict[String, Int], k: String) raises -> Int:'), r.source);
|
|
assert.ok(r.source.includes('def twice(m: Dict[String, Int], k: String) raises -> Int:'), r.source);
|
|
assert.ok(r.source.includes('def plain(n: Int) -> Int:'), r.source);
|
|
const withMain = pseudoToMojo(pseudo + 'OUTPUT PLAIN(1)\n');
|
|
assert.ok(withMain.source.includes('def main():'), 'main does not raise when nothing it calls does');
|
|
const raising = pseudoToMojo(pseudo + 'DECLARE M : HASHMAP OF STRING : INTEGER\nM["a"] <- 1\nOUTPUT TWICE(M, "a")\n');
|
|
assert.ok(raising.source.includes('def main() raises:'), raising.source);
|
|
});
|
|
|
|
test('a set needs its import, and the import comes from the harvested module', () => {
|
|
const r = pseudoToMojo('TYPE Bases = SET OF CHAR\nDEFINE Purines (\'A\', \'G\') : Bases\nOUTPUT \'A\' IN Purines\n');
|
|
assert.ok(r.source.includes('from std.collections import Set'), r.source);
|
|
assert.equal(checkMojo(r.source).diagnostics.filter((d) => d.severity === 'error').length, 0);
|
|
});
|
|
|
|
test('what has no faithful Mojo becomes a visible raise and a warning, never a guess', () => {
|
|
const r = pseudoToMojo('DECLARE N : FLOAT\nN <- 1.0\nN <- RANDN()\nOUTPUT N\n');
|
|
const gap = r.notes.find((n) => n.id === 'translate-gap');
|
|
assert.ok(gap && gap.severity === 'warning' && gap.line === 3, JSON.stringify(r.notes ?? r));
|
|
assert.ok(r.source.includes('raise Error("not translated: pseudo line 3")'), r.source);
|
|
assert.ok(r.source.includes('def main() raises:'), 'the routine that raises says so');
|
|
assert.equal(checkMojo(r.source).diagnostics.filter((d) => d.severity === 'error').length, 0, 'the result still checks');
|
|
});
|
|
|
|
test('float literals are not folded the way Mojo folds them: 0.1 + 0.2 stays a Float64 sum', () => {
|
|
const r = pseudoToMojo('OUTPUT 0.1 + 0.2 == 0.3\n');
|
|
assert.ok(r.source.includes('Float64(0.1) + 0.2 == 0.3'), r.source);
|
|
const run = runMojo(checkMojo(r.source).module, r.source, {});
|
|
assert.equal(run.stdout, 'FALSE\n');
|
|
});
|
|
|
|
test('quantifiers become loops written before the line that uses them, and agree with the pseudo', () => {
|
|
const src = fs.readFileSync(path.join(corpusDir, '27-quantifiers.pseudo'), 'utf8');
|
|
const r = pseudoToMojo(src);
|
|
assert.ok(/var _all\d+ = True/.test(r.source) && /var _any\d+ = False/.test(r.source) && /var _sum\d+ = 0/.test(r.source), r.source);
|
|
assert.equal(verdicts.get('27-quantifiers.pseudo')?.verdict, 'agree');
|
|
});
|
|
|
|
test('a quantifier inside a loop condition is a gap, not a wrong answer', () => {
|
|
const r = pseudoToMojo('DECLARE L : LIST OF INTEGER\nL <- [1, 2]\nWHILE EXISTS K IN [0, LENGTH(L)) : L[K] > 5\n L[0] <- 9\nENDWHILE\n');
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-gap'), JSON.stringify(r.notes));
|
|
});
|
|
|
|
/**
|
|
* Spellings the pinned compiler asked for in whole programs: `pixi run mojo-fuzz --statements` builds generated
|
|
* programs of statements (loops, IF and CASE, collections, routines with BYREF, records) and found each of these.
|
|
*/
|
|
const pseudoOut = (src) => { const st = studyOf(src); const tr = runPseudo(st, { maxSteps: 200000 }); assert.equal(tr.error, null, JSON.stringify(tr.error)); return tr.output.join('\n'); };
|
|
const mojoOut = (r) => { const ck = checkMojo(r.source); assert.deepEqual(ck.diagnostics.filter((d) => d.severity === 'error').map((d) => d.message), []); const run = runMojo(ck.module, r.source, { maxSteps: 400000 }); assert.ok(!run.refused, run.refused); return run.stdout.replace(/\n$/, ''); };
|
|
|
|
test('two pseudo names that make one Mojo name are told apart', () => {
|
|
const src = 'DECLARE RunTotal : INTEGER <- 1\nDECLARE RUN_TOTAL : INTEGER <- 2\nOUTPUT RunTotal, " ", RUN_TOTAL';
|
|
const r = mojoOf(src);
|
|
has(r, 'var run_total: Int = 1', 'var run_total_2: Int = 2', 'print(run_total, " ", run_total_2, sep="")');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('two constants that make one Mojo name are told apart, as two variables are', () => {
|
|
// the statement fuzzer, seed 61: the compiler said "invalid redefinition of 'WORD_LIST2'"
|
|
const src = 'CONSTANT WordList2 = 2\nCONSTANT WORD_LIST2 = 6\nOUTPUT WordList2, " ", WORD_LIST2, " ", WORD_LIST2 + WordList2';
|
|
const r = mojoOf(src);
|
|
has(r, 'comptime WORD_LIST2: Int = 2', 'comptime WORD_LIST2_2: Int = 6', 'print(WORD_LIST2, " ", WORD_LIST2_2, " ", WORD_LIST2_2 + WORD_LIST2, sep="")');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('a value the translation already named is handed to a call as it is, beside a BYREF argument', () => {
|
|
// the statement fuzzer, seed 7302: `var _arg3: List[String] = _parts2` was rejected ("cannot be implicitly copied")
|
|
const src = 'TYPE Point\n DECLARE Label : STRING\nENDTYPE\nPROCEDURE Show(BYREF P : Point, Parts : LIST OF STRING, Order : LIST OF INTEGER)\n OUTPUT LENGTH(Parts), " ", P.Label, " ", Order\nENDPROCEDURE\nFUNCTION Build(P : Point, Ns : LIST OF INTEGER) RETURNS INTEGER\n CALL Show(P, SPLIT(P.Label, ","), SORTED(Ns))\n RETURN 0\nENDFUNCTION\nDECLARE Q : Point\nQ.Label <- "a,b,c"\nOUTPUT Build(Q, [3, 1, 2])';
|
|
const r = mojoOf(src);
|
|
assert.doesNotMatch(r.source, /var _arg\d+: List\[String\] = _parts\d+$/m);
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('a variable with no value that is read only inside an IF or a loop starts at zero, as one some path sets does', () => {
|
|
// the statement fuzzer, seed 1 (programs 382, 529, 2671): the notation runs when the path is not taken; Mojo said
|
|
// "use of uninitialized value"
|
|
const src = 'DECLARE N : INTEGER\nDECLARE B : BOOL <- FALSE\nIF B THEN\n OUTPUT N\nENDIF\nFOR I <- 0 TO 0\n DECLARE M : FLOAT\n IF B THEN\n OUTPUT M\n ENDIF\nNEXT I\nOUTPUT "end"';
|
|
const r = mojoOf(src);
|
|
has(r, 'var n: Int = 0', 'var m: Float64 = 0.0');
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-maybe-unset'));
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
// a read every run reaches is left for the compiler to reject, as the notation stops there
|
|
has(mojoOf('DECLARE K : INTEGER\nOUTPUT K'), 'var k: Int');
|
|
assert.doesNotMatch(mojoOf('DECLARE K : INTEGER\nOUTPUT K').source, /var k: Int = 0/);
|
|
});
|
|
|
|
test('an argument that calls something is worked out once when a loop written for the built-in mentions it', () => {
|
|
// the statement fuzzer, seed 202: SLICE(F(X), 0, 2) ran F once per letter, and its OUTPUT showed each time
|
|
const F = 'FUNCTION Word(N : INTEGER) RETURNS STRING\n OUTPUT "word ", N\n RETURN "x,y,z"\nENDFUNCTION\nFUNCTION Nums(N : INTEGER) RETURNS LIST OF INTEGER\n OUTPUT "nums ", N\n RETURN [N, N + 1, N + 2]\nENDFUNCTION\nFUNCTION Pick(N : INTEGER) RETURNS INTEGER\n OUTPUT "pick ", N\n RETURN N\nENDFUNCTION\n';
|
|
for (const body of ['OUTPUT SLICE(Word(1), 0, 3)', 'DECLARE S : STRING\nS <- SLICE(Word(1), 0, MIN(2, LENGTH(Word(2))))\nOUTPUT S', 'OUTPUT INDEX_OF(Nums(4), Pick(6))', 'OUTPUT DOT(Nums(1), Nums(2))',
|
|
// a list in brackets is named by the translation already (ci-fuzz, seed 1: `var _value6 = _list2` does not copy)
|
|
'DECLARE LI : LIST OF INTEGER\nLI <- [3, 1, 2]\nOUTPUT INDEX_OF([FLOOR(3.25), MAX((-1), 1000)], MAX(MIN(LI), 3))', 'OUTPUT DOT([ABS(-1), 2], [Pick(3), 4])']) {
|
|
const r = mojoOf(F + body);
|
|
assert.equal(mojoOut(r), pseudoOut(F + body), body);
|
|
}
|
|
});
|
|
|
|
test('a name declared inside a block and used after it is declared before the block', () => {
|
|
const src = 'DECLARE N : INTEGER <- 3\nIF N > 0 THEN\n DECLARE Inner : INTEGER <- 5\nENDIF\nOUTPUT Inner\nFOR I <- 0 TO 2\n DECLARE Row : LIST OF INTEGER\n APPEND(Row, I)\n DECLARE T : INTEGER <- I\nNEXT I\nOUTPUT T, " ", Row';
|
|
const r = mojoOf(src);
|
|
has(r, 'var inner: Int = 0', 'inner = 5', 'var t: Int = 0', 'var row: List[Int] = List[Int]()', 'row = List[Int]()', 't = i');
|
|
assert.ok(r.source.indexOf('var inner: Int = 0') < r.source.indexOf('if n > 0:'), r.source);
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-lifted'));
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('a scalar some path leaves without a value starts at zero; one every path assigns, or none does, is left as declared', () => {
|
|
const src = 'DECLARE N : INTEGER <- 3\nDECLARE W : INTEGER\nIF N > 1 THEN\n W <- 1\nENDIF\nOUTPUT W\nDECLARE V : INTEGER\nFOR I <- 0 TO N\n V <- I\nNEXT I\nOUTPUT V\nDECLARE Z : INTEGER\nIF N > 1 THEN\n Z <- 1\nELSE\n Z <- 2\nENDIF\nOUTPUT Z';
|
|
const r = mojoOf(src);
|
|
has(r, 'var w: Int = 0', 'var v: Int = 0', 'var z: Int');
|
|
assert.ok(r.notes.some((n) => n.id === 'translate-maybe-unset'));
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
// read before anything can give it a value: every run of the notation stops there, and the compiler rejects it too
|
|
has(mojoOf('DECLARE T : INTEGER\nOUTPUT T + 1'), 'var t: Int');
|
|
});
|
|
|
|
test('CONTINUE in a REPEAT tests the UNTIL condition before the next pass', () => {
|
|
const src = 'DECLARE K : INTEGER <- 0\nREPEAT\n K <- K + 1\n IF K < 3 THEN\n CONTINUE\n ENDIF\n OUTPUT "k ", K\nUNTIL K >= 2\nOUTPUT K';
|
|
const r = mojoOf(src);
|
|
assert.ok(/ {12}if k >= 2:\n {16}break\n {12}continue\n/.test(r.source), r.source);
|
|
assert.equal(pseudoOut(src), '2');
|
|
assert.equal(mojoOut(r), '2');
|
|
});
|
|
|
|
test('DELETE of a member or key that is not there changes nothing, and does not raise', () => {
|
|
const r = mojoOf('DECLARE S : SET OF INTEGER <- {3, 1}\nDELETE(S, 7)\nDECLARE M : HASHMAP OF STRING : FLOAT <- {"k": 1}\nDELETE(M, "zz")\nDECLARE G : HASHMAP OF INTEGER : LIST OF INTEGER\nDELETE(G, 2)\nOUTPUT LENGTH(S), LENGTH(M)');
|
|
has(r, 's.discard(7)', '_ = m.pop("zz", 0.0)', '_ = g.pop(2, List[Int]())', 'var m: Dict[String, Float64] = {"k": 1}');
|
|
assert.ok(r.source.includes('def main():'), 'nothing here raises');
|
|
});
|
|
|
|
test('a map literal lands in the map\'s types, and a SLICE of a list is a new list', () => {
|
|
const r = mojoOf('DECLARE H : HASHMAP OF CHAR : LIST OF INTEGER <- {\'d\': [3]}\nDECLARE L : LIST OF INTEGER <- [1, 2, 3]\nDECLARE M : LIST OF INTEGER\nM <- SLICE(L, 0, 2)\nOUTPUT M, LENGTH(H)');
|
|
has(r, 'var h: Dict[String, List[Int]] = {"d": [3]}', 'm = List[Int](l[0:2])');
|
|
});
|
|
|
|
test('FOR EACH walks the text, list or map as it was when the loop began', () => {
|
|
const src = 'DECLARE S : STRING <- "abc"\nFOR EACH Ch IN S\n S <- "z" & S\n OUTPUT Ch\nNEXT Ch\nDECLARE H : HASHMAP OF STRING : INTEGER <- {"a": 1}\nFOR EACH K IN H\n H[K] <- H[K] * 2\nNEXT K\nOUTPUT S, H';
|
|
const r = mojoOf(src);
|
|
has(r, 'var _walk2 = String(s)', 'var ch = String(_walk2[codepoint=_ch_pos1])', 'var _walk3 = h.copy()', 'for k in _walk3.keys():');
|
|
assert.equal(pseudoOut(src), 'a\nb\nc\nzzzabc{"a": 2}');
|
|
});
|
|
|
|
test('notes say what differs, and only where it does: / and DIV by zero, IEEE, whole and fractional powers', () => {
|
|
const ids = (src) => mojoOf(src).notes.map((n) => n.id);
|
|
assert.ok(ids('DECLARE X : FLOAT <- 1.0\nOUTPUT X / 3').includes('translate-divide'));
|
|
assert.ok(!ids('USE IEEE\nDECLARE X : FLOAT <- 1.0\nOUTPUT X / 0.0').includes('translate-divide'), 'under USE IEEE the notation gives infinity too');
|
|
// probes/int-div-zero and int-mod-zero: Mojo's // and % by zero give 0
|
|
assert.ok(ids('DECLARE N : INTEGER <- 7\nDECLARE Z : INTEGER <- 0\nOUTPUT N DIV Z').includes('translate-divide-int'));
|
|
assert.ok(ids('DECLARE N : INTEGER <- 7\nDECLARE Z : INTEGER <- 0\nOUTPUT N MOD (Z + 1)').includes('translate-divide-int'));
|
|
assert.ok(!ids('DECLARE N : INTEGER <- 7\nOUTPUT N DIV 2, N MOD (-3)').includes('translate-divide-int'), 'a nonzero literal divisor cannot be zero');
|
|
const whole = mojoOf('DECLARE X : FLOAT <- 1.1\nDECLARE N : INTEGER <- 20\nOUTPUT X ^ N, X ^ 3');
|
|
assert.deepEqual(whole.notes.filter((n) => /power/.test(n.id)).map((n) => n.id), ['translate-power-whole']);
|
|
assert.match(whole.notes.find((n) => n.id === 'translate-power-whole').message, /repeated multiplication/);
|
|
const frac = mojoOf('DECLARE X : FLOAT <- 2.0\nOUTPUT X ^ 0.5');
|
|
assert.match(frac.notes.find((n) => n.id === 'translate-power').message, /13 significant digits/);
|
|
assert.ok(!/1e10/.test(frac.notes.find((n) => n.id === 'translate-power').message));
|
|
const unknown = mojoOf('DECLARE X : FLOAT <- 2.0\nDECLARE Y : FLOAT <- 0.5\nOUTPUT POW(X, Y)');
|
|
assert.match(unknown.notes.find((n) => n.id === 'translate-power').message, /whole power.*fractional power/);
|
|
});
|
|
|
|
test('a FLOAT made into text is printed, never used as text: Mojo spells some FLOATs otherwise', () => {
|
|
// the notation writes 6.02e23, Mojo 6.02e+23; they switch to an exponent at other sizes, and where two shortest
|
|
// spellings tie they pick differently (11340668257756.562 and ...563), so the text itself is not the notation's
|
|
const used = mojoOf('DECLARE X : FLOAT <- 6.02e23\nOUTPUT 100 * LENGTH(TO_STRING(X))\nDECLARE S : STRING\nS <- "x" & TO_STRING(X)\nOUTPUT S');
|
|
assert.deepEqual(gaps(used).map((g) => g.line), [2, 4]);
|
|
assert.match(gaps(used)[0].message, /used as text/);
|
|
// printed, it is the same value: OUTPUT compares by value
|
|
const shown = mojoOf('DECLARE X : FLOAT <- 2.5\nOUTPUT "x = " & TO_STRING(X) & " " & TO_STRING(X + 1.0), " ", TO_STRING(X)');
|
|
assert.deepEqual(gaps(shown), []);
|
|
has(shown, 'print((("x = " + String(x)) + " ") + String(x + 1.0), " ", String(x), sep="")');
|
|
assert.equal(mojoOut(shown), 'x = 2.5 3.5 2.5');
|
|
// a list of text made into text has quotes in the notation and none in Mojo
|
|
assert.equal(gaps(mojoOf('DECLARE L : LIST OF STRING <- ["a"]\nOUTPUT LENGTH(TO_STRING(L))')).length, 1);
|
|
assert.deepEqual(gaps(mojoOf('DECLARE L : LIST OF INTEGER <- [1]\nOUTPUT LENGTH(TO_STRING(L))')), []);
|
|
});
|
|
|
|
test('SUM_OF, MAX, MEAN_OF, SORTED and IN of a two-dimensional ARRAY look at every cell, not at the rows', () => {
|
|
const src = 'DECLARE A : ARRAY[2, 3] OF INTEGER\nFOR I <- 0 TO 2\n FOR J <- 0 TO 3\n A[I, J] <- I * 10 + J\n NEXT J\nNEXT I\nOUTPUT SUM_OF(A)\nOUTPUT MAX(A)\nOUTPUT MEAN_OF(A)\nOUTPUT 12 IN A\nOUTPUT SORTED(A)';
|
|
const r = mojoOf(src);
|
|
has(r, 'var _cells4 = List[Int]()', 'for _row2 in a:', 'for _x3 in _row2:', '_cells4.append(_x3)', 'for _x5 in _cells4:');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('a constant has its type, so Mojo does not fold it as a literal; Mojo\'s own words are not names', () => {
|
|
const src = 'CONSTANT Rate = 0.1\nCONSTANT Word = "GC"\nCONSTANT Lim = 4\nOUTPUT Rate + 0.2 == 0.3, " ", INT(Rate), " ", REPLACE(Word, "G", "x"), " ", Lim\nDECLARE Nonlocal : INTEGER <- 2\nOUTPUT Nonlocal';
|
|
const r = mojoOf(src);
|
|
has(r, 'comptime RATE: Float64 = 0.1', 'comptime WORD: String = "GC"', 'comptime LIM: Int = 4', 'var nonlocal_: Int = 2');
|
|
assert.equal(pseudoOut(src), 'FALSE 0 xC 4\n2');
|
|
assert.ok(mojoOf('TYPE Self\n DECLARE X : INTEGER\nENDTYPE\nDECLARE P : Self\nP.X <- 1\nOUTPUT P.X').source.includes('struct Self_(Copyable, Movable):'));
|
|
assert.ok(mojoOf('TYPE Dict\n DECLARE X : INTEGER\nENDTYPE\nDECLARE P : Dict\nP.X <- 1\nOUTPUT P.X').source.includes('var p = Dict_(0)'));
|
|
});
|
|
|
|
test('a value made from the collection it is stored into is named first, with its type', () => {
|
|
const r = mojoOf('DECLARE L : LIST OF INTEGER <- [1, 2, 3]\nL <- SLICE(L, 0, 2)\nDECLARE G : LIST OF LIST OF INTEGER <- [[1], [2]]\nG[0] <- [G[1][0], 5]\nDECLARE S : LIST OF STRING <- ["a", "b"]\nS[0] <- JOIN(S, "-")\nOUTPUT L, G, S');
|
|
has(r, 'var _value1: List[Int] = List[Int](l[0:2])', 'l = _value1^', 'g[0] = [g[1][0], 5]', 'var _value2: String = String("-").join(s)', 's[0] = _value2^');
|
|
});
|
|
|
|
test('a variable handed BYREF and also read by another argument of the call is copied for that argument first', () => {
|
|
const src = 'PROCEDURE Grow(BYREF L : LIST OF INTEGER, Old : LIST OF INTEGER, N : INTEGER)\n APPEND(L, N)\n OUTPUT LENGTH(L), " ", LENGTH(Old)\nENDPROCEDURE\nDECLARE Xs : LIST OF INTEGER <- [1]\nCALL Grow(Xs, Xs, LENGTH(Xs))';
|
|
const r = mojoOf(src);
|
|
has(r, 'var _arg1: List[Int] = xs.copy()', 'var _arg2: Int = len(xs)', 'grow(xs, _arg1^, _arg2)');
|
|
has(mojoOf('PROCEDURE Grow(BYREF L : LIST OF INTEGER, Old : LIST OF INTEGER)\n APPEND(L, LENGTH(Old))\nENDPROCEDURE\nDECLARE Xs : LIST OF INTEGER <- [1]\nCALL Grow(Xs, [Xs[0], 2])'), 'var _arg1: List[Int] = [xs[0], 2]');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('FILL works its value out once', () => {
|
|
const src = 'FUNCTION Noisy(N : INTEGER) RETURNS INTEGER\n OUTPUT "called"\n RETURN N * 2\nENDFUNCTION\nDECLARE Xs : LIST OF INTEGER <- FILL(3, Noisy(4))\nDECLARE G : LIST OF LIST OF INTEGER <- FILL(2, [1, 2])\nG[0][0] <- 9\nOUTPUT Xs, " ", G';
|
|
const r = mojoOf(src);
|
|
has(r, 'var _item1: Int = noisy(4)', '_fill2.append(_item1)');
|
|
assert.equal(pseudoOut(src), 'called\n[8, 8, 8] [[9, 2], [1, 2]]');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|
|
|
|
test('a CASE subject is worked out once, before any arm', () => {
|
|
const src = 'FUNCTION Noisy(N : INTEGER) RETURNS INTEGER\n OUTPUT "called"\n RETURN N\nENDFUNCTION\nCASE OF Noisy(3)\n 1 : OUTPUT "one"\n 2, 3 : OUTPUT "two or three"\n OTHERWISE : OUTPUT "other"\nENDCASE\nCASE OF Noisy(5)\nENDCASE';
|
|
const r = mojoOf(src);
|
|
has(r, 'var _subject1: Int = noisy(3)', 'if _subject1 == 1:', 'elif _subject1 == 2 or _subject1 == 3:', 'var _subject2: Int = noisy(5)');
|
|
assert.equal(pseudoOut(src), 'called\ntwo or three\ncalled');
|
|
assert.equal(mojoOut(r), pseudoOut(src));
|
|
});
|