/** * pseudo/check.js * * Names and types. The checker works out what every name refers to and what * type every expression has, writes both onto the tree, and reports each * place where the notation's rules are broken. It also gathers each * subroutine's contracts (REQUIRE, ENSURE, DECREASES) and each loop's * (INVARIANT, DECREASES) into fields of their own, so the interpreter and the * verifier find them without searching. * * check(parsed) -> { program, diags } * * program = { * ast, types, setTypes, constants, defines, subs, main, * blanks: [ { line, col, text } ], template blanks still to fill * } */ 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'; /* ------------------------------------------------------------------ */ /* Helpers */ /* ------------------------------------------------------------------ */ const up = (s) => String(s).toUpperCase(); /** Function names from Python and Mojo, and what this notation writes instead. */ const FOREIGN_FUNCTIONS = { LEN: 'The length of a STRING or a collection is LENGTH(T).', RANGE: 'A loop over positions is FOR I <- 0 TO N ... NEXT I, and a range in a condition or a set is [0, N).', PRINT: 'Output is a statement of its own: OUTPUT X.', STR: 'TO_STRING(X) turns a value into text.', FLOAT: 'TO_FLOAT(X) turns a whole number or text into a FLOAT.', APPEND: null, ENUMERATE: 'FOR I <- 0 TO LENGTH(T) visits every position, and T[I] is the letter there.', ZIP: 'Walk both with one counter: FOR I <- 0 TO LENGTH(A), reading A[I] and B[I].', SUM: 'Add up in a loop with a running total, or write SUM K IN [0, N) : L[K] inside a specification.', SORT: null, SORTED: null, REVERSED: 'Build the reverse in a loop that walks from the last position down: FOR I <- LENGTH(T) - 1 TO -1 STEP -1.', JOIN: 'Join text with &, as in A & B.', SPLIT: 'This notation has no SPLIT. Walk the text one letter at a time with a FOR loop.', INPUT: 'INPUT is a statement of its own: INPUT X reads the next value into X.', }; for (const k of Object.keys(FOREIGN_FUNCTIONS)) if (!FOREIGN_FUNCTIONS[k]) delete FOREIGN_FUNCTIONS[k]; /** Type names from Python and Mojo, and this notation's word for each. */ const FOREIGN_TYPES = { 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 TO ', MAP: 'HASHMAP OF TO ', ARRAYLIST: 'LIST OF ', }; /** The closest few names to a misspelt one, by edit distance. */ export function suggest(name, candidates) { const n = up(name); const scored = []; for (const c of candidates) { const d = editDistance(n, up(c)); if (d <= Math.max(1, Math.floor(n.length / 3))) scored.push([d, c]); } scored.sort((a, b) => a[0] - b[0]); return scored.slice(0, 2).map((x) => x[1]); } const article = (t) => { if (!t || t.k === 'ANY') return 'a value'; const w = typeName(t); return /^[AEIOU]/.test(w) ? `an ${w}` : `a ${w}`; }; function elementOf(t) { if (!t) return T.ANY; switch (t.k) { case 'STRING': return T.CHAR; case 'LIST': case 'SET': case 'ARRAY': return t.of; case 'HASHMAP': return t.key; case 'RANGE': return T.INTEGER; default: return null; } } /** * 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; 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) { if (s.kind === 'Return') return true; if (s.kind === 'If' && s.elseBody && s.branches.every((b) => alwaysReturns(b.body)) && alwaysReturns(s.elseBody)) return true; if (s.kind === 'Case' && s.otherwise && s.arms.every((a) => alwaysReturns(a.body)) && alwaysReturns(s.otherwise)) return true; } return false; } /* ------------------------------------------------------------------ */ /* Scopes */ /* ------------------------------------------------------------------ */ /** * A scope maps an uppercase name to a symbol: * { name, type, kind, line, col, readOnly } * kind is 'var', 'param', 'counter', 'each', 'bound' (a quantifier's name), * 'const', or 'define'. */ class Scope { constructor(parent, owner) { this.parent = parent; this.owner = owner; this.map = new Map(); } get(name) { const k = up(name); return this.map.get(k) ?? this.parent?.get(k); } own(name) { return this.map.get(up(name)); } set(name, sym) { this.map.set(up(name), sym); return sym; } all() { const out = this.parent ? this.parent.all() : new Map(); for (const [k, v] of this.map) out.set(k, v); return out; } } /* ------------------------------------------------------------------ */ /* The checker */ /* ------------------------------------------------------------------ */ class Checker { 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 ... this.constants = new Map(); this.defines = new Map(); this.subs = new Map(); this.blanks = []; this.global = new Scope(null, 'global'); this.mainScope = new Scope(this.global, 'main'); 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 })); } blank(node, text) { this.blanks.push({ line: node.line, col: node.col, text }); this.diags.push(diag('error', 'blank', node.line, `<${text}> is a blank to fill in before this can run.`, { col: node.col })); } /* ---------- pass 1: everything global ---------- */ collect(body) { for (const s of body) { if (s.kind === 'TypeDef') { if (this.types.has(up(s.name)) || this.setTypes.has(up(s.name))) this.error('duplicate', s, `A type called ${s.name} is already defined.`); this.types.set(up(s.name), { k: 'RECORD', name: s.name, fields: new Map(), fieldNames: [], node: s }); } else if (s.kind === 'SetTypeDef') { this.setTypes.set(up(s.name), { k: 'SET', of: T.ANY, name: s.name, node: s }); } 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)] && !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}..`, { guide: 'libraries' }); else this.subs.set(up(s.name), { name: s.name, kind: s.kind, node: s, params: [], returns: null, requires: [], ensures: [], decreases: null }); } } // Field and element types, now that every type name is known. for (const rt of this.types.values()) { for (const f of rt.node.fields) { if (rt.fields.has(up(f.name)) && !f.name.startsWith('<')) this.error('duplicate', f, `${rt.name} already has a field called ${f.name}.`); rt.fields.set(up(f.name), this.resolveType(f.type, f)); rt.fieldNames.push(f.name); } } for (const st of this.setTypes.values()) st.of = this.resolveType(st.node.of, st.node); for (const sub of this.subs.values()) { const s = sub.node; for (const p of s.params) { const type = this.resolveType(p.type, p); if (p.mode === 'BYREF' && s.kind === 'Function') { this.error('function-byref', p, `Parameters of a FUNCTION are always by value, so ${p.name} cannot be BYREF. A subroutine that changes its caller's variables is a PROCEDURE.`, { guide: 'passing-by-value-or-by-reference' }); } sub.params.push({ name: p.name, type, mode: s.kind === 'Function' ? 'BYVAL' : p.mode, line: p.line, col: p.col }); } sub.returns = s.kind === 'Function' ? (s.returns ? this.resolveType(s.returns, s) : T.ANY) : T.VOID; } // Constants and sets, in order, since one may use another. for (const s of body) { if (s.kind === 'Constant') { if (this.constants.has(up(s.name))) { this.error('duplicate', s, `The constant ${s.name} is already defined.`); continue; } this.ctx = { scope: this.global, constOnly: true }; const type = this.expr(s.value, this.global); this.ctx = null; const sym = { name: s.name, type, kind: 'const', line: s.line, col: s.col, readOnly: true, node: s }; this.constants.set(up(s.name), sym); this.global.set(s.name, sym); s.type = type; } else if (s.kind === 'Define') { const st = this.setTypes.get(up(s.typeName || '')); if (!st && !String(s.typeName).startsWith('<')) this.error('unknown-type', s, `DEFINE ${s.name} names the set type ${s.typeName}, and no TYPE ${s.typeName} = SET OF ... is defined.`, { guide: 'set-for-membership' }); const type = st || T.set(T.ANY); this.ctx = { scope: this.global, constOnly: true }; for (const v of s.values) { const vt = this.expr(v, this.global); if (st && !assignable(st.of, vt)) this.error('type', v, `${sourceOf(v)} is ${article(vt)}, and ${st.name} holds ${typeName(st.of)} values.`); } this.ctx = null; const sym = { name: s.name, type, kind: 'define', line: s.line, col: s.col, readOnly: true, node: s }; this.defines.set(up(s.name), sym); this.global.set(s.name, sym); s.type = type; } } } resolveType(tn, at) { if (!tn) return T.ANY; switch (tn.tk) { case 'scalar': return T[tn.name]; case 'list': return T.list(this.resolveType(tn.of, at)); case 'set': return T.set(this.resolveType(tn.of, at)); case 'map': { const key = this.resolveType(tn.key, at); if (key.k === 'FLOAT') this.warn('float-key', tn, 'A FLOAT key finds its value only when the key is exactly equal, and two measurements rarely are. Round to an INTEGER first.'); if (!['INTEGER', 'CHAR', 'STRING', 'BOOL', 'FLOAT', 'ANY'].includes(key.k)) this.error('bad-key', tn, `A HASHMAP key is a single value: INTEGER, CHAR, STRING, or BOOL, not ${typeName(key)}.`); return T.map(key, this.resolveType(tn.val, at)); } case 'array': { for (const d of tn.dims) { const dt = this.expr(d, this.ctx?.scope || this.mainScope); if (!isAny(dt) && dt.k !== 'INTEGER') this.error('type', d, `An ARRAY's length is a whole number, and ${sourceOf(d)} is ${article(dt)}.`); } return { ...T.array(this.resolveType(tn.of, at), tn.dims.length), dimExprs: tn.dims }; } case 'named': { const r = this.types.get(up(tn.name)) || this.setTypes.get(up(tn.name)); if (r) return r; const s = suggest(tn.name, [...this.types.values(), ...this.setTypes.values()].map((x) => x.name).concat(['INTEGER', 'FLOAT', 'CHAR', 'STRING', 'BOOL'])); const other = FOREIGN_TYPES[up(tn.name)]; if (other) this.error('unknown-type', tn, `${tn.name} is not a type here. Write ${other}.`, { guide: 'the-types' }); else this.error('unknown-type', tn, `${tn.name} is not a type.${s.length ? ` Did you mean ${s.join(' or ')}?` : ' Define it with TYPE ... ENDTYPE first.'}`, { guide: 'the-types' }); return T.ANY; } case 'blank': this.blank(tn, tn.text); return T.ANY; default: return T.ANY; } } /* ---------- pass 2: bodies ---------- */ run() { const ast = this.parsed.ast; this.collect(ast.body); const mainBody = []; for (const s of ast.body) { 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); } this.ctx = { scope: this.mainScope, sub: null, loops: [], counters: [] }; this.liftContracts(mainBody, 'main'); this.block(mainBody, this.mainScope); this.ctx = null; return { ast, types: this.types, setTypes: this.setTypes, 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, }; } /** REQUIRE and ENSURE at the head of a body move onto the subroutine. */ liftContracts(body, where, sub = null) { let head = true; for (let i = 0; i < body.length; i++) { const s = body[i]; const isContract = s.kind === 'Require' || s.kind === 'Ensure'; if (isContract && where === 'main') { this.error('contract-place', s, `${s.kind.toUpperCase()} belongs directly under a FUNCTION or PROCEDURE line. To check a condition in the main program, write ASSERT.`, { guide: 'contracts' }); s.reported = true; continue; } if (s.kind === 'Decreases' && where === 'sub' && head) { sub.decreases = s; s.lifted = true; continue; } if (isContract) { if (!head) { this.error('contract-place', s, `${s.kind.toUpperCase()} goes directly under the ${sub.kind.toUpperCase()} line, before any other line of the body.`, { guide: 'contracts' }); s.reported = true; } else { (s.kind === 'Require' ? sub.requires : sub.ensures).push(s); s.lifted = true; } continue; } head = false; } for (let i = body.length - 1; i >= 0; i--) if (body[i].lifted) body.splice(i, 1); } subroutine(sub) { const s = sub.node; const scope = new Scope(this.global, s.name); sub.scope = scope; for (const p of sub.params) { if (p.name.startsWith('<')) { this.blank(p, p.name.slice(1, -1)); continue; } if (scope.own(p.name)) this.error('duplicate', p, `Two parameters are called ${p.name}.`); if (this.global.get(p.name)) this.warn('shadow', p, `Parameter ${p.name} has the same name as the ${this.global.get(p.name).kind === 'const' ? 'constant' : 'set'} ${this.global.get(p.name).name}, which it hides inside ${s.name}.`); scope.set(p.name, { name: p.name, type: p.type, kind: 'param', mode: p.mode, line: p.line, col: p.col }); } this.liftContracts(s.body, 'sub', sub); this.ctx = { scope, sub, loops: [], counters: [] }; for (const r of sub.requires) this.condition(r.expr, scope, 'REQUIRE'); this.ctx.inEnsure = true; for (const e of sub.ensures) this.condition(e.expr, scope, 'ENSURE'); this.ctx.inEnsure = false; if (sub.decreases) { const dt = this.expr(sub.decreases.expr, scope); if (!isAny(dt) && dt.k !== 'INTEGER') this.error('type', sub.decreases, 'DECREASES needs a whole number that gets smaller with every recursive call.'); } this.block(s.body, scope); if (s.kind === 'Function' && !alwaysReturns(s.body) && s.endLine && !s.body.some((x) => x.kind === 'BlankStmt')) { this.error('missing-return', { line: s.endLine, col: 1 }, `FUNCTION ${s.name} can reach ENDFUNCTION without a RETURN, and a function has to hand back ${article(sub.returns)} on every path.`, { guide: 'function' }); } sub.symbols = [...scope.map.values()]; this.ctx = null; } block(body, scope) { for (const s of body) this.statement(s, scope); } /** Names a loop creates are visible only inside it. */ childScope(scope) { const c = new Scope(scope, scope.owner); c.map = scope.map; return c; } declareName(name, sym, scope, node) { const k = up(name); const prior = scope.own(name); if (prior) { if (prior.node === node) return prior; // the same DECLARE, reached again this.error('duplicate', node, `${name} is already declared on line ${prior.line}${prior.kind === 'param' ? ' as a parameter' : ''}. One name per idea, throughout an algorithm.`, { guide: 'names' }); return prior; } 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.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); } statement(s, scope) { const ctx = this.ctx; switch (s.kind) { case 'Declare': { const type = this.resolveType(s.type, s); s.resolved = type; for (const n of s.names) { if (n.blank) { this.blank(n, n.name.slice(1, -1)); continue; } this.declareName(n.name, { name: n.name, type, kind: 'var', line: s.line, col: n.col, node: s }, scope, s); } return; } case 'TypeDef': case 'SetTypeDef': case 'Constant': case 'Define': 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; const t = this.target(s.target, scope, 'INPUT'); if (t && !isAny(t) && !['INTEGER', 'FLOAT', 'CHAR', 'STRING', 'BOOL'].includes(t.k)) this.error('type', s, `INPUT fills one value, and ${sourceOf(s.target)} is ${article(t)}. Read the values one at a time in a loop.`, { guide: 'input-and-output' }); return; } case 'Output': for (const v of s.values) { const t = this.expr(v, scope); if (t.k === 'VOID') this.error('type', v, `${sourceOf(v)} hands nothing back, so there is nothing to show.`); } return; case 'If': for (const b of s.branches) { this.condition(b.cond, scope, b === s.branches[0] ? 'IF' : 'ELSEIF'); this.block(b.body, scope); } if (s.elseBody) this.block(s.elseBody, scope); return; case 'Case': this.caseStmt(s, scope); return; case 'For': this.forStmt(s, scope); return; case 'ForEach': this.forEach(s, scope); return; case 'While': { this.condition(s.cond, scope, 'WHILE'); this.loopBody(s, scope); return; } case 'Repeat': { this.loopBody(s, scope); if (s.cond) this.condition(s.cond, scope, 'UNTIL'); return; } case 'Break': case 'Continue': if (!ctx.loops.length) this.error('outside-loop', s, `${s.kind.toUpperCase()} works only inside a loop, and this line is not inside one.`, { guide: 'leaving-a-loop-early' }); return; case 'Return': this.returnStmt(s, scope); return; case 'Call': this.callStmt(s, scope); return; case 'BuiltinCall': this.builtinStmt(s, scope); return; case 'ExprStmt': this.exprStmt(s, scope); return; case 'Assert': this.condition(s.expr, scope, 'ASSERT'); return; case 'Invariant': case 'Decreases': this.error('contract-place', s, `${s.kind.toUpperCase()} goes at the top of a loop's body, before any other line of it.`, { guide: 'contracts' }); this.expr(s.expr, scope); return; case 'Require': case 'Ensure': if (!s.reported) this.error('contract-place', s, `${s.kind.toUpperCase()} goes directly under a FUNCTION or PROCEDURE line.`, { guide: 'contracts' }); return; case 'BlankStmt': this.blank(s, s.text); return; default: return; } } /** INVARIANT and DECREASES at the top of a loop body belong to the loop. */ loopBody(loop, scope) { loop.invariants = []; loop.decreases = null; const body = loop.body; let i = 0; while (i < body.length && (body[i].kind === 'Invariant' || body[i].kind === 'Decreases')) { if (body[i].kind === 'Invariant') loop.invariants.push(body[i]); else if (loop.decreases) this.error('duplicate', body[i], 'A loop has one DECREASES.'); else loop.decreases = body[i]; i++; } body.splice(0, i); this.ctx.loops.push(loop); const inner = this.childScope(scope); for (const inv of loop.invariants) this.condition(inv.expr, scope, 'INVARIANT'); if (loop.decreases) { const dt = this.expr(loop.decreases.expr, scope); if (!isAny(dt) && dt.k !== 'INTEGER') this.error('type', loop.decreases, `DECREASES needs a whole number that gets smaller on every pass, and ${sourceOf(loop.decreases.expr)} is ${article(dt)}.`, { guide: 'contracts' }); } this.block(body, inner); this.ctx.loops.pop(); } forStmt(s, scope) { for (const [e, what] of [[s.start, 'start'], [s.stop, 'stop'], [s.step, 'step']]) { if (!e) continue; const t = this.expr(e, scope); if (!isAny(t) && t.k !== 'INTEGER') { this.error('type', e, `A FOR counter counts in whole numbers, and its ${what} value ${sourceOf(e)} is ${article(t)}.${t.k === 'FLOAT' ? ' Use INT or ROUND, or a WHILE loop for a FLOAT that changes.' : ''}`, { guide: 'for-when-you-know-how-many-times' }); } } if (s.step && s.step.kind === 'Num' && s.step.value === 0) this.error('zero-step', s.step, 'STEP 0 never moves the counter, so the loop would never end.'); if (s.var.startsWith('<')) { this.blank(s, s.var.slice(1, -1)); this.loopBody(s, scope); return; } const existing = scope.get(s.var); if (existing && (existing.kind === 'counter' || existing.kind === 'each')) { this.error('counter-reuse', s, `${s.var} is already the counter of the loop on line ${existing.line}. A nested loop needs a counter of its own, such as J.`, { guide: 'nested-loops' }); } if (existing && existing.kind === 'var') { if (!isAny(existing.type) && existing.type.k !== 'INTEGER') this.error('type', s, `${s.var} is declared ${typeName(existing.type)}, and a FOR counter holds whole numbers.`); s.declaredCounter = existing; } else if (existing && existing.kind === 'param') { this.error('counter-param', s, `${s.var} is a parameter, and a FOR loop needs a counter of its own.`); } else if (existing && (existing.kind === 'const' || existing.kind === 'define')) { this.error('counter-const', s, `${s.var} is a constant, and a FOR loop needs a counter it can change.`); } const inner = this.childScope(scope); const prior = inner.map.get(up(s.var)); const sym = { name: s.var, type: T.INTEGER, kind: 'counter', line: s.line, col: s.varCol, readOnly: true, loop: s }; inner.map.set(up(s.var), sym); s.counterSym = sym; this.loopBodyWith(s, inner); if (prior) inner.map.set(up(s.var), prior); else inner.map.delete(up(s.var)); } /** loopBody, with the counter already in scope for the invariants. */ loopBodyWith(loop, inner) { loop.invariants = []; loop.decreases = null; const body = loop.body; let i = 0; while (i < body.length && (body[i].kind === 'Invariant' || body[i].kind === 'Decreases')) { if (body[i].kind === 'Invariant') loop.invariants.push(body[i]); else loop.decreases = body[i]; i++; } body.splice(0, i); this.ctx.loops.push(loop); for (const inv of loop.invariants) this.condition(inv.expr, inner, 'INVARIANT'); if (loop.decreases) this.expr(loop.decreases.expr, inner); this.block(body, inner); this.ctx.loops.pop(); } forEach(s, scope) { let elem = T.ANY; if (s.iterable) { const t = this.expr(s.iterable, scope, { rangeOk: true }); if (t.k === 'ARRAY' && t.dims === 2) this.error('type', s.iterable, 'FOR EACH visits a one-dimensional collection. For a two-dimensional ARRAY, nest two FOR loops over ROWS and COLUMNS.'); else if (!isAny(t)) { elem = elementOf(t); if (!elem) { this.error('type', s.iterable, `FOR EACH visits the values of a STRING, LIST, ARRAY, SET, or HASHMAP, and ${sourceOf(s.iterable)} is ${article(t)}.`); elem = T.ANY; } } if (t.k === 'SET' || t.k === 'HASHMAP') s.unordered = true; } const existing = scope.get(s.var); if (existing && (existing.kind === 'var' || existing.kind === 'param')) this.error('each-shadow', s, `${s.var} is already a ${existing.kind === 'param' ? 'parameter' : 'variable'} (line ${existing.line}). FOR EACH needs a fresh name for the value it visits.`); const inner = this.childScope(scope); const prior = inner.map.get(up(s.var)); const sym = { name: s.var, type: elem, kind: 'each', line: s.line, col: s.varCol, readOnly: true, loop: s }; inner.map.set(up(s.var), sym); s.eachSym = sym; this.loopBodyWith(s, inner); if (prior) inner.map.set(up(s.var), prior); else inner.map.delete(up(s.var)); } caseStmt(s, scope) { const st = s.subject ? this.expr(s.subject, scope) : T.ANY; const seen = new Map(); for (const arm of s.arms) { for (const lab of arm.labels) { if (lab.value) { const lt = this.expr(lab.value, scope); this.caseLabelType(st, lt, lab.value, s); if (['Num', 'Str', 'Char', 'Bool'].includes(lab.value.kind)) { const key = `${lab.value.kind}:${lab.value.value}`; if (seen.has(key)) this.warn('case-duplicate', lab.value, `${sourceOf(lab.value)} already has a branch on line ${seen.get(key)}, and CASE runs only the first branch that matches, so this one never runs.`, { guide: 'case' }); else seen.set(key, arm.line); } } else { const a = this.expr(lab.low, scope); const b = this.expr(lab.high, scope); this.caseLabelType(st, a, lab.low, s); this.caseLabelType(st, b, lab.high, s); if (!isAny(st) && !isNumeric(st) && st.k !== 'CHAR') this.error('type', lab.low, `A range in a CASE needs values that come in order, such as numbers, and the CASE tests ${article(st)}.`); } } this.block(arm.body, scope); } if (s.otherwise) this.block(s.otherwise, scope); } caseLabelType(subjectType, labelType, node, s) { if (isAny(subjectType) || isAny(labelType)) return; if (isNumeric(subjectType) && isNumeric(labelType)) return; if (!sameType(subjectType, labelType)) { const extra = subjectType.k === 'CHAR' && labelType.k === 'STRING' ? ` Single quotes make a CHAR: write '${node.value}'.` : subjectType.k === 'STRING' && labelType.k === 'CHAR' ? ` Double quotes make a STRING: write "${node.value}".` : ''; this.error('type', node, `CASE OF ${sourceOf(s.subject)} tests ${article(subjectType)}, and ${sourceOf(node)} is ${article(labelType)}, so this branch can never match.${extra}`, { guide: 'the-types' }); } } returnStmt(s, scope) { const sub = this.ctx.sub; if (!sub) { this.error('return-main', s, 'RETURN belongs inside a FUNCTION or PROCEDURE. The main program ends at its last line.', { guide: 'function' }); if (s.value) this.expr(s.value, scope); return; } if (sub.kind === 'Procedure') { if (s.value) { this.error('procedure-value', s, `A PROCEDURE hands nothing back, so its RETURN takes no value. ${sub.name} would need to be a FUNCTION to return ${sourceOf(s.value)}.`, { guide: 'procedure' }); this.expr(s.value, scope); } 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.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.'; } if (to.k === 'CHAR' && from.k === 'STRING' && value?.kind === 'Str' && Array.from(value.value).length === 1) return ` Single quotes make a CHAR: '${value.value}'.`; return ''; } assign(s, scope) { const tt = this.target(s.target, scope, 'assign'); 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; if (!assignable(tt, vt)) { this.error('type', s.value, `${sourceOf(s.target)} holds ${typeName(tt)} values, and ${sourceOf(s.value)} is ${article(vt)}.${this.narrowHint(tt, vt, s.value)}`, { guide: 'the-types' }); } } /** Something that can receive a value; returns its type. */ target(e, scope, why) { if (!e) return T.ANY; if (e.kind === 'Name') { const sym = this.lookup(e, scope, why === 'assign' ? 'assign' : 'read'); if (!sym) return T.ANY; if (sym.kind === 'counter') this.error('counter-assign', e, `The FOR loop on line ${sym.line} owns ${sym.name}, and changing it inside the loop hides the loop's shape from a reader. Use a WHILE loop if the counter has to jump.`, { guide: 'for-when-you-know-how-many-times' }); else if (sym.kind === 'each') this.error('counter-assign', e, `${sym.name} is the value FOR EACH is visiting, and it cannot be changed from inside the loop.`); else if (sym.kind === 'const') this.error('const-assign', e, `${sym.name} is a CONSTANT, so its value cannot change.`, { guide: 'constants' }); else if (sym.kind === 'define') this.error('const-assign', e, `${sym.name} is a set made with DEFINE, so its members are fixed.`); e.type = sym.type; return sym.type; } if (e.kind === 'Index') { const t = this.expr(e, scope, { target: true }); const base = this.rootType(e.target, scope); if (base && base.k === 'STRING' && e.target.type?.k === 'STRING') { this.error('string-write', e, `A STRING cannot be changed one position at a time. Build a new one with &, or keep the letters in a LIST OF CHAR while you change them.`, { guide: 'text-and-positions' }); } this.rootWritable(e, scope); return t; } if (e.kind === 'Field') { const t = this.expr(e, scope); this.rootWritable(e, scope); return t; } if (e.kind === 'Blank') { this.blank(e, e.text); return T.ANY; } this.error('bad-target', e, `${sourceOf(e)} cannot receive a value. Only a name, a position such as T[I], or a field such as R.Name can.`); return T.ANY; } rootType(e) { return e.type; } rootWritable(e, scope) { let r = e; while (r.kind === 'Index' || r.kind === 'Field') r = r.target; if (r.kind === 'Name') { const sym = scope.get(r.name); if (sym && (sym.kind === 'const' || sym.kind === 'define')) this.error('const-assign', r, `${sym.name} is fixed, so no part of it can change.`); if (sym && sym.kind === 'each') this.error('counter-assign', r, `${sym.name} is the value FOR EACH is visiting. Changing it would not change the collection.`); } } lookup(e, scope, how = 'read') { const name = e.name; if (name.startsWith('<')) { this.blank(e, name.slice(1, -1)); return null; } const sym = scope.get(name); if (sym) { if (sym.name !== name && sym.kind !== 'bound') { this.note('name-case', e, `${name} is written ${sym.name} where it was ${sym.kind === 'param' ? 'named' : 'declared'} on line ${sym.line}. Names ignore case, so this is the same name; pick one spelling and hold it.`, { guide: 'names' }); } if (sym.kind === 'var' && sym.line > e.line && !this.ctx?.loops?.length) { this.error('before-declare', e, `${name} is used on line ${e.line} and declared on line ${sym.line}. Declare a variable before using it.`, { guide: 'declaring' }); } e.sym = sym; return sym; } if (this.ctx?.inEnsure && up(name) === 'RESULT' && this.ctx.sub?.kind === 'Function') { e.sym = { name: 'RESULT', type: this.ctx.sub.returns, kind: 'result' }; return e.sym; } // A function reaching for a name in the main program. const mainSym = this.mainScope.own(name); if (this.ctx?.sub && mainSym) { this.error('outer-name', e, `${name} belongs to the main program, and ${this.ctx.sub.name} can see only its own parameters and variables. Pass ${name} in as a parameter.`, { guide: 'function' }); e.sym = mainSym; return mainSym; } 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); const verb = how === 'assign' ? 'Declare it before assigning to it' : 'Declare it, and give it a value, before reading it'; this.error('undeclared', e, `${name} has not been declared.${s.length ? ` Did you mean ${s.join(' or ')}?` : ` ${verb}: DECLARE ${name} : .`}`, { guide: 'declaring' }); return null; } condition(e, scope, word) { if (!e) return; const t = this.expr(e, scope); if (isAny(t) || t.k === 'BOOL') return; let hint = ''; if (isNumeric(t)) hint = ` Compare it with something, as in ${sourceOf(e)} > 0.`; if (e.kind === 'Binary' && e.op === '<-') hint = ' <- stores a value; == compares two.'; this.error('not-bool', e, `${word} needs a condition that is TRUE or FALSE, and ${sourceOf(e)} is ${article(t)}.${hint}`, { guide: 'comparison' }); } callStmt(s, scope) { 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.`); this.builtinStmt({ ...s, kind: 'BuiltinCall', name: up(s.name) }, scope); s.builtin = true; return; } 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; } if (sub.kind === 'Function') { this.error('call-function', s, `${sub.name} is a FUNCTION, so its answer would be thrown away. A function call stands where a value stands: X <- ${sub.name}(...).`, { guide: 'procedure' }); } s.sub = sub; this.args(sub, s.args, s, scope); } args(sub, args, at, scope) { // Two BYREF parameters bound to one variable would be two names for one // box, and every claim about either one would stop meaning what it says. const byref = new Map(); args.forEach((a, i) => { const p = sub.params[i]; if (!p || p.mode !== 'BYREF' || a.kind !== 'Name') return; const k = up(a.name); if (byref.has(k)) this.error('byref-alias', a, `${a.name} is passed to both ${byref.get(k)} and ${p.name}, which are BYREF. Each BYREF parameter needs a variable of its own, or a change through one name would silently change the other.`, { guide: 'passing-by-value-or-by-reference' }); else byref.set(k, p.name); }); if (args.length !== sub.params.length) { this.error('arg-count', at, `${sub.name} takes ${sub.params.length} ${sub.params.length === 1 ? 'value' : 'values'} (${sub.params.map((p) => p.name).join(', ') || 'none'}), and this call gives it ${args.length}.`, { guide: 'function' }); } args.forEach((a, i) => { const p = sub.params[i]; 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 { const sym = a.sym; if (sym && (sym.kind === 'const' || sym.kind === 'define' || sym.kind === 'counter' || sym.kind === 'each')) this.error('byref-arg', a, `${sym.name} cannot be changed, so it cannot be passed to the BYREF parameter ${p.name}.`); if (!isAny(t) && !isAny(p.type) && !sameType(t, p.type)) this.error('type', a, `BYREF parameter ${p.name} is ${article(p.type)}, and ${sourceOf(a)} is ${article(t)}. A BYREF argument has to match exactly, since the procedure writes back into it.`); } return; } if (!isAny(t) && !isAny(p.type) && !assignable(p.type, t) && !(p.type.k === 'STRING' && t.k === 'CHAR')) { const extra = p.type.k === 'CHAR' && t.k === 'STRING' && a.kind === 'Str' && Array.from(a.value).length === 1 ? ` Single quotes make a CHAR: '${a.value}'.` : ''; this.error('type', a, `Parameter ${p.name} of ${sub.name} is ${article(p.type)}, and ${sourceOf(a)} is ${article(t)}.${extra}`, { guide: 'function' }); } }); } exprStmt(s, scope) { const e = s.expr; if (e.kind === 'CallExpr') { 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; this.args(sub, e.args, e, scope); return; } if (sub && sub.kind === 'Function') { this.error('call-alone', s, `${sub.name} is a FUNCTION: a call stands where a value stands, so it goes inside an expression, and never on a line of its own. Store its answer, as in X <- ${sourceOf(e)}, or OUTPUT it.`, { guide: 'function' }); this.expr(e, scope); return; } if (BUILTINS[up(e.name)]?.kind === 'function') { this.error('call-alone', s, `${up(e.name)} computes a value, and on a line of its own that value is thrown away. Store it or OUTPUT it.`); this.expr(e, scope); return; } this.expr(e, scope); return; } this.error('bare-value', s, `${sourceOf(e)} on a line of its own does nothing.`); } builtinStmt(s, scope) { const name = s.name; const spec = BUILTINS[name]; const [first, ...rest] = s.args; const need = { APPEND: 2, INSERT: 3, REMOVE: 2, ADD: 2, DELETE: 2, SORT: 1 }[name]; if (s.args.length !== need) { this.error('arg-count', s, `${spec.sig} takes ${need} ${need === 1 ? 'value' : 'values'}, and this line gives it ${s.args.length}.`); for (const a of s.args) this.expr(a, scope); return; } if (!['Name', 'Index', 'Field'].includes(first.kind)) { this.error('bad-target', first, `${name} changes its first argument, so that has to be a variable, not ${sourceOf(first)}.`); for (const a of rest) this.expr(a, scope); return; } const ct = this.target(first, scope, 'mutate'); const types = rest.map((a) => this.expr(a, scope)); if (isAny(ct)) return; const want = (kinds, what) => { if (!kinds.includes(ct.k)) { let extra = ''; if (ct.k === 'ARRAY' && name === 'APPEND') extra = ' An ARRAY\'s length is fixed when it is declared. Use a LIST when you do not know how many values are coming.'; if (ct.k === 'STRING' && name === 'APPEND') extra = ' Join text with &: T <- T & \'A\'.'; this.error('type', first, `${name} works on ${what}, and ${sourceOf(first)} is ${article(ct)}.${extra}`, { guide: 'collections' }); return false; } return true; }; const checkElem = (t, node, of, role) => { if (!isAny(t) && !isAny(of) && !assignable(of, t) && !(of.k === 'STRING' && t.k === 'CHAR')) this.error('type', node, `${sourceOf(first)} holds ${typeName(of)} values, and the ${role} ${sourceOf(node)} is ${article(t)}.`); }; const checkIndex = (t, node) => { if (!isAny(t) && t.k !== 'INTEGER') this.error('type', node, `A position is a whole number, and ${sourceOf(node)} is ${article(t)}.`); }; switch (name) { case 'APPEND': if (want(['LIST'], 'a LIST')) checkElem(types[0], rest[0], ct.of, 'value'); break; case 'INSERT': if (want(['LIST'], 'a LIST')) { checkIndex(types[0], rest[0]); checkElem(types[1], rest[1], ct.of, 'value'); } break; case 'REMOVE': if (ct.k === 'SET' || ct.k === 'HASHMAP') { this.error('type', s, `REMOVE takes a position out of a LIST. To take ${ct.k === 'SET' ? 'a member out of a SET' : 'a key out of a HASHMAP'}, use DELETE.`); break; } if (want(['LIST'], 'a LIST')) checkIndex(types[0], rest[0]); break; case 'ADD': if (want(['SET'], 'a SET')) checkElem(types[0], rest[0], ct.of, 'member'); break; case 'DELETE': if (ct.k === 'LIST') { this.error('type', s, 'DELETE works on a SET or a HASHMAP. To take a position out of a LIST, use REMOVE.'); break; } if (want(['SET', 'HASHMAP'], 'a SET or a HASHMAP')) checkElem(types[0], rest[0], ct.k === 'SET' ? ct.of : ct.key, ct.k === 'SET' ? 'member' : 'key'); break; case 'SORT': if (want(['LIST', 'ARRAY'], 'a LIST or a one-dimensional ARRAY') && ct.k === 'ARRAY' && ct.dims === 2) this.error('type', first, 'SORT works on a one-dimensional collection.'); break; default: break; } s.targetType = ct; } /* ---------- expressions ---------- */ expr(e, scope, opts = {}) { const t = this.exprInner(e, scope, opts) || T.ANY; e.type = t; return t; } exprInner(e, scope, opts) { if (!e) return T.ANY; switch (e.kind) { case 'Num': return e.float ? T.FLOAT : T.INTEGER; case 'Str': return T.STRING; case 'Char': return T.CHAR; 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); if (!sym || (sym.kind !== 'const' && sym.kind !== 'define')) { this.error('const-expr', e, `A CONSTANT's value can use only literals and other constants, and ${e.name} is not one.`, { guide: 'constants' }); return T.ANY; } e.sym = sym; return sym.type; } const sym = this.lookup(e, scope); return sym ? sym.type : T.ANY; } case 'Unary': { const t = this.expr(e.arg, scope); if (e.op === 'NOT') { if (!isAny(t) && t.k !== 'BOOL') this.error('type', e, `NOT needs a TRUE-or-FALSE value, and ${sourceOf(e.arg)} is ${article(t)}.`); return T.BOOL; } if (!isAny(t) && !isNumeric(t)) this.error('type', e, `Only a number can be negated, and ${sourceOf(e.arg)} is ${article(t)}.`); return isAny(t) ? T.ANY : t; } case 'Binary': return this.binary(e, scope, opts); case 'Chain': { for (let i = 0; i < e.ops.length; i++) { const fake = { kind: 'Binary', op: e.ops[i], left: e.operands[i], right: e.operands[i + 1], line: e.line, col: e.col }; this.binary(fake, scope, opts, i > 0); } return T.BOOL; } case 'Index': return this.index(e, scope); case 'Field': { const t = this.expr(e.target, scope); if (isAny(t)) return T.ANY; if (t.k !== 'RECORD') { this.error('type', e, `A dot reaches a field of a record, and ${sourceOf(e.target)} is ${article(t)}.`, { guide: 'record-for-grouping-related-fields' }); return T.ANY; } const f = t.fields.get(up(e.field)); if (!f) { const s = suggest(e.field, t.fieldNames); this.error('unknown-field', e, `${t.name} has no field called ${e.field}.${s.length ? ` Did you mean ${s.join(' or ')}?` : ` Its fields are ${t.fieldNames.join(', ')}.`}`); return T.ANY; } return f; } 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.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)}.`); } if (e.maybeRange && !opts.quiet) this.note('closed-range', e, `[${sourceOf(e.items[0])}, ${sourceOf(e.items[1])}] is a LIST of two values. A range of positions is half-open and ends with a round bracket: [${sourceOf(e.items[0])}, ${sourceOf(e.items[1])}).`, { guide: 'text-and-positions' }); return T.list(el); } case 'SetLit': { let el = T.ANY; for (const it of e.items) { const t = this.expr(it, scope); if (isAny(el)) el = t; else if (!isAny(t) && !sameType(el, t) && !(isNumeric(el) && isNumeric(t))) this.error('type', it, `Every member of a set has one type, and ${sourceOf(it)} is ${article(t)}.`); } return T.set(el); } case 'MapLit': { let kt = T.ANY; let vt = T.ANY; for (const x of e.entries) { const a = this.expr(x.key, scope); const b = this.expr(x.value, scope); if (isAny(kt)) kt = a; else if (!isAny(a) && !sameType(kt, a)) this.error('type', x.key, `Every key of a HASHMAP has one type, and ${sourceOf(x.key)} is ${article(a)}.`); if (isAny(vt)) vt = b; else if (isNumeric(vt) && isNumeric(b)) vt = numericResult(vt, b); else if (!isAny(b) && !sameType(vt, b)) this.error('type', x.value, `Every value of a HASHMAP has one type, and ${sourceOf(x.value)} is ${article(b)}.`); } return T.map(kt, vt); } case 'Range': { const a = this.expr(e.lo, scope); const b = this.expr(e.hi, scope); for (const [x, n] of [[a, e.lo], [b, e.hi]]) if (!isAny(x) && x.k !== 'INTEGER') this.error('type', n, `The ends of a range of positions are whole numbers, and ${sourceOf(n)} is ${article(x)}.`); if (!opts.rangeOk) this.error('range-place', e, `A range such as [${sourceOf(e.lo)}, ${sourceOf(e.hi)}) can follow IN, as in I IN [0, N), and cannot stand on its own as a value.`); return T.range(); } case 'SetBuilder': case 'Quant': return this.binder(e, scope); default: return T.ANY; } } binder(e, scope) { const dt = e.domain ? this.expr(e.domain, scope, { rangeOk: true, quiet: false }) : T.ANY; let vt = T.ANY; if (!isAny(dt)) { vt = elementOf(dt); if (!vt) { this.error('type', e.domain, `${e.kind === 'SetBuilder' ? 'A set written by rule' : e.q} ranges over a range such as [0, N), or over a collection, and ${sourceOf(e.domain)} is ${article(dt)}.`); vt = T.ANY; } } const inner = new Scope(scope, scope.owner); inner.set(e.var, { name: e.var, type: vt, kind: 'bound', line: e.line, col: e.col, readOnly: true }); if (scope.get(e.var) && scope.get(e.var).kind !== 'bound') this.warn('bound-shadow', e, `${e.var} is already a name here, and inside the ${e.kind === 'SetBuilder' ? 'set' : e.q} it means something else. A fresh name, such as K, reads more clearly.`); const bt = this.expr(e.body, inner); if (e.kind === 'SetBuilder' || e.q === 'FORALL' || e.q === 'EXISTS') { if (!isAny(bt) && bt.k !== 'BOOL') this.error('type', e.body, `The test after the colon has to be TRUE or FALSE, and ${sourceOf(e.body)} is ${article(bt)}.`); return e.kind === 'SetBuilder' ? T.set(vt) : T.BOOL; } // SUM if (!isAny(bt) && !isNumeric(bt)) this.error('type', e.body, `SUM adds numbers, and ${sourceOf(e.body)} is ${article(bt)}.`); return isAny(bt) ? T.ANY : bt; } binary(e, scope, opts, leftDone = false) { const op = e.op; const lt = leftDone ? (e.left.type || T.ANY) : this.expr(e.left, scope); const rt = this.expr(e.right, scope, { rangeOk: op === 'IN' }); const any = isAny(lt) || isAny(rt); switch (op) { case 'AND': case 'OR': for (const [t, n] of [[lt, e.left], [rt, e.right]]) { if (!isAny(t) && t.k !== 'BOOL') this.error('type', n, `${op} joins two TRUE-or-FALSE values, and ${sourceOf(n)} is ${article(t)}.${isText(t) || isNumeric(t) ? ` Each side needs its own comparison: ${op === 'OR' ? 'Base == \'G\' OR Base == \'C\'' : 'X > 0 AND X < 10'}.` : ''}`, { guide: 'compound-conditions' }); } 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)}.`); } 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 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': { if (any) return T.BOOL; let el; if (rt.k === 'HASHMAP') el = rt.key; else if (rt.k === 'STRING') { if (lt.k === 'STRING') { this.error('type', e, `IN on a STRING asks whether one CHAR occurs in it. Finding a whole pattern inside a text is an algorithm, not an operator: see MATCH.`, { guide: 'putting-it-together' }); return T.BOOL; } el = T.CHAR; } else el = elementOf(rt); if (!el) { this.error('type', e.right, `IN asks about membership of a SET, HASHMAP, LIST, ARRAY, STRING, or range, and ${sourceOf(e.right)} is ${article(rt)}.`); return T.BOOL; } if (!isAny(el) && !(isNumeric(el) && isNumeric(lt)) && !sameType(el, lt)) { const extra = el.k === 'CHAR' && lt.k === 'STRING' && e.left.kind === 'Str' ? ` Single quotes make a CHAR: '${e.left.value}'.` : el.k === 'STRING' && lt.k === 'CHAR' && e.left.kind === 'Char' ? ` Double quotes make a STRING: "${e.left.value}".` : ''; this.error('type', e.left, `${sourceOf(e.right)} holds ${typeName(el)} ${rt.k === 'HASHMAP' ? 'keys' : 'values'}, and ${sourceOf(e.left)} is ${article(lt)}, so the answer is always FALSE.${extra}`, { guide: 'the-types' }); } return T.BOOL; } default: return T.ANY; } } /** * 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; if ((lt.k === 'CHAR' && rt.k === 'STRING') || (lt.k === 'STRING' && rt.k === 'CHAR')) { const [cs, ss] = lt.k === 'CHAR' ? [e.left, e.right] : [e.right, e.left]; const lit = ss.kind === 'Str' && Array.from(ss.value).length === 1 ? ` Write '${ss.value}' with single quotes to compare against the CHAR.` : ''; this.error('char-string', e, `${sourceOf(cs)} is a CHAR and ${sourceOf(ss)} is a STRING. They are different types even when they hold the same letter, so ${e.op === '==' ? 'this comparison is never TRUE' : e.op === '!=' ? 'this comparison is always TRUE' : 'one cannot be ordered against the other'}.${lit}`, { guide: 'the-types', fix: lit ? { line: ss.line, col: ss.col, endCol: ss.col + ss.value.length + 2, text: `'${ss.value}'` } : undefined, }); return; } if (!sameType(lt, rt)) { this.error('type', e, `${sourceOf(e.left)} is ${article(lt)} and ${sourceOf(e.right)} is ${article(rt)}, and values of different types cannot be compared.`); return; } if (!equality && !['CHAR', 'STRING', 'INTEGER', 'FLOAT'].includes(lt.k)) this.error('type', e, `${e.op} puts values in order, and ${typeName(lt)} values have no order.`); } index(e, scope) { const t = this.expr(e.target, scope); const its = e.indices.map((i) => this.expr(i, scope)); for (let k = 0; k < its.length; k++) { const it = its[k]; if (t.k === 'HASHMAP') continue; if (!isAny(it) && it.k !== 'INTEGER') { this.error('type', e.indices[k], `A position is a whole number, and ${sourceOf(e.indices[k])} is ${article(it)}.${it.k === 'FLOAT' ? ' INT or ROUND turns it into one; decide which.' : ''}`, { guide: 'text-and-positions' }); } } if (isAny(t)) return T.ANY; switch (t.k) { case 'STRING': if (its.length !== 1) this.error('type', e, 'A STRING has one position per character, so it takes one index.'); return T.CHAR; case 'LIST': if (its.length !== 1) this.error('type', e, `A LIST takes one index. For a list of lists, write ${sourceOf(e.target)}[I][J].`); return t.of; case 'ARRAY': if (its.length !== t.dims) { this.error('type', e, t.dims === 2 ? `${sourceOf(e.target)} is a two-dimensional ARRAY, so it takes a row and a column: ${sourceOf(e.target)}[Row, Column].` : `${sourceOf(e.target)} is a one-dimensional ARRAY, so it takes one index.`, { guide: 'array-when-you-know-how-many' }); } return t.of; case 'HASHMAP': { const kt = its[0]; if (its.length !== 1) this.error('type', e, 'A HASHMAP takes one key in its brackets.'); else if (!isAny(kt) && !sameType(t.key, kt) && !(isNumeric(t.key) && isNumeric(kt))) { const extra = t.key.k === 'CHAR' && kt.k === 'STRING' && e.indices[0].kind === 'Str' ? ` Single quotes make a CHAR: '${e.indices[0].value}'.` : t.key.k === 'STRING' && kt.k === 'CHAR' ? ' Double quotes make a STRING.' : ''; this.error('type', e.indices[0], `${sourceOf(e.target)} has ${typeName(t.key)} keys, and ${sourceOf(e.indices[0])} is ${article(kt)}.${extra}`); } return t.val; } case 'SET': this.error('type', e, `A SET has no positions, so ${sourceOf(e)} means nothing. Ask a SET whether something is in it, with IN.`, { guide: 'set-for-membership' }); return T.ANY; default: this.error('type', e, `Square brackets reach a position in a STRING, LIST, ARRAY, or HASHMAP, and ${sourceOf(e.target)} is ${article(t)}.`); return T.ANY; } } call(e, scope) { const name = up(e.name); if (this.ctx?.inEnsure && name === 'OLD') { if (e.args.length !== 1) { this.error('arg-count', e, 'OLD takes one name: OLD(X) is the value X held when the subroutine was called.'); return T.ANY; } const t = this.expr(e.args[0], scope); e.isOld = true; const a = e.args[0]; if (a.kind !== 'Name' || (a.sym && a.sym.kind !== 'param')) { const inner = a.kind === 'CallExpr' && a.args.length === 1 && a.args[0].kind === 'Name' ? `${a.name}(OLD(${a.args[0].name}))` : null; this.error('old-name', e, `OLD takes the name of a parameter: OLD(X) is the value X held when the subroutine was called.${inner ? ` To use that value inside a call, write ${inner}.` : ''}`, { guide: 'contracts' }); } return t; } if (e.convert) return this.conversion(e, scope); const sub = this.findSub(name); if (sub) { e.sub = sub; if (sub.kind === 'Procedure') { this.error('procedure-value', e, `${sub.name} is a PROCEDURE and hands nothing back, so it cannot stand where a value stands. CALL it on a line of its own.`, { guide: 'procedure' }); for (const a of e.args) this.expr(a, scope); return T.VOID; } this.args(sub, e.args, e, scope); return sub.returns; } const b = BUILTINS[name]; 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(), ...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' }); for (const a of e.args) this.expr(a, scope); return T.ANY; } if (b.kind === 'procedure') { this.error('procedure-value', e, `${name} changes a collection and hands nothing back, so it goes on a line of its own: ${name}(...).`); for (const a of e.args) this.expr(a, scope); return T.VOID; } e.builtin = name; 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; }; const num = (i) => { const t = ts[i]; if (!isAny(t) && !isNumeric(t)) this.error('type', e.args[i], `${name} works on numbers, and ${sourceOf(e.args[i])} is ${article(t)}.`); return t; }; const int = (i) => { const t = ts[i]; if (!isAny(t) && t.k !== 'INTEGER') this.error('type', e.args[i], `${name} needs a whole number here, and ${sourceOf(e.args[i])} is ${article(t)}.`); }; switch (name) { case 'LENGTH': { if (!argc(1)) return T.INTEGER; const t = ts[0]; if (isAny(t)) return T.INTEGER; if (t.k === 'ARRAY' && t.dims === 2) this.error('type', e, 'A two-dimensional ARRAY has two lengths: ROWS(A) and COLUMNS(A).'); else if (!['STRING', 'LIST', 'ARRAY', 'SET', 'HASHMAP'].includes(t.k)) this.error('type', e.args[0], `LENGTH measures a STRING or a collection, and ${sourceOf(e.args[0])} is ${article(t)}.${t.k === 'CHAR' ? ' A CHAR is always exactly one character.' : ''}`); return T.INTEGER; } case 'ROWS': case 'COLUMNS': if (argc(1) && !isAny(ts[0]) && !(ts[0].k === 'ARRAY' && ts[0].dims === 2)) this.error('type', e.args[0], `${name} measures a two-dimensional ARRAY. For anything else, use LENGTH.`); return T.INTEGER; case 'INT': case 'ROUND': if (argc(1)) { num(0); if (ts[0].k === 'INTEGER') this.note('already-whole', e, `${sourceOf(e.args[0])} is already an INTEGER, so ${name} changes nothing.`); } return T.INTEGER; case 'ABS': if (argc(1)) return isAny(num(0)) ? T.ANY : ts[0]; return T.ANY; case 'MIN': case 'MAX': { if (ts.length === 1) { const t = ts[0]; if (isAny(t)) return T.ANY; const el = ['LIST', 'ARRAY', 'SET'].includes(t.k) ? t.of : null; if (!el || (!isNumeric(el) && !isAny(el) && !isText(el))) { this.error('type', e, `${name} of one value needs a LIST, ARRAY, or SET of numbers; with separate values, give it two or more: ${name}(A, B).`); return T.ANY; } return el; } if (ts.length < 2) { this.error('arg-count', e, `${name} needs at least two values, or one LIST.`); return T.ANY; } let r = null; ts.forEach((t, i) => { num(i); r = r ? numericResult(r, t) : t; }); return r; } case 'SQRT': case 'EXP': case 'LOG': case 'LOG2': case 'RAND': case 'LOG10': case 'SIN': case 'COS': case 'TAN': if (argc(1)) num(0); return T.FLOAT; case 'ATAN2': if (argc(2)) { num(0); num(1); } return T.FLOAT; case 'PI': case 'RANDN': argc(0); return T.FLOAT; case 'FLOOR': case 'CEIL': if (argc(1)) { num(0); if (ts[0].k === 'INTEGER') this.note('already-whole', e, `${sourceOf(e.args[0])} is already an INTEGER, so ${name} changes nothing.`); } return T.INTEGER; case 'CHOOSE': if (argc(2)) { int(0); int(1); } return T.INTEGER; case 'SUM_OF': case 'MEAN_OF': case 'VARIANCE_OF': case 'STDEV_OF': case 'MEDIAN_OF': case 'NORM_OF': { if (!argc(1)) return name === 'SUM_OF' ? T.ANY : T.FLOAT; const t = ts[0]; const el = ['LIST', 'ARRAY'].includes(t.k) ? t.of : null; if (!isAny(t) && (!el || (!isNumeric(el) && !isAny(el)))) { this.error('type', e.args[0], `${name} works on a LIST or ARRAY of numbers, and ${sourceOf(e.args[0])} is ${article(t)}.${t.k === 'SET' ? ' Turn the SET into a LIST first with SORTED.' : ''}`); return name === 'SUM_OF' ? T.ANY : T.FLOAT; } if (name === 'SUM_OF') return el && !isAny(el) ? el : T.ANY; return T.FLOAT; } case 'DOT': { if (!argc(2)) return T.ANY; const els = ts.map((t, i) => { const el = ['LIST', 'ARRAY'].includes(t.k) ? t.of : null; if (!isAny(t) && (!el || (!isNumeric(el) && !isAny(el)))) this.error('type', e.args[i], `DOT multiplies two LISTs or ARRAYs of numbers position by position, and ${sourceOf(e.args[i])} is ${article(t)}.`); return el && !isAny(el) ? el : null; }); return els[0] && els[1] ? numericResult(els[0], els[1]) : T.ANY; } case 'FILL': if (!argc(2)) return T.list(T.ANY); int(0); return T.list(ts[1]); case 'RANDINT': if (argc(2)) { int(0); int(1); } return T.INTEGER; case 'SLICE': { if (!argc(3)) return T.ANY; int(1); int(2); const t = ts[0]; if (!isAny(t) && !['STRING', 'LIST'].includes(t.k)) { this.error('type', e.args[0], `SLICE takes a run of positions from a STRING or a LIST, and ${sourceOf(e.args[0])} is ${article(t)}.`); return T.ANY; } return t; } case 'UPPER': case 'LOWER': if (argc(1) && !isAny(ts[0]) && !isText(ts[0])) this.error('type', e.args[0], `${name} changes letters, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); return isText(ts[0]) ? ts[0] : T.STRING; case 'SPLIT': if (argc(2)) { if (!isAny(ts[0]) && ts[0].k !== 'STRING') this.error('type', e.args[0], `SPLIT cuts a STRING into pieces, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); if (!isAny(ts[1]) && !isText(ts[1])) this.error('type', e.args[1], `The separator of SPLIT is a STRING or a CHAR, and ${sourceOf(e.args[1])} is ${article(ts[1])}.`); if (e.args[1].kind === 'Str' && e.args[1].value === '') this.error('value', e.args[1], 'SPLIT needs a separator with at least one character. To take a text apart character by character, use FOR EACH.'); } return T.list(T.STRING); case 'JOIN': if (argc(2)) { if (!isAny(ts[0]) && !(ts[0].k === 'LIST' && (isAny(ts[0].of) || ts[0].of.k === 'STRING' || ts[0].of.k === 'CHAR'))) this.error('type', e.args[0], `JOIN glues a LIST OF STRING together, and ${sourceOf(e.args[0])} is ${article(ts[0])}.${ts[0].k === 'LIST' ? ' Turn each value into text first with TO_STRING.' : ''}`); if (!isAny(ts[1]) && !isText(ts[1])) this.error('type', e.args[1], `The separator of JOIN is a STRING or a CHAR, and ${sourceOf(e.args[1])} is ${article(ts[1])}.`); } return T.STRING; case 'INDEX_OF': if (argc(2)) { const t = ts[0]; if (isAny(t)) return T.INTEGER; if (t.k === 'STRING') { if (!isAny(ts[1]) && !isText(ts[1])) this.error('type', e.args[1], `INDEX_OF looks for a STRING or a CHAR inside a STRING, and ${sourceOf(e.args[1])} is ${article(ts[1])}.`); } else if (t.k === 'LIST') { if (!isAny(ts[1]) && !isAny(t.of) && !sameType(ts[1], t.of)) this.error('type', e.args[1], `${sourceOf(e.args[0])} holds ${article(t.of)} at each position, and INDEX_OF is looking for ${article(ts[1])}.`); } else this.error('type', e.args[0], `INDEX_OF searches a STRING or a LIST, and ${sourceOf(e.args[0])} is ${article(t)}.${t.k === 'HASHMAP' || t.k === 'SET' ? ' Ask IN instead: a HASHMAP or SET has no positions.' : ''}`); } return T.INTEGER; case 'REPLACE': if (argc(3)) { if (!isAny(ts[0]) && ts[0].k !== 'STRING') this.error('type', e.args[0], `REPLACE works on a STRING, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); for (const i of [1, 2]) if (!isAny(ts[i]) && !isText(ts[i])) this.error('type', e.args[i], `REPLACE swaps one piece of text for another, and ${sourceOf(e.args[i])} is ${article(ts[i])}.`); if (e.args[1].kind === 'Str' && e.args[1].value === '') this.error('value', e.args[1], 'REPLACE needs something to look for: the piece to replace cannot be empty.'); } return T.STRING; case 'ORD': if (argc(1) && !isAny(ts[0]) && ts[0].k !== 'CHAR') this.error('type', e.args[0], `ORD numbers one CHAR, and ${sourceOf(e.args[0])} is ${article(ts[0])}.${ts[0].k === 'STRING' && e.args[0].kind === 'Str' ? ` Single quotes make a CHAR: '${e.args[0].value}'.` : ''}`); return T.INTEGER; case 'CHR': if (argc(1)) int(0); return T.CHAR; case 'TO_STRING': argc(1); return T.STRING; case 'TO_INTEGER': if (argc(1) && !isAny(ts[0]) && !isText(ts[0])) this.error('type', e.args[0], ts[0].k === 'FLOAT' ? 'TO_INTEGER reads text. To turn a FLOAT into a whole number, use INT or ROUND.' : `TO_INTEGER reads a STRING of digits, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); return T.INTEGER; case 'TO_FLOAT': if (argc(1) && !isAny(ts[0]) && !isText(ts[0]) && !isNumeric(ts[0])) this.error('type', e.args[0], `TO_FLOAT reads a STRING or converts a number, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); return T.FLOAT; case 'KEYS': if (argc(1) && !isAny(ts[0]) && ts[0].k !== 'HASHMAP') { this.error('type', e.args[0], `KEYS lists the keys of a HASHMAP, and ${sourceOf(e.args[0])} is ${article(ts[0])}.`); return T.list(T.ANY); } return T.list(isAny(ts[0]) ? T.ANY : ts[0].key); 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; } } } /** * @param {any} parsed * @param {{ libs?: Map, libOrigin?: Map }} [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; program.comments = parsed.comments; const diags = [...parsed.diags, ...c.diags].sort((a, b) => a.line - b.line || a.col - b.col); return { program, diags }; } export { elementOf, MUTATORS };