Widen pseudo for numerical work: sized types, FLOAT32, exact built-ins, USE IEEE
Pseudo could say what a procedure computes only up to INTEGER and FLOAT, so it could not state what a Mojo or Python program with Int32, UInt8 or Float32 values will compute, and it had no words for rounding itself. - lang/parse: INT8..INT64, UINT8..UINT64, FLOAT32, FLOAT64 as types (INTEGER or FLOAT with a width, so every "whole number" rule accepts them); conversions written as Mojo writes them, INT32(X), FLOAT32(X); 1_000_000, 0xFF and 0b1010 literals; a type name as an argument (MAX_VALUE(INT8)); the USE line (USE IEEE now, library modules next). - check: widths and precisions never mix silently (mixed-width, mixed-precision); a literal takes the type of the sized value beside it, as in Mojo, and one that does not fit is an error before any run (literal-range); typing for every new built-in. - interp: a sized result, store, parameter, RETURN or conversion that does not fit stops the run (kind overflow), WRAP(X, T) wraps on purpose; FLOAT32 results are rounded to single precision; USE IEEE lets NaN and infinities flow. - numeric.js: exact helpers: FMA rounded once, EXACT(X) with every digit a FLOAT holds, ULP and NEXT_AFTER for both precisions, bit operations in two's complement. - Built-ins: ASIN ACOS ATAN SINH COSH TANH HYPOT POW CBRT EXPM1 LOG1P E TRUNC SIGN COPYSIGN CLAMP FMA IS_NAN IS_INF IS_FINITE INF NAN ULP NEXT_AFTER IS_CLOSE EXACT MAX_VALUE MIN_VALUE EPSILON GCD LCM BIT_AND BIT_OR BIT_XOR BIT_NOT SHIFT_LEFT SHIFT_RIGHT WRAP. They stay usable as names (a variable E, a FUNCTION GCD): the program's own wins. - vcgen: an overflow obligation on every sized result, then the range as a fact (also for sized parameters and loop-cut variables); FLOAT32 arithmetic as its own uninterpreted functions, constants rounded exactly, TOFLOAT32(v) otherwise; argument obligations for SQRT, the logarithms, ASIN/ACOS, LOG1P, CLAMP and the shifts; nothing proved under USE IEEE. - testing: the fuzzer tries the edges of a sized type and generates FLOAT32 values. - pseudo-to-mojo: Int8..Float32, conversions, the new built-ins through std.math (each name in the harvested index), a note where Mojo wraps. - Tests: numeric.test.mjs; corpus 49-52; prover fixtures int8-overflow, float32-store, ieee-nan; the reference documents every new form. Gate: 324 pass (core). New Mojo uses std.math names the interpreter has not been verified on (listed in sync-mojo's KNOWN_GAPS); they need pixi run mojo-verify on the network before the interpreter runs them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
This commit is contained in:
24 files changed
+1271
-96
No files matched your search
+187
-25
@@ -18,6 +18,7 @@
|
||||
|
||||
import {
|
||||
T, BUILTINS, MUTATORS, typeName, sameType, assignable, isNumeric, isAny, isText,
|
||||
SIZED, isSizedInt, isFloat32, intRange, intRangeText, TYPE_ARGS, SOFT_BUILTINS,
|
||||
} from './lang.js';
|
||||
import { diag, sourceOf } from './parse.js';
|
||||
import { editDistance } from '../shared/text.js';
|
||||
@@ -50,8 +51,8 @@ for (const k of Object.keys(FOREIGN_FUNCTIONS)) if (!FOREIGN_FUNCTIONS[k]) delet
|
||||
|
||||
/** Type names from Python and Mojo, and this notation's word for each. */
|
||||
const FOREIGN_TYPES = {
|
||||
INT: 'INTEGER', INT64: 'INTEGER', LONG: 'INTEGER', NUMBER: 'INTEGER or FLOAT',
|
||||
STR: 'STRING', TEXT: 'STRING', FLOAT64: 'FLOAT', DOUBLE: 'FLOAT', REAL: 'FLOAT',
|
||||
INT: 'INTEGER (or INT64 for a 64-bit whole number)', LONG: 'INT64', NUMBER: 'INTEGER or FLOAT',
|
||||
STR: 'STRING', TEXT: 'STRING', DOUBLE: 'FLOAT64', REAL: 'FLOAT', SINGLE: 'FLOAT32',
|
||||
BOOLEAN: 'BOOL', DICT: 'HASHMAP OF <key type> TO <value type>', MAP: 'HASHMAP OF <key type> TO <value type>',
|
||||
ARRAYLIST: 'LIST OF <type>',
|
||||
};
|
||||
@@ -85,12 +86,24 @@ function elementOf(t) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Two numbers combine to FLOAT unless both are INTEGER. */
|
||||
/**
|
||||
* The type two numbers combine to. A FLOAT with anything is a FLOAT (FLOAT32 stays FLOAT32 next to a whole
|
||||
* number; FLOAT32 next to FLOAT64 is a clash the caller reports). Two whole numbers are INTEGER, or the sized
|
||||
* type when one is sized (two different widths are a clash the caller reports).
|
||||
*/
|
||||
function numericResult(a, b) {
|
||||
if (isAny(a) || isAny(b)) return isAny(a) ? (isAny(b) ? T.ANY : b) : a;
|
||||
return a.k === 'FLOAT' || b.k === 'FLOAT' ? T.FLOAT : T.INTEGER;
|
||||
if (a.k === 'FLOAT' || b.k === 'FLOAT') {
|
||||
if (a.k === 'FLOAT' && b.k === 'FLOAT') return isFloat32(a) && isFloat32(b) ? a : (a.bits === 64 ? a : b.bits === 64 ? b : T.FLOAT);
|
||||
return a.k === 'FLOAT' ? a : b;
|
||||
}
|
||||
if (a.bits) return a;
|
||||
return b.bits ? b : T.INTEGER;
|
||||
}
|
||||
|
||||
/** A numeric literal, which takes the type of the sized value beside it: X + 1 for an INT8 X is INT8 arithmetic. */
|
||||
const isLiteral = (n) => !!n && n.kind === 'Num';
|
||||
|
||||
/** Does a list of statements end every path in RETURN? */
|
||||
export function alwaysReturns(body) {
|
||||
for (const s of body) {
|
||||
@@ -124,8 +137,10 @@ class Scope {
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
class Checker {
|
||||
constructor(parsed) {
|
||||
constructor(parsed, options = {}) {
|
||||
this.parsed = parsed;
|
||||
this.libs = options.libs || new Map(); // routines from the library: UPPER name -> checked routine
|
||||
this.libOrigin = options.libOrigin || new Map(); // UPPER name -> { module, line } of the USE that brought it
|
||||
this.diags = [];
|
||||
this.types = new Map(); // record types
|
||||
this.setTypes = new Map(); // TYPE X = SET OF ...
|
||||
@@ -138,6 +153,9 @@ class Checker {
|
||||
this.ctx = null;
|
||||
}
|
||||
|
||||
/** A routine defined in this program, or brought in from the library with USE. */
|
||||
findSub(name) { const k = up(name); return this.subs.get(k) || this.libs.get(k); }
|
||||
|
||||
error(code, node, message, extra = {}) { this.diags.push(diag('error', code, node?.line ?? 1, message, { col: node?.col ?? 1, ...extra })); }
|
||||
warn(code, node, message, extra = {}) { this.diags.push(diag('warning', code, node?.line ?? 1, message, { col: node?.col ?? 1, ...extra })); }
|
||||
note(code, node, message, extra = {}) { this.diags.push(diag('note', code, node?.line ?? 1, message, { col: node?.col ?? 1, ...extra })); }
|
||||
@@ -158,7 +176,8 @@ class Checker {
|
||||
} else if (s.kind === 'Function' || s.kind === 'Procedure') {
|
||||
if (s.name.startsWith('<')) this.subs.set(`${up(s.name)}#${s.line}`, { name: s.name, kind: s.kind, node: s, params: [], returns: null, requires: [], ensures: [], decreases: null });
|
||||
else if (this.subs.has(up(s.name))) this.error('duplicate', s, `${s.name} is already defined on line ${this.subs.get(up(s.name)).node.line}.`);
|
||||
else if (BUILTINS[up(s.name)]) this.error('builtin-name', s, `${up(s.name)} is a built-in, so a ${s.kind.toUpperCase()} cannot take its name.`);
|
||||
else if ((BUILTINS[up(s.name)] && !SOFT_BUILTINS.has(up(s.name))) || SIZED[up(s.name)]) this.error('builtin-name', s, `${up(s.name)} is a built-in, so a ${s.kind.toUpperCase()} cannot take its name.`);
|
||||
else if (this.libs.has(up(s.name))) this.error('library-clash', s, `${s.name} also comes from the library (USE ${this.libOrigin.get(up(s.name))?.module} on line ${this.libOrigin.get(up(s.name))?.line}). Rename this one, or bring in only the routines you need: USE ${this.libOrigin.get(up(s.name))?.module}.<Name>.`, { guide: 'libraries' });
|
||||
else this.subs.set(up(s.name), { name: s.name, kind: s.kind, node: s, params: [], returns: null, requires: [], ensures: [], decreases: null });
|
||||
}
|
||||
}
|
||||
@@ -250,7 +269,7 @@ class Checker {
|
||||
this.collect(ast.body);
|
||||
const mainBody = [];
|
||||
for (const s of ast.body) {
|
||||
if (['TypeDef', 'SetTypeDef', 'Constant', 'Define'].includes(s.kind)) continue;
|
||||
if (['TypeDef', 'SetTypeDef', 'Constant', 'Define', 'Use'].includes(s.kind)) continue;
|
||||
if (s.kind === 'Function' || s.kind === 'Procedure') { this.subroutine(this.subs.get(up(s.name)) || this.subs.get(`${up(s.name)}#${s.line}`) || { node: s, params: [], returns: T.ANY, requires: [], ensures: [] }); continue; }
|
||||
mainBody.push(s);
|
||||
}
|
||||
@@ -265,6 +284,9 @@ class Checker {
|
||||
constants: this.constants,
|
||||
defines: this.defines,
|
||||
subs: this.subs,
|
||||
libs: this.libs,
|
||||
uses: ast.body.filter((s) => s.kind === 'Use'),
|
||||
ieee: ast.body.some((s) => s.kind === 'Use' && s.ieee),
|
||||
main: { body: mainBody, scope: this.mainScope, symbols: [...this.mainScope.map.values()] },
|
||||
blanks: this.blanks,
|
||||
};
|
||||
@@ -337,8 +359,8 @@ class Checker {
|
||||
}
|
||||
const g = this.global.get(name);
|
||||
if (g) this.error('duplicate', node, `${name} is already the name of a ${g.kind === 'const' ? 'CONSTANT' : 'set'} defined on line ${g.line}.`);
|
||||
if (this.subs.has(k)) this.error('duplicate', node, `${name} is already the name of a ${this.subs.get(k).kind.toUpperCase()}.`);
|
||||
if (BUILTINS[k]) this.error('builtin-name', node, `${k} is a built-in, so a variable cannot take its name.`);
|
||||
if (this.findSub(k)) this.error('duplicate', node, `${name} is already the name of a ${this.findSub(k).kind.toUpperCase()}${this.libs.has(k) ? ' from the library' : ''}.`);
|
||||
if ((BUILTINS[k] && !SOFT_BUILTINS.has(k)) || SIZED[k]) this.error('builtin-name', node, `${k} is a built-in, so a variable cannot take its name.`);
|
||||
if (this.types.has(k) || this.setTypes.has(k)) this.error('duplicate', node, `${name} is already the name of a type.`);
|
||||
return scope.set(name, sym);
|
||||
}
|
||||
@@ -359,6 +381,7 @@ class Checker {
|
||||
this.error('global-only', s, `${s.kind === 'TypeDef' || s.kind === 'SetTypeDef' ? 'TYPE' : s.kind === 'Constant' ? 'CONSTANT' : 'DEFINE'} lines go at the top level, outside every block.`);
|
||||
return;
|
||||
case 'Function': case 'Procedure': return;
|
||||
case 'Use': this.error('use-place', s, 'USE lines go at the top of the program, outside every block.', { guide: 'libraries' }); return;
|
||||
case 'Assign': this.assign(s, scope); return;
|
||||
case 'Input': {
|
||||
if (!s.target) return;
|
||||
@@ -553,11 +576,13 @@ class Checker {
|
||||
return;
|
||||
}
|
||||
if (!s.value) { this.error('return-value', s, `FUNCTION ${sub.name} has to hand back ${article(sub.returns)}, so its RETURN needs a value.`, { guide: 'function' }); return; }
|
||||
const t = this.expr(s.value, scope);
|
||||
const t = this.adopt(s.value, sub.returns, this.expr(s.value, scope));
|
||||
if (!assignable(sub.returns, t)) this.error('type', s.value, `FUNCTION ${sub.name} promises ${article(sub.returns)} with RETURNS, and ${sourceOf(s.value)} is ${article(t)}.${this.narrowHint(sub.returns, t, s.value)}`, { guide: 'function' });
|
||||
}
|
||||
|
||||
narrowHint(to, from, value) {
|
||||
if (to.k === 'INTEGER' && from.k === 'INTEGER' && to.bits && from.bits) return ` Two different sized types do not mix silently: convert with ${to.name}(${sourceOf(value)}), which stops the run if the value does not fit.`;
|
||||
if (isFloat32(to) && from.k === 'FLOAT') return ` A FLOAT64 rounds when it becomes a FLOAT32, so the conversion is written out: FLOAT32(${sourceOf(value)}).`;
|
||||
if (to.k === 'INTEGER' && from.k === 'FLOAT') {
|
||||
if (value && value.kind === 'Binary' && value.op === '/') return ' / always gives a FLOAT, even when both sides are whole. Use DIV for a whole-number answer.';
|
||||
return ' Use INT or ROUND to turn a FLOAT into a whole number, and decide which one you mean.';
|
||||
@@ -568,7 +593,7 @@ class Checker {
|
||||
|
||||
assign(s, scope) {
|
||||
const tt = this.target(s.target, scope, 'assign');
|
||||
const vt = this.expr(s.value, scope, { expect: tt });
|
||||
const vt = this.adopt(s.value, tt, this.expr(s.value, scope, { expect: tt }));
|
||||
if (!tt || isAny(tt) || isAny(vt)) return;
|
||||
if (vt.k === 'VOID') { this.error('type', s.value, `${sourceOf(s.value)} hands nothing back, so there is nothing to store.`); return; }
|
||||
if (tt.k === 'STRING' && vt.k === 'CHAR') return;
|
||||
@@ -642,7 +667,7 @@ class Checker {
|
||||
e.sym = mainSym;
|
||||
return mainSym;
|
||||
}
|
||||
if (this.subs.has(up(name))) { this.error('sub-as-value', e, `${name} is a ${this.subs.get(up(name)).kind.toUpperCase()}, and it needs brackets and its arguments to be called.`); return null; }
|
||||
if (this.findSub(name)) { this.error('sub-as-value', e, `${name} is a ${this.findSub(name).kind.toUpperCase()}, and it needs brackets and its arguments to be called.`); return null; }
|
||||
if (up(name) === 'RESULT') { this.error('result-place', e, 'RESULT means the value a FUNCTION returns, so it can appear only in that function\'s ENSURE lines.', { guide: 'contracts' }); return null; }
|
||||
const pool = [...scope.all().values()].map((x) => x.name);
|
||||
const s = suggest(name, pool);
|
||||
@@ -662,7 +687,7 @@ class Checker {
|
||||
}
|
||||
|
||||
callStmt(s, scope) {
|
||||
const sub = this.subs.get(up(s.name));
|
||||
const sub = this.findSub(s.name);
|
||||
if (!sub) {
|
||||
if (BUILTINS[up(s.name)]?.kind === 'procedure') {
|
||||
this.note('builtin-call', s, `${up(s.name)} is a built-in procedure and needs no CALL: write ${up(s.name)}(...) on its own.`);
|
||||
@@ -670,7 +695,7 @@ class Checker {
|
||||
s.builtin = true;
|
||||
return;
|
||||
}
|
||||
const hint = suggest(s.name, [...this.subs.values()].map((x) => x.name));
|
||||
const hint = suggest(s.name, [...this.subs.values(), ...this.libs.values()].map((x) => x.name));
|
||||
this.error('unknown-sub', s, `No PROCEDURE is called ${s.name}.${hint.length ? ` Did you mean ${hint.join(' or ')}?` : ''}`, { guide: 'procedure' });
|
||||
for (const a of s.args) this.expr(a, scope);
|
||||
return;
|
||||
@@ -698,8 +723,9 @@ class Checker {
|
||||
}
|
||||
args.forEach((a, i) => {
|
||||
const p = sub.params[i];
|
||||
const t = this.expr(a, scope);
|
||||
let t = this.expr(a, scope);
|
||||
if (!p) return;
|
||||
if (p.mode !== 'BYREF') t = this.adopt(a, p.type);
|
||||
if (p.mode === 'BYREF') {
|
||||
if (a.kind !== 'Name') this.error('byref-arg', a, `Parameter ${p.name} of ${sub.name} is BYREF, so the call has to pass a variable it can change, not ${sourceOf(a)}.`, { guide: 'passing-by-value-or-by-reference' });
|
||||
else {
|
||||
@@ -719,7 +745,7 @@ class Checker {
|
||||
exprStmt(s, scope) {
|
||||
const e = s.expr;
|
||||
if (e.kind === 'CallExpr') {
|
||||
const sub = this.subs.get(up(e.name));
|
||||
const sub = e.convert ? null : this.findSub(e.name);
|
||||
if (sub && sub.kind === 'Procedure') {
|
||||
this.error('missing-call', s, `Call a PROCEDURE with CALL, on a line of its own: CALL ${sourceOf(e)}.`, { guide: 'procedure', fix: { line: s.line, col: s.col, endCol: s.col, text: 'CALL ' } });
|
||||
s.sub = sub;
|
||||
@@ -810,6 +836,9 @@ class Checker {
|
||||
case 'Bool': return T.BOOL;
|
||||
case 'Blank': if (e.text !== '...') this.blank(e, e.text); return T.ANY;
|
||||
case 'Error': return T.ANY;
|
||||
case 'TypeRef':
|
||||
if (!opts.typeArg) { this.error('type-as-value', e, `${e.name} is a type, and a value was expected here. To convert a number to it, write ${e.name}(X)${['INTEGER', 'FLOAT'].includes(e.name) ? ` with a sized type, or ${e.name === 'INTEGER' ? 'INT(X)' : 'TO_FLOAT(X)'}` : ''}.`, { guide: 'the-types' }); return T.ANY; }
|
||||
return T[e.name] || T.ANY;
|
||||
case 'Name': {
|
||||
if (this.ctx?.constOnly) {
|
||||
const sym = scope.get(e.name);
|
||||
@@ -849,8 +878,9 @@ class Checker {
|
||||
case 'CallExpr': return this.call(e, scope);
|
||||
case 'ListLit': {
|
||||
let el = T.ANY;
|
||||
const want = opts.expect && ['LIST', 'ARRAY'].includes(opts.expect.k) ? opts.expect.of : null;
|
||||
for (const it of e.items) {
|
||||
const t = this.expr(it, scope);
|
||||
const t = this.adopt(it, want, this.expr(it, scope));
|
||||
if (isAny(el)) el = t;
|
||||
else if (isNumeric(el) && isNumeric(t)) el = numericResult(el, t);
|
||||
else if (!isAny(t) && !sameType(el, t)) this.error('type', it, `Every value in a list has one type, and ${sourceOf(it)} is ${article(t)} where the others are ${typeName(el)}.`);
|
||||
@@ -920,29 +950,37 @@ class Checker {
|
||||
return T.BOOL;
|
||||
case '+': case '-': case '*':
|
||||
if (any) return isNumeric(lt) ? lt : isNumeric(rt) ? rt : T.ANY;
|
||||
if (isNumeric(lt) && isNumeric(rt)) return this.mix(e, lt, rt);
|
||||
if (op === '+' && isText(lt) && isText(rt)) { this.error('type', e, `Text is joined with &, not +: ${sourceOf(e.left)} & ${sourceOf(e.right)}.`, { guide: 'joining-and-cutting-text' }); return T.STRING; }
|
||||
if (!isNumeric(lt) || !isNumeric(rt)) { this.error('type', e, `${op} works on numbers, and ${!isNumeric(lt) ? sourceOf(e.left) : sourceOf(e.right)} is ${article(!isNumeric(lt) ? lt : rt)}.${isText(lt) && isNumeric(rt) ? ' TO_STRING turns a number into text, and & joins text.' : ''}`); return T.ANY; }
|
||||
return numericResult(lt, rt);
|
||||
case '/':
|
||||
if (!any && (!isNumeric(lt) || !isNumeric(rt))) { this.error('type', e, `/ divides numbers, and ${!isNumeric(lt) ? sourceOf(e.left) : sourceOf(e.right)} is ${article(!isNumeric(lt) ? lt : rt)}.`); }
|
||||
return T.FLOAT;
|
||||
if (!any && isNumeric(lt) && isNumeric(rt) && (isFloat32(lt) || isFloat32(rt))) { const m = this.mix(e, lt, rt); return isFloat32(m) ? m : T.FLOAT; }
|
||||
return lt.bits === 64 || rt.bits === 64 ? T.FLOAT64 : T.FLOAT;
|
||||
case 'DIV': case 'MOD':
|
||||
for (const [t, n] of [[lt, e.left], [rt, e.right]]) {
|
||||
if (!isAny(t) && t.k !== 'INTEGER') this.error('type', n, `${op} works on whole numbers, and ${sourceOf(n)} is ${article(t)}.${t.k === 'FLOAT' ? ' Use / to divide FLOAT values.' : ''}`, { guide: 'arithmetic' });
|
||||
}
|
||||
if (!any && lt.k === 'INTEGER' && rt.k === 'INTEGER') return this.mix(e, lt, rt);
|
||||
return T.INTEGER;
|
||||
case '^':
|
||||
if (!any && (!isNumeric(lt) || !isNumeric(rt))) this.error('type', e, '^ raises a number to a power, and both sides have to be numbers.');
|
||||
return any ? T.ANY : numericResult(lt, rt);
|
||||
if (!any && (!isNumeric(lt) || !isNumeric(rt))) { this.error('type', e, '^ raises a number to a power, and both sides have to be numbers.'); return T.ANY; }
|
||||
if (any) return T.ANY;
|
||||
// the power keeps the base's width: INT32 ^ 2 is INT32, whatever the exponent's type
|
||||
if (lt.bits && rt.k === 'INTEGER') { this.adopt(e.right, lt.k === 'INTEGER' ? lt : null); return lt; }
|
||||
return this.mix(e, lt, rt);
|
||||
case '&':
|
||||
for (const [t, n] of [[lt, e.left], [rt, e.right]]) {
|
||||
if (!isAny(t) && !isText(t)) this.error('type', n, `& joins text, and ${sourceOf(n)} is ${article(t)}. TO_STRING(${sourceOf(n)}) writes it as text first.`);
|
||||
}
|
||||
return T.STRING;
|
||||
case '==': case '!=':
|
||||
this.adoptPair(e, lt, rt);
|
||||
this.comparable(e, lt, rt, true);
|
||||
return T.BOOL;
|
||||
case '<': case '<=': case '>': case '>=':
|
||||
this.adoptPair(e, lt, rt);
|
||||
this.comparable(e, lt, rt, false);
|
||||
return T.BOOL;
|
||||
case 'IN': {
|
||||
@@ -964,6 +1002,58 @@ class Checker {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A numeric literal next to a sized value takes that value's type: X + 1 with an INT8 X is INT8 arithmetic,
|
||||
* and 0.1 next to a FLOAT32 is the FLOAT32 nearest 0.1, as in Mojo. A whole-number literal that does not fit
|
||||
* the type is an error here, before any run. Returns the node's type afterwards.
|
||||
*/
|
||||
adopt(node, want, current = node?.type) {
|
||||
if (!isLiteral(node) || !want || isAny(want) || !isNumeric(want)) return current;
|
||||
if (isSizedInt(want) && !node.float) {
|
||||
const [lo, hi] = intRange(want);
|
||||
if (node.value < lo || node.value > hi) this.error('literal-range', node, `${sourceOf(node)} does not fit ${want.name}, which holds ${intRangeText(want)}.`, { guide: 'sized-types' });
|
||||
node.type = want;
|
||||
return want;
|
||||
}
|
||||
if (isFloat32(want)) { node.type = want; return want; }
|
||||
return current;
|
||||
}
|
||||
|
||||
/** In a binary operation, a literal on either side adopts the other side's sized type. */
|
||||
adoptPair(e, lt, rt) {
|
||||
if (isLiteral(e.left) && !isLiteral(e.right)) return [this.adopt(e.left, rt, lt), rt];
|
||||
if (isLiteral(e.right) && !isLiteral(e.left)) return [lt, this.adopt(e.right, lt, rt)];
|
||||
return [lt, rt];
|
||||
}
|
||||
|
||||
/** The type of +, -, *, DIV, MOD on two numbers, after literals adopt; two widths that do not mix are an error. */
|
||||
mix(e, lt0, rt0) {
|
||||
const [lt, rt] = this.adoptPair(e, lt0, rt0);
|
||||
if (lt.k === 'INTEGER' && rt.k === 'INTEGER' && lt.bits && rt.bits && !sameType(lt, rt)) {
|
||||
const [narrow, wide] = lt.bits <= rt.bits ? [e.left, rt] : [e.right, lt];
|
||||
this.error('mixed-width', e, `${sourceOf(e.left)} is ${lt.name} and ${sourceOf(e.right)} is ${rt.name}, and two different sized types do not mix silently. Convert one so both sides agree, as in ${wide.name}(${sourceOf(narrow)}).`, { guide: 'sized-types' });
|
||||
return T.ANY;
|
||||
}
|
||||
if (lt.k === 'FLOAT' && rt.k === 'FLOAT' && isFloat32(lt) !== isFloat32(rt)) {
|
||||
const [s32, s64] = isFloat32(lt) ? [e.left, e.right] : [e.right, e.left];
|
||||
this.error('mixed-precision', e, `${sourceOf(s32)} is FLOAT32 and ${sourceOf(s64)} is a FLOAT64, and the two precisions do not mix silently. Write FLOAT32(${sourceOf(s64)}) to round it to single precision, or FLOAT64(${sourceOf(s32)}) to widen the other side.`, { guide: 'sized-types' });
|
||||
return T.ANY;
|
||||
}
|
||||
return numericResult(lt, rt);
|
||||
}
|
||||
|
||||
/** INT32(X), FLOAT32(X), ...: one number, converted to the named type. */
|
||||
conversion(e, scope) {
|
||||
const to = SIZED[up(e.name)];
|
||||
const ts = e.args.map((a) => this.expr(a, scope));
|
||||
if (ts.length !== 1) { this.error('arg-count', e, `${up(e.name)}(X) converts one number, and this call gives it ${ts.length}.`); return to; }
|
||||
const t = ts[0];
|
||||
if (!isAny(t) && !isNumeric(t)) this.error('type', e.args[0], `${up(e.name)}(X) converts a number, and ${sourceOf(e.args[0])} is ${article(t)}.${isText(t) ? ' TO_INTEGER or TO_FLOAT reads a number out of text first.' : ''}`, { guide: 'sized-types' });
|
||||
else if (!isAny(t) && sameType(t, to) && t.name === to.name) this.note('already-type', e, `${sourceOf(e.args[0])} is already ${to.name}, so ${to.name}(...) changes nothing.`);
|
||||
if (isLiteral(e.args[0]) && to.k === 'INTEGER' && !e.args[0].float) this.adopt(e.args[0], to);
|
||||
return to;
|
||||
}
|
||||
|
||||
comparable(e, lt, rt, equality) {
|
||||
if (isAny(lt) || isAny(rt)) return;
|
||||
if (isNumeric(lt) && isNumeric(rt)) return;
|
||||
@@ -1032,7 +1122,8 @@ class Checker {
|
||||
}
|
||||
return t;
|
||||
}
|
||||
const sub = this.subs.get(name);
|
||||
if (e.convert) return this.conversion(e, scope);
|
||||
const sub = this.findSub(name);
|
||||
if (sub) {
|
||||
e.sub = sub;
|
||||
if (sub.kind === 'Procedure') {
|
||||
@@ -1047,7 +1138,7 @@ class Checker {
|
||||
if (!b) {
|
||||
const sym = scope.get(e.name);
|
||||
if (sym) { this.error('not-callable', e, `${e.name} is ${sym.kind === 'var' ? 'a variable' : 'not a subroutine'}, so it cannot be called. Square brackets reach a position: ${e.name}[I].`); return T.ANY; }
|
||||
const s = suggest(e.name, [...this.subs.values()].map((x) => x.name).concat(Object.keys(BUILTINS)));
|
||||
const s = suggest(e.name, [...this.subs.values(), ...this.libs.values()].map((x) => x.name).concat(Object.keys(BUILTINS)));
|
||||
const other = FOREIGN_FUNCTIONS[name];
|
||||
if (other) this.error('unknown-function', e, `No FUNCTION is called ${e.name}. ${other}`, { guide: 'function' });
|
||||
else this.error('unknown-function', e, `No FUNCTION is called ${e.name}.${s.length ? ` Did you mean ${s.join(' or ')}?` : ' Define it with FUNCTION ... ENDFUNCTION.'}`, { guide: 'function' });
|
||||
@@ -1060,7 +1151,7 @@ class Checker {
|
||||
return T.VOID;
|
||||
}
|
||||
e.builtin = name;
|
||||
const ts = e.args.map((a) => this.expr(a, scope));
|
||||
const ts = e.args.map((a, i) => this.expr(a, scope, { typeArg: TYPE_ARGS[name] === i }));
|
||||
const argc = (n) => {
|
||||
if (ts.length !== n) { this.error('arg-count', e, `${b.sig} takes ${n} ${n === 1 ? 'value' : 'values'}, and this call gives it ${ts.length}.`); return false; }
|
||||
return true;
|
||||
@@ -1181,13 +1272,84 @@ class Checker {
|
||||
case 'SORTED':
|
||||
if (argc(1) && !isAny(ts[0]) && !['LIST', 'SET', 'ARRAY'].includes(ts[0].k)) { this.error('type', e.args[0], `SORTED puts the values of a LIST or SET in order, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); return T.list(T.ANY); }
|
||||
return T.list(isAny(ts[0]) ? T.ANY : ts[0].of);
|
||||
// ---- numerical work
|
||||
case 'ASIN': case 'ACOS': case 'ATAN': case 'SINH': case 'COSH': case 'TANH': case 'CBRT': case 'EXPM1': case 'LOG1P':
|
||||
if (argc(1)) num(0);
|
||||
return T.FLOAT;
|
||||
case 'HYPOT': case 'POW': case 'COPYSIGN': if (argc(2)) { num(0); num(1); } return T.FLOAT;
|
||||
case 'E': case 'INF': case 'NAN': argc(0); return T.FLOAT;
|
||||
case 'TRUNC': if (argc(1)) { num(0); return ts[0].k === 'FLOAT' ? ts[0] : T.FLOAT; } return T.FLOAT;
|
||||
case 'SIGN': if (argc(1)) return isAny(num(0)) ? T.ANY : ts[0]; return T.ANY;
|
||||
case 'CLAMP': {
|
||||
if (!argc(3)) return T.ANY;
|
||||
ts.forEach((_, i) => num(i));
|
||||
if (ts.some((x) => isAny(x))) return T.ANY;
|
||||
for (const i of [1, 2]) this.adopt(e.args[i], ts[0]);
|
||||
return ts[0];
|
||||
}
|
||||
case 'FMA': {
|
||||
if (!argc(3)) return T.FLOAT;
|
||||
ts.forEach((_, i) => num(i));
|
||||
const f32 = ts.some((x) => isFloat32(x));
|
||||
if (f32) e.args.forEach((a) => this.adopt(a, T.FLOAT32));
|
||||
return f32 && e.args.every((a) => isFloat32(a.type) || a.type?.k === 'INTEGER') ? T.FLOAT32 : T.FLOAT;
|
||||
}
|
||||
case 'IS_NAN': case 'IS_INF': case 'IS_FINITE': if (argc(1)) num(0); return T.BOOL;
|
||||
case 'IS_CLOSE': if (argc(4)) ts.forEach((_, i) => num(i)); return T.BOOL;
|
||||
case 'ULP': case 'NEXT_AFTER': {
|
||||
if (!argc(name === 'ULP' ? 1 : 2)) return T.FLOAT;
|
||||
ts.forEach((_, i) => num(i));
|
||||
return isFloat32(ts[0]) ? ts[0] : T.FLOAT;
|
||||
}
|
||||
case 'EXACT': if (argc(1)) num(0); return T.STRING;
|
||||
case 'MAX_VALUE': case 'MIN_VALUE': case 'EPSILON': {
|
||||
if (!argc(1)) return T.ANY;
|
||||
const a = e.args[0];
|
||||
if (a.kind !== 'TypeRef') { this.error('type', a, `${name} takes the name of a numeric type, as in ${name}(${name === 'EPSILON' ? 'FLOAT64' : 'INT32'}).`, { guide: 'sized-types' }); return T.ANY; }
|
||||
const ty = T[a.name];
|
||||
if (name === 'EPSILON' && ty.k !== 'FLOAT') { this.error('type', a, `EPSILON measures the spacing of FLOAT values near 1.0; ${a.name} has none. For whole numbers the step is always 1.`, { guide: 'sized-types' }); return T.ANY; }
|
||||
if (ty.k === 'INTEGER' && !ty.bits) { this.error('type', a, `INTEGER has no ${name === 'MAX_VALUE' ? 'largest' : 'lowest'} value: it is a whole number of any size. Name a sized type, such as INT32.`, { guide: 'sized-types' }); return T.INTEGER; }
|
||||
if (ty.k === 'INTEGER' && ty.bits === 64 && (name === 'MAX_VALUE' || ty.signed)) { this.error('exact-limit', a, `${name}(${ty.name}) is ${name === 'MAX_VALUE' ? (ty.signed ? '9,223,372,036,854,775,807' : '18,446,744,073,709,551,615') : '-9,223,372,036,854,775,808'}, more than this lab holds exactly (9,007,199,254,740,991). Name a type up to 32 bits, or write the limit you need as a constant.`, { guide: 'sized-types' }); return ty; }
|
||||
return ty.k === 'FLOAT' && !ty.bits ? T.FLOAT : ty;
|
||||
}
|
||||
case 'GCD': case 'LCM': case 'BIT_AND': case 'BIT_OR': case 'BIT_XOR': {
|
||||
if (!argc(2)) return T.INTEGER;
|
||||
int(0); int(1);
|
||||
if (isAny(ts[0]) || isAny(ts[1])) return T.INTEGER;
|
||||
return this.mix({ ...e, left: e.args[0], right: e.args[1], op: name }, ts[0], ts[1]);
|
||||
}
|
||||
case 'BIT_NOT': if (argc(1)) { int(0); return ts[0].k === 'INTEGER' ? ts[0] : T.INTEGER; } return T.INTEGER;
|
||||
case 'SHIFT_LEFT': case 'SHIFT_RIGHT':
|
||||
if (argc(2)) { int(0); int(1); return ts[0].k === 'INTEGER' ? ts[0] : T.INTEGER; }
|
||||
return T.INTEGER;
|
||||
case 'WRAP': {
|
||||
if (!argc(2)) return T.ANY;
|
||||
int(0);
|
||||
// the arithmetic inside WRAP is exact (INTEGER), so that WRAP(Count + 1, UINT8) wraps instead of stopping at Count + 1
|
||||
const exact = (n) => {
|
||||
if (!n || typeof n !== 'object') return;
|
||||
if ((n.kind === 'Binary' || n.kind === 'Unary' || n.kind === 'Num') && isSizedInt(n.type)) n.type = T.INTEGER;
|
||||
if (n.kind === 'Binary') { exact(n.left); exact(n.right); } else if (n.kind === 'Unary') exact(n.arg);
|
||||
};
|
||||
exact(e.args[0]);
|
||||
const a = e.args[1];
|
||||
if (a.kind !== 'TypeRef' || !isSizedInt(T[a.name])) { this.error('type', a, 'WRAP takes a sized whole-number type as its second value, as in WRAP(X, UINT8).', { guide: 'sized-types' }); return T.ANY; }
|
||||
const ty = T[a.name];
|
||||
if (ty.bits > 32) { this.error('wrap-64', a, `WRAP works on types up to 32 bits in this lab, which holds whole numbers exactly only to 2^53 - 1; ${ty.name} wraps at 2^64.`, { guide: 'sized-types' }); return ty; }
|
||||
return ty;
|
||||
}
|
||||
default: return T.ANY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function check(parsed) {
|
||||
const c = new Checker(parsed);
|
||||
/**
|
||||
* @param {any} parsed
|
||||
* @param {{ libs?: Map<string, any>, libOrigin?: Map<string, { module: string, line: number }> }} [options]
|
||||
* libs: routines brought in with USE, already checked in their own files (UPPER name -> routine)
|
||||
*/
|
||||
export function check(parsed, options = {}) {
|
||||
const c = new Checker(parsed, options);
|
||||
const program = c.run();
|
||||
program.source = parsed.source;
|
||||
program.lines = parsed.lines;
|
||||
|
||||
Reference in new issue
Block a user