/** * pseudo/coach.js * * The mistakes the guide warns about, found in a student's own program. * Everything here runs after parsing, checking, and analysis, and adds * warnings and notes rather than errors: a program the coach dislikes still * runs, because running it is often the fastest way to see the problem. * * coach(program, analysis) -> [diag] * * Every rule has an id, a severity, and a guide anchor, so the lab can * link each finding to the paragraph that explains it. */ import { diag, sourceOf } from './parse.js'; import { walkStatements, walkExpr, rootName, statementExprs, childBlocks } from './analyze.js'; import { namesIn } from './interp.js'; import { isNumeric } from './lang.js'; const up = (s) => String(s).toUpperCase(); const LOOPS = ['For', 'ForEach', 'While', 'Repeat']; /** The expression a simple name was last set to, if it was set exactly once. */ function definitionsOf(body) { const count = new Map(); const value = new Map(); walkStatements(body, (s) => { if (s.kind === 'Assign' && s.target.kind === 'Name') { const k = up(s.target.name); count.set(k, (count.get(k) || 0) + 1); value.set(k, s.value); } }); const out = new Map(); for (const [k, n] of count) if (n === 1) out.set(k, value.get(k)); return out; } /** Is `e` LENGTH(X), or a name set once to LENGTH(X)? Returns X's source. */ function lengthOf(e, defs) { if (!e) return null; if (e.kind === 'CallExpr' && e.builtin === 'LENGTH' && e.args[0]) return sourceOf(e.args[0]); if (e.kind === 'Name' && defs.has(up(e.name))) return lengthOf(defs.get(up(e.name)), new Map()); return null; } /** Every X[...] read inside a list of statements, as { target, index, line }. */ function indexReads(body) { const out = []; const visit = (e) => walkExpr(e, (x) => { if (x.kind === 'Index' && x.target.kind === 'Name') out.push({ target: sourceOf(x.target), index: x.indices[0], node: x }); }); walkStatements(body, (s) => { for (const e of statementExprs(s)) visit(e); }); return out; } /** For T[I + 2] with counter I, 2; for T[I], 0; for anything else, null. */ function offsetOf(e, counter) { if (e.kind === 'Name' && up(e.name) === up(counter)) return 0; if (e.kind === 'Binary' && e.op === '+' && e.left.kind === 'Name' && up(e.left.name) === up(counter) && e.right.kind === 'Num') return e.right.value; if (e.kind === 'Binary' && e.op === '-' && e.left.kind === 'Name' && up(e.left.name) === up(counter) && e.right.kind === 'Num') return -e.right.value; return null; } const mentions = (e, name) => [...namesIn(e || {})].some((n) => up(n) === up(name)); export function coach(program, analysis, opts = {}) { const out = []; const say = (severity, code, node, message, extra = {}) => out.push(diag(severity, code, node?.line ?? 1, message, { col: node?.col ?? 1, source: 'coach', ...extra })); for (const unit of analysis.units) { const body = unit.body; const defs = definitionsOf(body); const where = unit.kind === 'main' ? 'the main program' : unit.name; /* ---------- values read before they are set ---------- */ const reported = new Set(); const loopsByLine = unit.loops; for (const u of unit.uses) { if (u.kind === 'spec' || u.implicit) continue; const key = `${u.var}@${u.line}`; if (reported.has(key)) continue; const unset = u.defs.filter((d) => d.kind === 'unset'); if (!unset.length) continue; // Passed BYREF to a procedure that writes the parameter before reading it: an out-parameter, not a read. if (u.byref) { const callee = analysis.units.find((x) => up(x.name) === up(u.callee)); const readsFirst = !callee || callee.uses.some((cu) => cu.var === u.byref && cu.kind !== 'spec' && cu.defs.some((d) => d.kind === 'param')); if (!readsFirst) continue; } const real = u.defs.filter((d) => d.kind !== 'unset'); reported.add(key); const afterLoop = unset.find((d) => d.stmt?.kind === 'For'); if (afterLoop && !real.length) { say('warning', 'counter-after-loop', { line: u.line, col: u.expr?.col }, `${u.name} is read on line ${u.line}, after the FOR loop on line ${afterLoop.stmt.line} that used it as a counter. The notation does not say what a counter holds after its loop, and the lab gives it no value. Keep the position you need in a variable of your own.`, { guide: 'for-when-you-know-how-many-times' }); continue; } // A value updated inside a loop from its own old value, with nothing before the loop. const enclosing = loopsByLine.filter((L) => u.line >= L.line && u.line <= (L.endLine ?? L.line)); const carried = real.length && real.every((d) => enclosing.some((L) => d.line >= L.line && d.line <= (L.endLine ?? L.line))); if (!real.length || carried) { const acc = unit.accumulators.find((a) => a.var === u.var && a.how !== 'flag'); const msg = acc ? `${u.name} is updated from its own old value on line ${acc.line}, and nothing before the loop gives it a starting value, so the first pass has nothing to add to. Set up is missing: give ${u.name} its starting value before the loop.` : carried ? `${u.name} is read on line ${u.line}, and on the first pass of the loop nothing has given it a value yet.` : `${u.name} is read on line ${u.line}, and no line before it gives ${u.name} a value.`; say('warning', 'unset-read', { line: u.line, col: u.expr?.col }, msg, { guide: 'declaring' }); } else { say('warning', 'maybe-unset', { line: u.line, col: u.expr?.col }, `${u.name} may reach line ${u.line} without a value: some path through ${where} gets here without assigning it. Give it a value on every path, or before the branch.`, { guide: 'declaring' }); } } /* ---------- names nobody reads ---------- */ const read = new Set(unit.uses.map((u) => u.var)); for (const sym of unit.symbols || []) { const k = up(sym.name); if (sym.kind === 'var' && !read.has(k)) { const assigned = unit.defs.some((d) => d.var === k && d.kind !== 'unset' && d.kind !== 'init'); say('note', assigned ? 'never-read' : 'unused', sym, assigned ? `${sym.name} is given a value and never read. Either something still needs it, or the line that sets it can go.` : `${sym.name} is declared and never used.`, { guide: 'declaring' }); } if (sym.kind === 'param' && !read.has(k) && sym.mode !== 'BYREF') say('note', 'unused-param', sym, `Parameter ${sym.name} is never used inside ${unit.name}.`); } /* ---------- loops ---------- */ for (const L of unit.loops) { const s = L.node; if (s.kind === 'For') { const reads = indexReads(s.body); // The bound against the furthest position the body reads: a loop over // [0, LENGTH(T) - d) may read T[I + d - 1] and no further. if (s.start?.kind === 'Num' && s.start.value === 0 && (!s.step || (s.step.kind === 'Num' && s.step.value === 1))) { let seq = lengthOf(s.stop, defs); let d = 0; if (!seq && s.stop?.kind === 'Binary' && s.stop.op === '-' && s.stop.right.kind === 'Num') { seq = lengthOf(s.stop.left, defs); d = s.stop.right.value; } if (seq) { const offsets = reads.filter((r) => r.target === seq).map((r) => offsetOf(r.index, s.var)).filter((o) => o !== null); if (offsets.length) { const far = Math.max(...offsets); if (d > far && d === 1 && far === 0) { say('warning', 'stops-early', s.stop, `FOR ${s.var} <- 0 TO ${sourceOf(s.stop)} stops one short of its bound, so ${s.var} never reaches ${sourceOf(s.stop)}, the last position of ${seq}. The loop skips the last position. A loop over every position uses the length itself: TO ${sourceOf(s.stop.left)}.`, { guide: 'for-when-you-know-how-many-times', fix: { line: s.stop.line, col: s.stop.col, text: sourceOf(s.stop.left), replaceExpr: true }, }); } else if (d > far) { say('warning', 'stops-early', s.stop, `The body reads ${seq} no further than ${s.var}${far ? ` + ${far}` : ''}, so the loop could run to ${far ? `LENGTH(${seq}) - ${far}` : `LENGTH(${seq})`}; stopping at ${sourceOf(s.stop)} skips the last ${d - far === 1 ? 'position' : `${d - far} positions`}.`, { guide: 'text-and-positions' }); } else if (far > d) { say('warning', 'overrun', s.stop, `The body reads ${seq}[${s.var} + ${far}], and on the last pass ${s.var} is ${d ? `LENGTH(${seq}) - ${d + 1}` : `LENGTH(${seq}) - 1`}, so it asks for position ${far > d + 1 ? `LENGTH(${seq}) + ${far - d - 1}` : `LENGTH(${seq})`}, which does not exist. A read that reaches ${far} ahead needs the bound LENGTH(${seq}) - ${far}.`, { guide: 'text-and-positions' }); } } } } // FOR I <- 1 TO LENGTH(T) + 1, or starting at 1 if (s.start?.kind === 'Num' && s.start.value === 1) { const seq = lengthOf(s.stop?.kind === 'Binary' && s.stop.op === '+' ? s.stop.left : s.stop, defs); const byCounter = (r) => r.index.kind === 'Name' && up(r.index.name) === up(s.var); // Starting at 1 is deliberate when position 0 is handled another // way: read before the loop (Max <- Q[0]), or remembered in a // variable the body compares against (Q[Best], T[I - 1]). const esc = String(seq || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const zeroBefore = String(program.source || "").split("\n").slice(0, s.line - 1).some((l) => new RegExp(`\\b${esc}\\[\\s*0\\s*\\]`, 'i').test(l.replace(/\/\/.*$/, ''))); const otherRead = reads.some((r) => r.target === seq && !byCounter(r)); if (seq && !zeroBefore && !otherRead && reads.some((r) => r.target === seq && byCounter(r))) { say('warning', 'starts-at-one', s.start, `${s.var} starts at 1, so ${seq}[0], the first position, is never visited. Positions count from zero.`, { guide: 'text-and-positions' }); } } // STEP k with T[I + k - 1] and a bound that is the length if (s.step?.kind === 'Num' && s.step.value > 1) { const seq = lengthOf(s.stop, defs); const reach = reads.filter((r) => r.target === seq && r.index.kind === 'Binary' && r.index.op === '+' && r.index.left.kind === 'Name' && up(r.index.left.name) === up(s.var) && r.index.right.kind === 'Num'); if (seq && reach.length) { const far = Math.max(...reach.map((r) => r.index.right.value)); say('warning', 'step-overrun', s.step, `With STEP ${s.step.value} and a stop of ${sourceOf(s.stop)}, the last pass can start within ${far} ${far === 1 ? 'position' : 'positions'} of the end, and then ${seq}[${s.var} + ${far}] does not exist unless the length is a multiple of ${s.step.value}. ${sourceOf(s.stop)} DIV ${s.step.value} * ${s.step.value} is a bound that always fits.`, { guide: 'step-for-other-increments' }); } } // APPEND to a list whose length is the bound walkStatements(s.body, (x) => { if (x.kind === 'BuiltinCall' && x.name === 'APPEND' && lengthOf(s.stop, new Map()) === sourceOf(x.args[0])) { say('note', 'growing-bound', s.stop, `The bound ${sourceOf(s.stop)} is worked out once, when the loop starts, and ${sourceOf(x.args[0])} grows inside it. The loop runs as many times as the list was long at the start.`, { guide: 'list-when-you-do-not-know-how-many' }); } }); } if (s.kind === 'While' || s.kind === 'Repeat') { const tests = L.tests.filter((t) => ![...(program.constants?.keys?.() || [])].includes(t)); const exits = L.breaks + L.returns; if (s.cond && !exits && tests.length && !tests.some((t) => L.changes.has(t))) { say('warning', 'no-progress', s, `The ${s.kind === 'While' ? 'WHILE' : 'REPEAT'} condition ${sourceOf(s.cond)} reads ${tests.map((t) => nameCase(s.cond, t)).join(' and ')}, and nothing in the body changes ${tests.length === 1 ? 'it' : 'any of them'}. ${s.kind === 'While' ? 'Once the loop starts, it never ends.' : 'If the condition starts FALSE, it stays FALSE.'} Name the quantity that moves, and move it.`, { guide: 'while-when-the-condition-is-checked-first' }); } if (s.cond && s.cond.kind === 'Bool' && s.cond.value === (s.kind === 'While') && !exits) { say('warning', 'no-progress', s, `${s.kind === 'While' ? 'WHILE TRUE' : 'UNTIL FALSE'} with no BREAK or RETURN inside never ends.`); } let drains = false; walkStatements(s.body, (x) => { if (x.kind === 'BuiltinCall' && x.name === 'REMOVE') drains = true; }); walkStatements(s.body, (x) => { if (x.kind === 'BuiltinCall' && x.name === 'APPEND' && !drains) { walkExpr(s.cond || {}, (e) => { if (e.kind === 'CallExpr' && e.builtin === 'LENGTH' && sourceOf(e.args[0]) === sourceOf(x.args[0])) { say('warning', 'growing-bound', e, `The condition measures ${sourceOf(e.args[0])}, and the body keeps adding to it, so the target moves every pass. Take the length once, into a name, before the loop.`, { guide: 'list-when-you-do-not-know-how-many' }); } }); } }); } if (s.kind === 'ForEach') { walkStatements(s.body, (x) => { const r = x.kind === 'BuiltinCall' ? rootName(x.args[0]) : x.kind === 'Assign' ? rootName(x.target) : null; if (r && s.iterable && sourceOf(s.iterable) === r) say('warning', 'change-while-visiting', x, `${r} changes inside the FOR EACH that is visiting it. The loop visits the values ${r} held when it started; build a second collection instead.`); }); } if (L.breaks >= 3) say('note', 'many-exits', s, `This loop has ${L.breaks} BREAK lines, so it has ${L.breaks} exits and no single place that says when it ends. One exit, placed where its reason is obvious, is easier to follow.`, { guide: 'leaving-a-loop-early' }); if (L.depth >= 3) say('note', 'deep-nesting', s, `This loop sits ${L.depth + 1} levels deep. Past three levels a reader loses track of which block is which; pulling the inner work out into a FUNCTION of its own is the usual way back.`, { guide: 'nesting' }); } /* ---------- accumulators reset in the wrong loop ---------- */ wrongReset(unit, say); /* ---------- statements ---------- */ walkStatements(body, (s, parents) => { // indentation shows structure const parent = parents[parents.length - 1]; if (parent && program.lines && !['Function', 'Procedure'].includes(parent.kind)) { const pl = program.lines[parent.line - 1]; const sl = program.lines[s.line - 1]; if (pl && sl && sl.indent <= pl.indent && s.line !== parent.line) say('note', 'indent', s, `Line ${s.line} is inside the ${openerWord(parent)} on line ${parent.line}, and is not indented past it. Indent a block's body by four spaces so its structure shows.`, { guide: 'how-to-read-this-guide' }); } else if (parent && program.lines) { const pl = program.lines[parent.line - 1]; const sl = program.lines[s.line - 1]; if (pl && sl && sl.indent <= pl.indent) say('note', 'indent', s, `Line ${s.line} is in the body of ${parent.name}, and is not indented past its first line.`, { guide: 'how-to-read-this-guide' }); } // unreachable lines for (const b of childBlocks(s).concat(parents.length ? [] : [])) unreachable(b, say); if (s.kind === 'Assign' && s.target.kind === 'Name' && s.value.kind === 'Name' && up(s.value.name) === up(s.target.name)) say('warning', 'self-assign', s, `${sourceOf(s.target)} <- ${sourceOf(s.value)} changes nothing.`); if (s.kind === 'Assign' && s.target.type?.k === 'FLOAT' && s.value.kind === 'Binary' && s.value.op === 'DIV') say('warning', 'div-into-float', s.value, `${sourceOf(s.target)} is a FLOAT, and DIV throws away the remainder before the value arrives. For a fraction, divide with /.`, { guide: 'arithmetic' }); if (s.kind === 'Case') caseChecks(s, say); if ((s.kind === 'If' || s.kind === 'Case') && s.kind === 'If' && s.branches.some((b) => !b.body.length) && !s.elseBody) say('note', 'empty-body', s, 'This IF has an empty body, so it does nothing either way.'); if (s.kind === 'Output' && unit.kind === 'Function') say('note', 'function-output', s, `${unit.name} is a FUNCTION and also shows output. A function that prints is harder to reason about, since its value stops being the whole story of what calling it did. Return the value and let the caller show it.`, { guide: 'procedure' }); for (const e of statementExprs(s)) exprChecks(e, say); // H[K] read with no guard hashGuards(s, parents, say); }); if (unit.kind !== 'main') unreachable(body, say); else unreachable(body, say); if (unit.kind === 'Function' && unit.node && !/^[A-Z0-9_]+$/.test(unit.name)) { say('note', 'function-name', unit.node, `Function and procedure names in this course are uppercase with underscores, such as ${up(unit.name.replace(/([a-z])([A-Z])/g, '$1_$2'))}, which tells a call apart from a variable at a glance.`, { guide: 'function' }); } } // one report per line and rule const seen = new Set(); return out.filter((d) => { const k = `${d.code}@${d.line}@${d.message}`; if (seen.has(k)) return false; seen.add(k); return true; }); } function nameCase(expr, upperName) { let found = upperName; walkExpr(expr, (x) => { if (x.kind === 'Name' && up(x.name) === upperName) found = x.name; }); return found; } function openerWord(s) { return { If: 'IF', Case: 'CASE', For: 'FOR', ForEach: 'FOR EACH', While: 'WHILE', Repeat: 'REPEAT' }[s.kind] || s.kind; } function unreachable(body, say) { for (let i = 0; i < body.length - 1; i++) { const s = body[i]; if (['Return', 'Break', 'Continue'].includes(s.kind)) { say('warning', 'unreachable', body[i + 1], `Line ${body[i + 1].line} can never run: the ${s.kind.toUpperCase()} on line ${s.line} always leaves before reaching it.`, { guide: s.kind === 'Return' ? 'function' : 'leaving-a-loop-early' }); return; } } } /** * Two ways to put an accumulator's reset in the wrong loop: * outer: reset before the outer loop, changed inside an inner loop, read * once per outer pass (the Matched mistake); every later pass * starts from whatever the previous one left. * inner: reset inside the loop, updated from itself inside the same loop, * and read only after the loop; every pass wipes the last. */ function wrongReset(unit, say) { for (const L of unit.loops) { if (L.depth !== 0) continue; const outer = L.node; const inner = unit.loops.filter((m) => m.parent === outer); // outer for (const I of inner) { for (const name of I.changes) { if (up(name) === up(I.node.var || '')) continue; const setBefore = findAssignBefore(unit.body, outer, name); if (!setBefore || !isConstant(setBefore.value)) continue; const resetInside = outer.body.some((s, idx) => idx < outer.body.indexOf(I.node) && s.kind === 'Assign' && s.target.kind === 'Name' && up(s.target.name) === name); if (resetInside) continue; const readAfter = outer.body.slice(outer.body.indexOf(I.node) + 1).some((s) => mentions({ kind: 'Chain', operands: statementExprs(s), ops: [] }, name) || blockMentions(s, name)); if (!readAfter) continue; say('warning', 'reset-outside', setBefore, `${setBefore.target.name} is set to ${sourceOf(setBefore.value)} once, before the ${openerWord(outer)} loop on line ${outer.line}, and changed inside the ${openerWord(I.node)} loop on line ${I.node.line}. Every pass of the outer loop after the first starts with whatever the last pass left in it. If ${setBefore.target.name} belongs to one pass, reset it at the top of the outer loop's body.`, { guide: 'nested-loops' }); } } // inner const resets = outer.body.filter((s) => s.kind === 'Assign' && s.target.kind === 'Name' && isConstant(s.value)); for (const r of resets) { const name = up(r.target.name); const acc = unit.accumulators.find((a) => a.var === name && a.loop === outer && a.how !== 'flag'); if (!acc || acc.line < r.line) continue; const usedInside = outer.body.some((s) => s !== acc.stmt && s !== r && s.line > acc.line && (mentions({ kind: 'Chain', operands: statementExprs(s), ops: [] }, name) || blockMentions(s, name))); if (usedInside) continue; const after = unit.body.slice(unit.body.indexOf(outer) + 1); if (!after.some((s) => mentions({ kind: 'Chain', operands: statementExprs(s), ops: [] }, name))) continue; say('warning', 'reset-inside', r, `${r.target.name} is reset to ${sourceOf(r.value)} at the start of every pass of the loop on line ${outer.line}, and read only after the loop ends, so it ends up holding just the last pass's contribution. If ${r.target.name} collects over the whole loop, set it up before the loop.`, { guide: 'nested-loops' }); } } } function blockMentions(s, name) { let hit = false; walkStatements([s], (x) => { for (const e of statementExprs(x)) if (mentions(e, name)) hit = true; }); return hit; } function findAssignBefore(body, loop, name) { const i = body.indexOf(loop); for (let k = i - 1; k >= 0; k--) { const s = body[k]; if (s.kind === 'Assign' && s.target.kind === 'Name' && up(s.target.name) === name) return s; } return null; } const isConstant = (e) => e && ['Num', 'Bool', 'Str', 'Char'].includes(e.kind); function caseChecks(s, say) { if (!s.otherwise) say('note', 'case-no-otherwise', s, `This CASE has no OTHERWISE, so a value that matches no branch does nothing, silently. That is occasionally what you want, and more often the bug you spend an afternoon on.`, { guide: 'case' }); const ranges = []; for (const a of s.arms) for (const l of a.labels) if (l.low && l.low.kind === 'Num' && l.high.kind === 'Num') ranges.push({ lo: l.low.value, hi: l.high.value, node: l.low, arm: a }); ranges.sort((a, b) => a.lo - b.lo); for (let i = 0; i < ranges.length; i++) { const r = ranges[i]; if (r.hi <= r.lo) say('warning', 'case-empty-range', r.node, `${r.lo} TO ${r.hi} covers [${r.lo}, ${r.hi}), which holds nothing: the second value has to be larger.`, { guide: 'case' }); const nx = ranges[i + 1]; if (!nx) continue; if (nx.lo === r.hi + 1) { say('warning', 'case-gap', r.node, `${r.lo} TO ${r.hi} covers [${r.lo}, ${r.hi}): ranges in a CASE stop one short of their second value, exactly like FOR. ${r.hi} itself${s.subject?.type?.k === 'FLOAT' ? `, and everything between ${r.hi} and ${nx.lo},` : ''} matches neither this branch nor the next one, which starts at ${nx.lo}. Write ${r.lo} TO ${nx.lo} so the two ranges meet.`, { guide: 'case', fix: { line: r.node.line, text: `${r.lo} TO ${nx.lo}` } }); } else if (nx.lo < r.hi) { say('warning', 'case-overlap', nx.node, `${nx.lo} TO ${nx.hi} overlaps ${r.lo} TO ${r.hi}. CASE runs only the first branch that matches, so the overlap goes to whichever comes first.`, { guide: 'case' }); } else if (nx.lo > r.hi) { say('note', 'case-hole', nx.node, `Nothing covers [${r.hi}, ${nx.lo}), the values between these two ranges.`, { guide: 'case' }); } } } function exprChecks(e, say) { walkExpr(e, (x) => { if (x.kind === 'Binary' && (x.op === '==' || x.op === '!=')) { const [a, b] = [x.left, x.right]; if (a.kind === 'Bool' || b.kind === 'Bool') { const other = a.kind === 'Bool' ? b : a; const lit = a.kind === 'Bool' ? a : b; const positive = (lit.value === true) === (x.op === '=='); say('note', 'bool-compare', x, `${sourceOf(other)} already holds TRUE or FALSE, so comparing it with ${lit.value ? 'TRUE' : 'FALSE'} asks the same question twice. Write ${positive ? sourceOf(other) : `NOT ${sourceOf(other)}`}.`, { guide: 'if' }); } if ((a.type?.k === 'FLOAT' || b.type?.k === 'FLOAT') && isNumeric(a.type) && isNumeric(b.type)) { say('warning', 'float-equal', x, `${sourceOf(x)} compares FLOAT values with ${x.op}. Two measurements that should be equal often differ in the last digit, so compare the difference against a tolerance: ABS(${sourceOf(a)} - ${sourceOf(b)}) < 0.0001, or IS_CLOSE(${sourceOf(a)}, ${sourceOf(b)}, 1e-9, 0.0) to say the tolerance as a fraction of the values.`, { guide: 'comparison' }); } } if (x.kind === 'Unary' && x.op === 'NOT' && !x.arg.paren && (x.arg.kind === 'Binary' && ['==', '!=', '<', '<=', '>', '>='].includes(x.arg.op))) { const opp = { '==': '!=', '!=': '==', '<': '>=', '<=': '>', '>': '<=', '>=': '<' }[x.arg.op]; say('note', 'not-compare', x, `NOT applies to the whole comparison here, and the comparison has a shorter opposite: ${sourceOf(x.arg.left)} ${opp} ${sourceOf(x.arg.right)}.`, { guide: 'compound-conditions' }); } if (x.kind === 'Unary' && x.op === 'NOT' && x.arg.paren && x.arg.kind === 'Binary' && ['<', '<=', '>', '>='].includes(x.arg.op)) { const opp = { '<': '>=', '<=': '>', '>': '<=', '>=': '<' }[x.arg.op]; say('note', 'not-compare', x, `${sourceOf(x)} has a shorter equivalent without the negation: ${sourceOf(x.arg.left)} ${opp} ${sourceOf(x.arg.right)}.`, { guide: 'compound-conditions' }); } if (x.kind === 'Binary' && x.op === 'AND') guardOrder(x, say); }); } /** In A AND B, the side that keeps a position legal has to come first. */ function guardOrder(x, say) { const reads = []; walkExpr(x.left, (e) => { if (e.kind === 'Index' && e.target.kind === 'Name') reads.push(e); }); if (!reads.length) return; let guard = null; walkExpr(x.right, (e) => { if ((e.kind === 'Binary' || e.kind === 'Chain') && ['<', '<=', '>', '>='].includes(e.op || e.ops?.[0])) { for (const r of reads) { const idx = sourceOf(r.indices[0]); const txt = sourceOf(e); if (txt.includes(idx) && (txt.includes(`LENGTH(${sourceOf(r.target)})`) || /\b[NM]\b/.test(txt))) guard = { e, r }; } } }); if (guard) { say('warning', 'guard-order', x, `${sourceOf(guard.r)} is read on the left of AND, and the test that keeps ${sourceOf(guard.r.indices[0])} legal, ${sourceOf(guard.e)}, is on the right. The left side runs first, so on the last test the read happens before the guard can stop it. Swap the two sides.`, { guide: 'compound-conditions' }); } } function hashGuards(s, parents, say) { for (const e of statementExprs(s)) { walkExpr(e, (x) => { if (x.kind !== 'Index' || x.target.type?.k !== 'HASHMAP') return; const key = sourceOf(x.indices[0]); const map = sourceOf(x.target); const guarded = parents.some((p) => p.kind === 'If' && p.branches.some((b, i) => i === 0 && b.body.some((y) => containsLine(y, s.line)) && mentionsIn(b.cond, key, map))) || parents.some((p) => (p.kind === 'ForEach') && sourceOf(p.iterable) === map && p.var.toUpperCase() === key.toUpperCase()); const inElse = parents.find((p) => p.kind === 'If' && p.elseBody && p.elseBody.some((y) => containsLine(y, s.line)) && p.branches.some((b) => mentionsIn(b.cond, key, map))); if (inElse) { say('warning', 'missing-key', x, `This line runs when ${key} IN ${map} is FALSE, and it reads ${map}[${key}], which is exactly the key that is missing.`, { guide: 'hashmap-for-lookup-by-key' }); return; } if (!guarded && s.kind === 'Assign' && sourceOf(s.target) === sourceOf(x)) { say('warning', 'missing-key', x, `${sourceOf(x)} is read to compute its own new value, and nothing checks that ${key} is already a key of ${map}. The first sighting of each key has no old value: test ${key} IN ${map} first.`, { guide: 'hashmap-for-lookup-by-key' }); } }); } } function mentionsIn(cond, key, map) { let hit = false; walkExpr(cond, (x) => { if (x.kind === 'Binary' && x.op === 'IN' && sourceOf(x.left) === key && sourceOf(x.right) === map) hit = true; }); return hit; } function containsLine(s, line) { if (s.line === line) return true; let hit = false; walkStatements([s], (x) => { if (x.line === line) hit = true; }); return hit; }