@skillstech/thunderlang 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "1.0.3",
4
- "description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
3
+ "version": "1.0.4",
4
+ "description": "ThunderLang, the programming language: its deterministic compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "types": "./src/index.d.ts",
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.0.3';
33
+ export const COMPILER_VERSION = '1.0.4';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
package/src/libraries.mjs CHANGED
@@ -108,7 +108,7 @@ const CATALOG = [
108
108
  { re: /^([A-Z]\w*)\s*(?:\.|::)\s*where\s*\(\s*["']([\w.]+)["']\s*,\s*(?:["'](?:=|==)["']\s*,\s*)?([^)]+?)\s*\)\s*(?:->|\.)\s*(first|get|firstOrFail|count|exists)\s*\(\s*\)$/, say: (m) => ({ says: `${{ first: 'Finds the first', firstOrFail: 'Finds the first', get: 'Finds the', count: 'Counts the', exists: 'Checks whether there are' }[m[4]]} ${m[4] === 'first' || m[4] === 'firstOrFail' ? words(m[1]) : plural(words(m[1]))} whose ${words(m[2])} is ${valueWords(m[3])}${m[4] === 'firstOrFail' ? ' (stops if there is none)' : ''}`, does: 'find' }) },
109
109
  { re: /^([A-Z]\w*)\s*\.\s*(findAll|where|all|filter)\s*\(/, say: (m, c) => ({ says: `Finds the ${plural(words(m[1]))} ${whereOf(inside(c, c.indexOf('(')) ?? '') || whoseFrom(inside(c, c.indexOf('(')) ?? '')}`.trim(), does: 'find' }) },
110
110
  // A model class (not a language built-in: Object.create makes an object, it saves nothing).
111
- { re: /^(?!(?:Object|Array|Promise|Symbol|Reflect|Proxy|JSON|Math|Date|Error|URL|String|Number|Map|Set|WeakMap|Stream|Path|Paths|File|Files|Thread|Task|Channel|Pattern|List|Collections|Optional|Executors|Duration|Instant|UUID|Uri|Logger|Http\w*|Request|Response|Headers|Blob|Intl|React|Vue|Ember|Ext|Class)\b)([A-Z]\w*)\s*(?:\.|::)\s*(create|insert|insertMany|bulkCreate|create!)\s*\(/, say: (m, c) => { const w = whoseFrom(inside(c, c.indexOf('(')) ?? '').replace(/^whose /, ''); return { says: `Saves a new ${words(m[1])}${w ? ` with ${w.replace(/ is /g, ' ').replace(/ and /g, ', ')}` : ''}`, does: 'save' }; } },
111
+ { re: /^(?!(?:Object|Array|Promise|Symbol|Reflect|Proxy|JSON|Math|Date|Error|URL|String|Number|Map|Set|WeakMap|Stream|Path|Paths|File|Files|Thread|Task|Channel|Pattern|List|Collections|Optional|Executors|Duration|Instant|UUID|Uri|Logger|Http\w*|Request|Response|Headers|Blob|Intl|React|Vue|Ember|Ext|Class)\b)([A-Z]\w*)\s*(?:\.|::)\s*(create|insert|insertMany|bulkCreate|create!)\s*\((?!\s*\))/, say: (m, c) => { const w = whoseFrom(inside(c, c.indexOf('(')) ?? '').replace(/^whose /, ''); return { says: `Saves a new ${words(m[1])}${w ? ` with ${w.replace(/ is /g, ' ').replace(/ and /g, ', ')}` : ''}`, does: 'save' }; } },
112
112
  { re: /^([A-Z]\w*)\s*\.\s*(updateOne|updateMany|findByIdAndUpdate|findOneAndUpdate|update_all)\s*\(/, say: (m) => ({ says: `Changes ${/Many|all/.test(m[2]) ? `the ${plural(words(m[1]))}` : `a ${words(m[1])}`}`, does: 'save' }) },
113
113
  { re: /^([A-Z]\w*)\s*\.\s*(deleteOne|deleteMany|findByIdAndDelete|destroy|destroy_all|delete_all)\s*\(/, say: (m) => ({ says: `Removes ${/Many|all/.test(m[2]) ? `the ${plural(words(m[1]))}` : `a ${words(m[1])}`}`, does: 'save' }) },
114
114
  { re: /^([A-Z]\w*)\s*\.\s*(countDocuments|count)\s*\(/, say: (m) => ({ says: `Counts the ${plural(words(m[1]))}`, does: 'find' }) },
@@ -149,7 +149,7 @@ const CATALOG = [
149
149
  // ── Laravel query builder ──
150
150
  { re: /^DB\s*::\s*table\s*\(\s*["']([\w.]+)["']\s*\)(.*)$/, say: (m) => ({ says: /->(insert|insertGetId)\(/.test(m[2]) ? `Saves a new row in ${words(m[1])}` : /->update\(/.test(m[2]) ? `Changes rows in ${words(m[1])}` : /->delete\(/.test(m[2]) ? `Removes rows from ${words(m[1])}` : `Finds rows in ${words(m[1])}`, does: /->(insert|update|delete)/.test(m[2]) ? 'save' : 'find' }) },
151
151
  // ── Saving an object you already have (ORM instance) ──
152
- { re: /^(\$?[a-z_]\w*)\s*(?:\.|->)\s*(save|save!|delete|destroy|update)\s*\(\s*\)$/, say: (m) => ({ says: `${{ save: 'Saves', 'save!': 'Saves', delete: 'Removes', destroy: 'Removes', update: 'Saves' }[m[2]]} ${words(m[1])}`, does: 'save' }) },
152
+ { re: /^(\$?[a-z_]\w*)\s*(?:\.|->)\s*(save|save!|delete|destroy)\s*\(\s*\)$/, say: (m) => ({ says: `${{ save: 'Saves', 'save!': 'Saves', delete: 'Removes', destroy: 'Removes' }[m[2]]} ${words(m[1])}`, does: 'save' }) },
153
153
 
154
154
  // ── Caches ──
155
155
  { re: /^(?:this\.)?(?:redis|cache|client|redisClient|_cache)\s*\.\s*(get|set|setex|del|exists|expire|incr|hget|hset)\s*\(\s*(.*)$/i, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); const k = a[0] ? valueWords(a[0]) : 'a key'; const S = { get: `Reads ${k} from the cache`, set: `Keeps ${k} in the cache`, setex: `Keeps ${k} in the cache for a while`, del: `Removes ${k} from the cache`, exists: `Checks whether ${k} is in the cache`, expire: `Sets when ${k} leaves the cache`, incr: `Adds 1 to ${k} in the cache`, hget: `Reads ${k} from the cache`, hset: `Keeps ${k} in the cache` }; return { says: S[m[1].toLowerCase()], does: /^(get|exists|hget)$/i.test(m[1]) ? 'find' : 'save' }; } },
package/src/meaning.mjs CHANGED
@@ -397,7 +397,8 @@ class Parser {
397
397
 
398
398
  // ── expressions ──
399
399
  expr(min = 0) {
400
- if (this.spans) { const a = this.peek().s; const e = this.expr0(min); this.spans.set(e, [a, this.L.at(this.k - 1).e]); return e; }
400
+ // (An expression that took no token, such as JSX read as code, has an empty span rather than none.)
401
+ if (this.spans) { const a = this.peek().s; const e = this.expr0(min); const last = this.k > 0 ? this.L.at(this.k - 1) : null; this.spans.set(e, [a, last ? last.e : a]); return e; }
401
402
  return this.expr0(min);
402
403
  }
403
404
  expr0(min) {
package/src/model.mjs CHANGED
@@ -10,7 +10,7 @@ import { makeThingReaders } from './things-langs.mjs';
10
10
  import { sqlThings } from './sql.mjs';
11
11
  import { rThings } from './rlang.mjs';
12
12
  import { psThings } from './powershell.mjs';
13
- import { splitLogic, closeOf, isCodeWords } from './faithful.mjs';
13
+ import { splitLogic, closeOf, isCodeWords, balancedText } from './faithful.mjs';
14
14
  import { detailParts } from './meaning.mjs';
15
15
  import { linkSystem, callsSummary } from './system.mjs';
16
16
 
@@ -269,7 +269,8 @@ const possessiveWords = (text) => String(text)
269
269
  .replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => (/^(self|this)$/.test(a) ? `the ${words(b)}` : `the ${words(a)}'s ${words(b)}`))
270
270
  .replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
271
271
  /** An answer as words: NoFee -> "No fee", true -> "Yes". */
272
- const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : cap(words(r)));
272
+ // (Quoted text is an answer as written: its case, signs, and spaces are kept.)
273
+ const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : /^(["'`]).*\1$/s.test(String(r).trim()) ? String(r).trim() : cap(words(r)));
273
274
 
274
275
  /**
275
276
  * A branch as a question a kid can answer with yes or no, asked the positive way round. "If book.status is not on
@@ -296,9 +297,11 @@ function askWords(step, ruleLabel) {
296
297
  // The faithfulness gate gave the code back: ask the code itself, Yes when it is true.
297
298
  if (isCodeWords(c)) return { text: `${c}?`, flip, code: true };
298
299
  if (ruleLabel) {
299
- const negated = /^not\b|^!/.test(String(step.code || '').replace(/^\s*if\s*\(?\s*/, '')) || /\bnot\s+(self|this)\./.test(step.code || '') || /!\s*(this|self)\./.test(step.code || '');
300
+ const negated = /^not\b|^!/.test(String(step.code || '').replace(/^\s*(?:if|guard|unless|elsif)\s*\(?\s*/, '')) || /\bnot\s+(self|this)\./.test(step.code || '') || /!\s*(this|self)\./.test(step.code || '');
300
301
  // The negation is read from the code alone; the step's wording may already say "not" for the same reason.
301
- return { text: `${ruleLabel.replace(/\?$/, '')}?`, flip: negated };
302
+ // (Swift `guard x else { return }` and Ruby `unless x` take their steps when x does not hold.)
303
+ const outer = /^\s*(?:guard|unless)\b/.test(String(step.code || '')) || (/\bunless\b/.test(String(step.code || '')) && /^If not: /.test(String(step.says || '')));
304
+ return { text: `${ruleLabel.replace(/\?$/, '')}?`, flip: negated !== outer };
302
305
  }
303
306
  let m;
304
307
  // A compound condition (a and b, a or not b) is asked as written: turning one part positive would flip the
@@ -311,6 +314,9 @@ function askWords(step, ruleLabel) {
311
314
  // as a review's "Now stops with 403 when …". Only where the question splits cleanly into a subject and the rest.
312
315
  const is = (a, b) => ({ yes: `${possessive(a)} is ${possessive(b)}`, no: `${possessive(a)} is not ${possessive(b)}` });
313
316
  const has = (a, b) => ({ yes: `${possessive(a)} has ${b}`, no: `${possessive(a)} has no ${b}` });
317
+ // (The subject of "is" must be whole: in `(a is not 0) is not (b is not 0)` the first "is not" is inside brackets,
318
+ // and turning that round would flip the question. A comparison of comparisons is asked as written.)
319
+ if (/[()]/.test(c) && !balancedText(c.split(/ is | has /)[0])) return { text: `${cap(possessive(c))}?`, flip };
314
320
  if ((m = c.match(/^(.+?) is not (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip: !flip, holds: is(m[1], m[2]) };
315
321
  if ((m = c.match(/^(.+?) has no (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip: !flip, holds: has(m[1], m[2]) };
316
322
  if ((m = c.match(/^(.+?) is (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip, holds: is(m[1], m[2]) };
@@ -656,6 +662,7 @@ export function thunderModel(files, { name = 'app' } = {}) {
656
662
  if (!language || !f.source) continue;
657
663
  let reading;
658
664
  try { reading = readingOf(f, language); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); fileInfo.push({ path: f.path, language, category: categoryOf(language), skipped: `Could not read this file: ${e.message}` }); continue; }
665
+ if (reading.skipped) { unknowns.push({ file: f.path, line: 1, why: reading.skipped }); fileInfo.push({ path: f.path, language, category: categoryOf(language), skipped: reading.skipped }); continue; }
659
666
  const infra = INFRA_LANGUAGES.includes(language) ? reading.infra : null;
660
667
  let fileThings = [];
661
668
  try { fileThings = infra ? infra.things.map((t) => ({ ...t, knows: t.knows.map((k) => ({ ...k })) })) : language === 'python' ? pythonThings(f.source, f.path) : language === 'typescript' || language === 'javascript' ? tsThings(f.source, f.path) : language === 'sql' ? sqlThings(f.source, f.path) : language === 'r' ? rThings(f.source, f.path, THING_HELPERS) : language === 'powershell' ? psThings(f.source, f.path, THING_HELPERS) : thingsFor(language, f.source, f.path); }
@@ -801,7 +808,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
801
808
  const pad = (d) => ' '.repeat(d);
802
809
  // `note` (optional) adds words after a node: the running system's counts (running.mjs).
803
810
  const at = (n) => `${n.line ? ` (line ${n.line})` : ''}${(note && note(n)) || ''}`;
804
- const say = (n) => (n.kind === 'code' || (n.kind === 'end' && n.code) ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' && n.cases ? n.text : n.kind === 'decision' ? `Ask: ${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
811
+ // (A value given back that could not be put into words still says it is given back: the ending is never hidden.)
812
+ const say = (n) => (n.kind === 'end' && n.code && !/^(?:return|yield)\b/.test(String(n.text).trim()) ? `Gives back \`${n.text}\` (code, not explained)` : n.kind === 'code' || (n.kind === 'end' && n.code) ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' && n.cases ? n.text : n.kind === 'decision' ? `Ask: ${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
805
813
  const go = (blocks, d) => {
806
814
  for (const b of blocks || []) {
807
815
  const n = byId.get(b.id);
@@ -35,6 +35,8 @@ function skipParen(s, i) {
35
35
  let d = 0;
36
36
  for (let j = i; j < s.length; j++) {
37
37
  const c = s[j];
38
+ // (A backtick escapes the next character, as in `"Apps$(if($q) { `" matching`"})"`.)
39
+ if (c === '`') { j++; continue; }
38
40
  if (c === "'" || c === '"') { j = skipString(s, j) - 1; continue; }
39
41
  if (c === '(') d++;
40
42
  else if (c === ')' && --d === 0) return j + 1;
@@ -205,7 +207,8 @@ function singleInsert(tok) {
205
207
  }
206
208
  /** A message: quoted text as it is; any other value in words, never inside quotes it does not have. */
207
209
  const messageOf = (v) => (v == null || v === '' ? '' : v);
208
- const quoteText = (t) => `"${t.length > 100 ? `${t.slice(0, 99)}…` : t}"`;
210
+ // (Shortened only between placeholders: a «value» is never cut in half.)
211
+ const quoteText = (t) => { if (t.length <= 100) return `"${t}"`; let cut = 99; const open = t.lastIndexOf('«', cut); if (open >= 0 && t.indexOf('»', open) >= cut) cut = open; return `"${t.slice(0, cut)}…"`; };
209
212
 
210
213
  const at0 = (toks) => toks.filter((t) => t.t !== 'nl' && t.t !== 'comment');
211
214
  /** Tokens grouped at the top level: each item is one token, or a bracket with everything inside it. */
@@ -251,9 +254,10 @@ function sayValue(toks, plain = false) {
251
254
  if (g.length === 1 && first.length > 1) {
252
255
  const open = first[0].text;
253
256
  const inner = first.slice(1, -1);
254
- if (open === '@(') return inner.length ? `the list ${listWords(splitCommas(inner).map((x) => sayValue(x) ?? 'a value').slice(0, 6))}` : 'an empty list';
257
+ // (Every item is counted: a list said with fewer items than it has would be a different list.)
258
+ if (open === '@(') { if (!inner.length) return 'an empty list'; const items = splitCommas(inner).map((x) => sayValue(x) ?? 'a value'); if (items.length === 1 && items[0] === 'a value') return 'a list of what the commands inside give'; return items.length > 6 ? `a list of ${items.length} items: ${items.slice(0, 5).join(', ')}, and ${items.length - 5} more` : `the list ${listWords(items)}`; }
255
259
  if (open === '{') return 'a set of steps to run later (a script block)';
256
- if (open === '@{') { const keys = at0(inner).filter((t, k, a) => (t.t === 'word' || t.t === 'str') && a[k + 1]?.text === '=').map((t) => words(t.t === 'str' ? t.body : t.text)); return keys.length ? `a table of ${listWords(keys.slice(0, 6))}` : 'an empty table'; }
260
+ if (open === '@{') { const ks = groups(at0(inner)).map((g) => g[0]).filter((t, k, a) => (t.t === 'word' || t.t === 'str' || t.t === 'var') && a[k + 1]?.text === '=').map((t) => (t.t === 'var' ? `the key in ${varWords(t.name)}` : words(t.t === 'str' ? t.body : t.text))); const keys = ks.length > 6 ? [...ks.slice(0, 5), `${ks.length - 5} more`] : ks; return keys.length ? `a table of ${listWords(keys)}` : at0(inner).some((t) => t.t !== 'nl' && t.t !== 'comment') ? 'a table' : 'an empty table'; }
257
261
  if ((open === '(' || open === '$(') && first[0].match != null) {
258
262
  const all = first[0].all;
259
263
  const st = splitStatements(all, first[0].i + 1, first[0].match);
@@ -328,7 +332,8 @@ function sayValue(toks, plain = false) {
328
332
  }
329
333
  // Several values separated by commas are a list.
330
334
  if (g.some((x) => x.length === 1 && x[0].text === ',')) { const items = splitCommas(toks).map((x) => sayValue(x, true)); if (items.every(Boolean)) return `the list ${listWords(items.slice(0, 6))}${items.length > 6 ? ', …' : ''}`; }
331
- if (!plain && g.some((x) => x.length === 1 && x[0].t === 'op')) { const c = condWords(toks, false); if (c) return `whether ${c}`; }
335
+ // (A pipeline is the values it gives: `-Match` after `Where-Object` is that command's switch, not a yes/no.)
336
+ if (!plain && !g.some((x) => x.length === 1 && x[0].text === '|') && g.some((x) => x.length === 1 && x[0].t === 'op')) { const c = condWords(toks, false); if (c) return `whether ${c}`; }
332
337
  const cmd = toks[0].t === 'word' || toks[0].text === '&' ? pipelineWords(toks) : null;
333
338
  if (cmd?.command) return `the result of ${gerund(cmd.says)}`;
334
339
  return null;
@@ -653,6 +658,19 @@ function pipelineWords(toks) {
653
658
  const lower = name.toLowerCase();
654
659
  const blockG = groups(p.slice(1)).find((x) => x[0].text === '{');
655
660
  const block = blockG?.[0];
661
+ // `Where-Object Name -Match "x"` / `Where-Object -Property Name -Value "x" -Match` (no script block).
662
+ if (lower === 'where-object' && !blockG) {
663
+ const opTok = p.slice(1).find((t) => t.t === 'op');
664
+ const a = argsOf(p.slice(1).filter((t) => t !== opTok));
665
+ if (opTok) a.switches.add(opTok.text.slice(1).toLowerCase());
666
+ const prop = at0(a.named.property ?? a.pos[0] ?? []);
667
+ const val = a.named.value ?? a.pos[1];
668
+ const OPS = { match: 'matches the pattern', notmatch: 'does not match the pattern', eq: 'is', ne: 'is not', like: 'is like', notlike: 'is not like', gt: 'is more than', ge: 'is at least', lt: 'is less than', le: 'is at most', contains: 'contains', in: 'is one of' };
669
+ const op = [...a.switches].map((x) => String(x).toLowerCase().replace(/^c|^i(?=[a-z]{2})/, '')).find((x) => OPS[x]);
670
+ const v = val ? sayValue(val) : null;
671
+ if (prop.length === 1 && prop[0].t === 'word' && op && v) { said.push(`keeps only those whose ${words(prop[0].text)} ${OPS[op]} ${v}`); command = true; continue; }
672
+ return null;
673
+ }
656
674
  if (lower === 'where-object') {
657
675
  const ct = blockG ? blockG.slice(1, -1) : p.slice(1);
658
676
  const c = gated(ct, condWords(ct, false));
@@ -682,7 +700,8 @@ function pipelineWords(toks) {
682
700
  if (lower === 'out-null') continue;
683
701
  if (lower === 'select-object') { const a = argsOf(p.slice(1)); const first = a.named.first ? sayValue(a.named.first) : null; const props = a.named.property ?? a.pos[0]; const xp = a.named.expandproperty ? at0(a.named.expandproperty) : null; said.push(xp?.length === 1 ? `takes each one's ${words(xp[0].text)}` : first ? `takes the first ${first}` : a.named.last ? `takes the last ${sayValue(a.named.last)}` : a.switches.has('unique') ? 'keeps one of each' : props ? `picks ${listWords(splitCommas(props).map((x) => words(at0(x)[0]?.text ?? '')))}` : 'picks some of them'); command = true; continue; }
684
702
  if (lower === 'sort-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`sorts them${by ? ` by ${listWords(splitCommas(by).map((x) => words(at0(x)[0]?.text ?? '')))}` : ''}${a.switches.has('descending') ? ', highest first' : ''}`); command = true; continue; }
685
- if (lower === 'measure-object') { said.push('counts them'); command = true; continue; }
703
+ // (`Measure-Object -Property Length -Sum` adds up their lengths; with no -Sum / -Average / … it counts them.)
704
+ if (lower === 'measure-object') { const a = argsOf(p.slice(1)); const prop = at0(a.named.property ?? a.pos[0] ?? []); const what = prop.length === 1 && prop[0].t === 'word' ? words(prop[0].text) : null; const kinds = ['sum', 'average', 'maximum', 'minimum'].filter((k) => [...a.switches].some((x) => String(x).toLowerCase() === k)); said.push(kinds.length ? `works out the ${listWords(kinds.map((k) => ({ sum: 'total', average: 'average', maximum: 'largest', minimum: 'smallest' }[k])))} of ${what ? `their ${what}` : 'them'}` : 'counts them'); command = true; continue; }
686
705
  if (lower === 'group-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`groups them${by ? ` by ${words(at0(by)[0]?.text ?? '')}` : ''}`); command = true; continue; }
687
706
  if (lower === 'format-table' || lower === 'format-list') { said.push(`shows them as a ${lower === 'format-table' ? 'table' : 'list'}`); command = true; continue; }
688
707
  if (lower === 'tee-object') { said.push('keeps a copy as it goes'); command = true; continue; }
package/src/read-repo.mjs CHANGED
@@ -98,6 +98,7 @@ export function readRepo(files, { maxFileBytes = 400000, maxFiles = 5000 } = {})
98
98
  let reading;
99
99
  try { reading = readCode(source, { language, file: path }); }
100
100
  catch (e) { skipped.push({ path, reason: e instanceof Error ? e.message : 'Could not be read.' }); continue; }
101
+ if (reading.skipped) { skipped.push({ path, reason: reading.skipped }); continue; }
101
102
  for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
102
103
  fileSummaries.push({ path, language, counts: reading.counts });
103
104
  }
package/src/read.mjs CHANGED
@@ -10,7 +10,7 @@
10
10
  // return cond ? X : Y (nested ternaries) Python: return X if cond else Y
11
11
  // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
12
12
  // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
13
- import { sqlItems } from './sql.mjs';
13
+ import { sqlItems, sqlTemplateReason } from './sql.mjs';
14
14
  import { readDockerfile } from './infra-docker.mjs';
15
15
  import { readWorkflow } from './infra-gha.mjs';
16
16
  import { readTerraform } from './infra-terraform.mjs';
@@ -152,6 +152,13 @@ function skipString(src, i) {
152
152
  while (/\w/.test(src[j] || '')) j++;
153
153
  if (src[j] !== '\'') return i;
154
154
  }
155
+ // Rust text runs over lines until its closing quote; a raw string `r#"…"#` ends at the quote followed by its hashes.
156
+ if (q === '"' && READING_RUST) {
157
+ const raw = /\br(#*)$/.exec(src.slice(Math.max(0, i - 8), i));
158
+ if (raw) { const e = src.indexOf(`"${raw[1]}`, i + 1); return e < 0 ? src.length : e + raw[1].length; }
159
+ for (let j = i + 1; j < src.length; j++) { if (src[j] === '\\') { j++; continue; } if (src[j] === q) return j; }
160
+ return src.length;
161
+ }
155
162
  for (let j = i + 1; j < src.length; j++) {
156
163
  if (src[j] === '\\') { j++; continue; }
157
164
  if (src[j] === q) return j;
@@ -180,7 +187,7 @@ function parseParams(raw, language) {
180
187
  let pendingGo = [];
181
188
  for (let p of parts.map((x) => x.trim()).filter(Boolean)) {
182
189
  p = p.replace(/=.*$/, '').trim();
183
- if (/^&?\s*(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
190
+ if (/^&?\s*(?:'\w+\s+)?(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
184
191
  if (language === 'ruby') {
185
192
  if (/^&/.test(p)) continue; // a block argument
186
193
  out.push({ name: p.replace(/^\*+/, '').replace(/:.*$/, '').trim(), type: null });
@@ -1127,7 +1134,7 @@ function annotateRoutes(fns, src) {
1127
1134
  let m;
1128
1135
  if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
1129
1136
  if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
1130
- if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: m[2] || '/' }; break; }
1137
+ if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: m[2] || '/' }; break; }
1131
1138
  if ((m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'ANY').toUpperCase(), path: m[1] }; break; }
1132
1139
  if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
1133
1140
  if ((m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
@@ -1329,7 +1336,9 @@ function lex(text) {
1329
1336
  return out;
1330
1337
  }
1331
1338
 
1332
- const unquote = (t) => t.slice(1, -1);
1339
+ // The text a quoted literal stands for: `'\t'` is a tab, not a backslash and a t (written back with JSON escapes).
1340
+ const ESCAPES = { t: '\t', n: '\n', r: '\r', 0: '\0', '\\': '\\', '"': '"', "'": "'", '`': '`' };
1341
+ const unquote = (t) => t.slice(1, -1).replace(/\\([tnr0\\"'`])/g, (m, c) => ESCAPES[c]);
1333
1342
 
1334
1343
  /** Convert a condition to ThunderLang, or return null with nothing guessed. */
1335
1344
  export function toThunderCondition(text, inputs = []) {
@@ -1794,6 +1803,8 @@ function splitStatements(body, baseLine) {
1794
1803
  } else if (c === ';' && depth === 0) {
1795
1804
  // Go: `if err := open(); err != nil {` and `for i := 0; i < n; i++ {` keep their header together.
1796
1805
  if (/^\s*(?:if|for|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /\{/.test(src.slice(i, src.indexOf('\n', i) < 0 ? undefined : src.indexOf('\n', i)))) continue;
1806
+ // (Go: the condition after `;` can go on over lines, `if w, ok := f(); !ok ||\n g() {`.)
1807
+ if (/^\s*(?:if|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /(?:\|\||&&|[,(])\s*\n[^;{}]*\{/.test(src.slice(i, i + 600))) { const nb = src.indexOf('{', i), ns = src.indexOf(';', i + 1); if (nb > 0 && (ns < 0 || nb < ns)) continue; }
1797
1808
  i++; break;
1798
1809
  }
1799
1810
  else if (c === '\n' && depth === 0) {
@@ -1812,8 +1823,9 @@ function splitStatements(body, baseLine) {
1812
1823
  if (/^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && headerClosed(before)) continue;
1813
1824
  // (Nested: `for (…)\n if (…)\n return 1;` is one statement: the last line is itself a brace-less header.)
1814
1825
  const lastLine = before.slice(before.lastIndexOf('\n') + 1).trim();
1815
- if (lastLine !== before && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && /^(?:if|for|foreach|while)\s*\(/.test(lastLine) && headerClosed(lastLine)) continue;
1816
- if (/^(?:\}\s*)?else$/.test(before)) continue;
1826
+ if (lastLine !== before && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while)\s*\(/.test(lastLine) && headerClosed(lastLine.replace(/^(?:\}\s*)?else\s+/, ''))) continue;
1827
+ // (`} else if (x)` / `} else` closing a braced if, with its one statement on the next line.)
1828
+ if (/^(?:\}\s*)?else$/.test(before) || (lastLine !== before && /^(?:if|else)\b/.test(before) && /^(?:\}\s*)?else$/.test(lastLine))) continue;
1817
1829
  // (`i++` / `n--` at the end of a line is a whole statement, not an operator waiting for more.)
1818
1830
  // (`do { … }` with its `while (…)` on the next line, Allman style, is one statement.)
1819
1831
  if (before && (!/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) || /[\w)\]](?:\+\+|--)$/.test(before)) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after) && !(/^(?:do|repeat)\b/.test(before) && /\}$/.test(before) && /^while\b/.test(after))) { i++; break; }
@@ -1860,6 +1872,7 @@ function stripCommentsKeepLayout(s) {
1860
1872
  if (c === '"' || c === "'" || c === '`') {
1861
1873
  // A quote is a string only when it closes (on the same line, except template and raw strings).
1862
1874
  let j = i + 1;
1875
+ if (c === '"' && READING_RUST) { const e = skipString(s, i); if (e < s.length) i = e; continue; }
1863
1876
  for (; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === c || (s[j] === '\n' && c !== '`')) break; }
1864
1877
  if (j < s.length && s[j] === c) i = j;
1865
1878
  continue;
@@ -2452,6 +2465,10 @@ function readPredicate(fn, lang, names, code) {
2452
2465
  // (C and C++ yes/no functions often return int, so only Swift is held to its declared type.)
2453
2466
  if (lang === 'swift' && fn.returns && !/^(?:Bool|bool|_Bool|boolean)\??$/.test(String(fn.returns).trim())) return null;
2454
2467
  if (/^(?:c|cpp)$/.test(lang) && fn.returns && /^(?:string|char\*|const char\*)$/.test(String(fn.returns).trim())) return null;
2468
+ // (C/C++ yes/no functions return bool or int; one that returns an enum or a class gives back that value.)
2469
+ if (/^(?:c|cpp)$/.test(lang) && fn.returns && !/^(?:(?:static\s+|inline\s+|const\s+)*(?:bool|_Bool|int|BOOL|\w*_bool|gboolean|unsigned|long|short|char))$/.test(String(fn.returns).trim())) return null;
2470
+ // (`p->style()` is a field of a pointer, not a comparison.)
2471
+ expr = expr.replace(/->/g, '.');
2455
2472
  if (/^(?:swift|c|cpp)$/.test(lang) && !BOOL_RETURN.test(String(fn.returns || '').trim()) && !/^Bool\??$/.test(String(fn.returns || '').trim()) && !LOGIC_OR_COMPARE.test(expr.replace(/"(?:\\.|[^"\\])*"/g, 'Q'))) return null;
2456
2473
  if (!(BOOL_RETURN.test(String(fn.returns || '').trim()) || LOGIC_OR_COMPARE.test(expr) || /\?$/.test(fn.name))) return null;
2457
2474
  const when = toThunderCondition(expr.replace(/\?$/, ''), names);
@@ -2513,14 +2530,28 @@ function markBuildOnlySteps(steps, fn, lang, code, srcLines) {
2513
2530
  // (A question or a loop keeps its own words, which the views turn into "Ask: …?"; the steps under it say it.)
2514
2531
  const holds = st.kind === 'branch' || st.kind === 'loop' || st.kind === 'try';
2515
2532
  if (label && label !== outer && !holds) st.says = `${st.says} (only in builds where \`${label}\`)`;
2533
+ // A loop header inside `#if … #endif` with its body outside it (`#if X\n while (…) {\n #endif`): the loop is
2534
+ // only in those builds; the steps inside are in every build. (Steps under a header are never given its label:
2535
+ // each says its own, from its own line.)
2536
+ if (label && label !== outer && st.kind === 'loop') st.says = `${st.says} (the loop only in builds where \`${label}\`${(st.children || []).some((k) => !only.has(k.line)) ? '; the steps inside are in every build' : ''})`;
2516
2537
  const inner = holds ? outer : label || outer;
2517
- if (st.children) walk(st.children.map((k) => (holds && label && !only.has(k.line) ? (only.set(k.line, label), k) : k)), inner);
2538
+ if (st.children) walk(st.children, inner);
2518
2539
  for (const h of st.handlers || []) if (h.steps) walk(h.steps, inner);
2519
2540
  }
2520
2541
  };
2521
2542
  walk(steps, null);
2522
2543
  }
2523
2544
 
2545
+ /** Go named results: `(head, tail string, err error)` -> ['head', 'tail', 'err']; [] when they have no names. */
2546
+ function goResultNames(returns) {
2547
+ const r = String(returns || '').trim();
2548
+ if (!/^\(.*\)$/.test(r)) return [];
2549
+ const parts = splitTop(r.slice(1, -1), ',').map((x) => x.trim()).filter(Boolean);
2550
+ // Named when the last part is "name type"; then each part's first word is a name.
2551
+ if (!parts.length || !/^[A-Za-z_]\w*\s+\S/.test(parts[parts.length - 1])) return [];
2552
+ return parts.map((p) => p.split(/\s+/)[0]).filter((n) => /^[A-Za-z_]\w*$/.test(n) && n !== '_').map((n) => displayLabel(n).toLowerCase());
2553
+ }
2554
+
2524
2555
  function functionSteps(fn, lang, code, names, srcLines = []) {
2525
2556
  let stmts = [];
2526
2557
  try {
@@ -2534,8 +2565,31 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2534
2565
  // So does one that is a single call or expression when the function says it gives something back
2535
2566
  // (`func base32Bytes() -> [UInt8] { Base32.default.encode(…) }` gives back what encode makes).
2536
2567
  if (lang === 'swift' && stmts.length === 1 && ((!stmts[0].children?.length && swiftImplicitValue(stmts[0].text)) || swiftImplicitResult(stmts[0].text, fn.returns || (fn.route ? 'a response' : null)))) stmts[0] = { ...stmts[0], implicitReturn: true };
2568
+ // Rust gives back the value of its last expression (written without `;`): `Ok(n)` at the end is what comes back.
2569
+ let rustTail = null;
2570
+ if (lang === 'rust' && fn.returns && !/^\(\s*\)$/.test(String(fn.returns).trim())) {
2571
+ const last = stmts[stmts.length - 1];
2572
+ const ends = last && last.end != null ? /^\s*;/.test(fn.body.slice(last.end)) : true;
2573
+ if (last && !ends) {
2574
+ if (/^(?:match|if)\b/.test(String(last.text).trim())) rustTail = last;
2575
+ else if (!/^(?:let|for|while|loop|return|break|continue|const|static|use|fn|impl|struct|enum)\b|^[\w.\[\]*]+\s*(?:[-+*/%|&^]|<<|>>)?=(?!=)|!\s*\(|^[a-z_][\w:]*!/.test(String(last.text).trim()) || /^(?:vec|format|matches)!/.test(String(last.text).trim())) stmts[stmts.length - 1] = { ...last, implicitReturn: true };
2576
+ }
2577
+ }
2537
2578
  const r = withLanguage(lang, () => withFunctionContext({ params: fn.params || [], language: lang, route: !!fn.route }, () => {
2538
2579
  const out = stepsFrom(stmts);
2580
+ // Rust: a `match` / `if` that ends the function gives back what each arm or side ends with.
2581
+ if (rustTail) {
2582
+ const tail = out.steps[out.steps.length - 1];
2583
+ const giveBack = (list) => {
2584
+ const k = list?.[list.length - 1];
2585
+ if (!k) return;
2586
+ if (k.caseLabel || (k.kind === 'branch' && /^(?:match|if)\b/.test(String(k.code || '')))) { for (const arm of k.caseLabel ? [k] : []) giveBack(arm.children); if (!k.caseLabel) { for (const arm of (k.children || []).filter((c) => c.caseLabel)) giveBack(arm.children); if (!(k.children || []).some((c) => c.caseLabel)) giveBack(k.children); giveBack(k.otherwise); } return; }
2587
+ if (!/^(?:call|other)$/.test(k.kind) || k.jump || !k.code || /;\s*$/.test(k.code) || /^[\w.\[\]*]+\s*(?:[-+*/%|&^]|<<|>>)?=(?!=)|^(?:let|for|while|loop|unsafe)\b|^(?:panic|unreachable|todo|unimplemented)!/.test(String(k.code).replace(/,\s*$/, ''))) return;
2588
+ const v = classifyStatement(`return ${String(k.code).replace(/,\s*$/, '')}`);
2589
+ if (v.kind === 'return' || v.kind === 'fail') { list[list.length - 1] = { ...k, ...v, code: k.code }; delete list[list.length - 1].callee; delete list[list.length - 1].restates; }
2590
+ };
2591
+ if (tail) { if (tail.kind === 'branch' && (tail.children || []).some((c) => c.caseLabel)) for (const arm of tail.children.filter((c) => c.caseLabel)) giveBack(arm.children); else if (tail.kind === 'branch') { giveBack(tail.children); giveBack(tail.otherwise); } }
2592
+ }
2539
2593
  // Ruby gives back its last value: in a yes/no method (`def accepts?`) or a last line that is a comparison or
2540
2594
  // and/or, that value is the answer, not a call made for its effect.
2541
2595
  const last = out.steps[out.steps.length - 1];
@@ -2544,9 +2598,23 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2544
2598
  if (v.kind === 'return') out.steps[out.steps.length - 1] = { ...last, ...v, code: last.code, ...(/^Returns (?:a computed value|a value)$/.test(v.says) ? { restates: true } : {}) };
2545
2599
  delete out.steps[out.steps.length - 1].callee;
2546
2600
  }
2601
+ // Ruby, otherwise: a last line that is a value (shown as code, or read) is what the method gives back
2602
+ // (`cache[input].dup`), so the ending is never hidden. (Not `initialize` or a setter, whose value is not used.)
2603
+ else if (lang === 'ruby' && last && (last.kind === 'other' || (last.kind === 'call' && /^Reads /.test(last.says || ''))) && !last.jump && !last.children?.length && !/^(?:initialize|\w+=)$/.test(fn.name) && !/^[@$]?[\w.\[\]:]+\s*(?:[-+*/|&]{0,2})=(?![=~])|^(?:puts|print|p|pp|raise|fail|yield|super|require|include|extend|attr_\w+|private|protected|public|alias\w*|define_method)\b/.test(String(last.code || '').trim())) {
2604
+ const v = classifyStatement(`return ${String(last.code || '').trim()}`);
2605
+ if (v.kind === 'return') { out.steps[out.steps.length - 1] = { ...last, ...v, code: last.code, ...(/^Returns (?:a computed value|a value)$/.test(v.says) ? { restates: true } : {}) }; delete out.steps[out.steps.length - 1].callee; }
2606
+ }
2547
2607
  return out;
2548
2608
  }));
2549
2609
  if (lang === 'c' || lang === 'cpp') markBuildOnlySteps(r.steps, fn, lang, code, srcLines);
2610
+ // Go: a bare `return` in a function with named results gives back those results as they are then.
2611
+ if (lang === 'go') {
2612
+ const named = goResultNames(fn.returns);
2613
+ if (named.length) {
2614
+ const walk = (list) => { for (const st of list || []) { if (st.nested) continue; if (st.kind === 'return' && st.says === 'Stops here' && /^return\s*;?$/.test(String(st.code || '').trim())) st.says = `Returns ${named.length > 1 ? `${named.slice(0, -1).join(', ')} and ${named.at(-1)}` : named[0]}`; walk(st.children); walk(st.otherwise); for (const h of st.handlers || []) walk(h.steps); } };
2615
+ walk(r.steps);
2616
+ }
2617
+ }
2550
2618
  // A Swift `switch` that is the whole body of a function that gives something back: each case's one expression is
2551
2619
  // what comes back (`case .key(let key): String(reflecting: key)` gives back that text; it is not just a call).
2552
2620
  // So does an if / else if / else that is the whole body (Swift if-expressions).
@@ -2645,7 +2713,9 @@ export function readCode(source, { language, file = '', allSteps = false } = {})
2645
2713
  }
2646
2714
  // A rule is drawn only when every statement was read into it; a body with other steps (a loop, an assignment, a
2647
2715
  // later check) is read as steps instead, so no check is silently left out of the picture.
2648
- const isDecision = read.rules.length > 0 && !!read.otherwise && !read.unread.length;
2716
+ // (A check that returns or stops before the rules — `if shape != Line { return shape }` — is part of the answer: with
2717
+ // one, the body is read as steps, so no rule card claims fewer answers than the code can give.)
2718
+ const isDecision = read.rules.length > 0 && !!read.otherwise && !read.unread.length && !(read.guards || []).length;
2649
2719
  const guards = read.guards || [];
2650
2720
  // In a function that is not a pure decision, early fixed returns are still rules worth reading.
2651
2721
  if (!isDecision) {
@@ -2726,6 +2796,9 @@ export function searchReading(reading, { query = '', kinds = [], status = [] } =
2726
2796
 
2727
2797
  /** A reading of a SQL file in the same shape as every other language's. */
2728
2798
  function sqlReading(src) {
2799
+ // A dbt / Jinja template is listed as skipped with the reason: its SQL is not known until the template is filled in.
2800
+ const template = sqlTemplateReason(src);
2801
+ if (template) return { schema: READ_SCHEMA, language: 'sql', detected: false, items: [], counts: { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 }, skipped: template, limitations: [template] };
2729
2802
  const items = sqlItems(src);
2730
2803
  for (const it of items) it.completeness = completenessOf(it);
2731
2804
  const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
@@ -2734,6 +2807,7 @@ function sqlReading(src) {
2734
2807
  limitations: [
2735
2808
  'Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.',
2736
2809
  'Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps.',
2810
+ 'Routine bodies (PL/pgSQL, MySQL stored programs, T-SQL) are read block by block; a statement Thunder cannot say exactly is shown as code, and a body whose blocks do not match is shown as not read.',
2737
2811
  ],
2738
2812
  };
2739
2813
  }
package/src/rlang.mjs CHANGED
@@ -140,7 +140,8 @@ function argsOf(list) {
140
140
 
141
141
  // ── Words ─────────────────────────────────────────────────────────────────────────────────────────────
142
142
 
143
- const rWords = (name) => { const w = words(String(name).replace(/^\.+/, '').replace(/\./g, ' ')); return w || String(name); };
143
+ // (A name that starts with a dot, `.stroke`, is its own name: "stroke" would be a different variable.)
144
+ const rWords = (name) => { if (/^\.[A-Za-z_]\w*$/.test(String(name))) return String(name); const w = words(String(name).replace(/^\.+/, '').replace(/\./g, ' ')); return w || String(name); };
144
145
  const quote = (s) => `"${s.length > 100 ? `${s.slice(0, 99)}…` : s}"`;
145
146
 
146
147
  // Text with values inside (docs/spec.md): the literal parts are kept exactly as the code writes them (escapes
@@ -841,13 +842,19 @@ function makeReader(src) {
841
842
  if (call) {
842
843
  const { bare, args } = call;
843
844
  const a0 = args[0] ? sayValue(args[0].toks) : null;
844
- if (bare === 'stop' || bare === 'abort' || bare === 'cli_abort' || bare === 'stopf') {
845
+ // rlang's `stop_input_type(x, "a formula")` always stops: x is not what was wanted.
846
+ if (bare === 'stop_input_type') {
847
+ const what = at0(args[1]?.toks ?? [])[0];
848
+ const x = at0(args[0]?.toks ?? []);
849
+ return [{ kind: 'fail', says: `Fails with an input-type error${what?.t === 'str' || typeof what?.value === 'string' ? ` (${x.length === 1 ? rWords(x[0].text) : 'the value'} is not ${what.value})` : ''}`, error: 'an input-type error', ...base(s, e) }];
850
+ }
851
+ if (bare === 'stop' || bare === 'abort' || bare === 'cli_abort' || bare === 'stopf' || bare === 'ui_abort' || /^(?:abort_\w+|\w+_abort|stop_\w+)$/.test(bare)) {
845
852
  // Only cli_abort fills in {…}; stop() and rlang's abort() show their text as written.
846
853
  const parts = args.filter((a) => !a.name || a.name === 'message').map((a) => ({ ...a, name: null }));
847
854
  const one = at0(parts[0]?.toks ?? []);
848
855
  const isVar = parts.length === 1 && one.length === 1 && one[0].t === 'id';
849
856
  const single = !isVar && oneValue(parts) ? sayValue(parts[0].toks) : null;
850
- const msg = isVar || single || !parts.length ? null : textOf(parts, '', bare === 'cli_abort');
857
+ const msg = isVar || single || !parts.length ? null : textOf(parts, '', bare === 'cli_abort' || bare === 'ui_abort');
851
858
  if (msg) errors.set(msg, errors.get(msg) ?? lineAt(toks[s].at));
852
859
  const cls = args.find((a) => a.name === 'class');
853
860
  const name = cls ? (at0(cls.toks)[0]?.value ?? 'an error') : 'an error';
package/src/shell.mjs CHANGED
@@ -399,13 +399,16 @@ function braceWords(inner) {
399
399
  return `${d} when ${subj} ${colon ? 'is set and not empty' : 'is set'}, otherwise nothing`;
400
400
  }
401
401
  if ((m = rest.match(/^(##?|%%?)([\s\S]*)$/))) {
402
- const [, op, p] = m;
402
+ // (Shell quotes in a pattern only mark text as literal: `${x%', '}` removes ", ".)
403
+ const [, op, p0] = m;
404
+ const p = p0.replace(/'([^']*)'|"([^"$`\\]*)"/g, '$1$2');
403
405
  if (/\$/.test(p)) return null;
404
406
  const what = GLOBBY.test(p) ? `the ${op.length === 2 ? 'longest' : 'shortest'} match of "${p}"` : `"${p}"`;
405
407
  return `${subj} without ${what} at the ${op[0] === '#' ? 'start' : 'end'}`;
406
408
  }
407
409
  if ((m = rest.match(/^\/([/#%]?)((?:\\.|[^/\\])*)(?:\/([\s\S]*))?$/))) {
408
- const [, mode, p, r] = m;
410
+ const [, mode, p0, r] = m;
411
+ const p = p0.replace(/'([^']*)'|"([^"$`\\]*)"/g, '$1$2');
409
412
  if (!p || /\$/.test(p)) return null;
410
413
  const pat = GLOBBY.test(p) ? `match of "${p}"` : `"${p}"`;
411
414
  const which = mode === '/' ? `every ${pat}` : mode === '#' ? `${pat} at the start` : mode === '%' ? `${pat} at the end` : `the first ${pat}`;
@@ -575,8 +578,9 @@ const arithSays = (expr) => { const st = arithStatement(expr); if (st) return st
575
578
 
576
579
  // ── Tests and conditions ──────────────────────────────────────────────────────────────────────────────
577
580
 
578
- const PLACE = /(?:^|\s)(?:file|dir|directory|folder|path)$/;
579
- const fileLeaf = (noun, x, neg) => { const w = sayWord(x); const own = PLACE.test(w); return neg ? (own ? `${w} does not exist` : `there is no ${noun} ${w}`) : (own ? `${w} exists` : `the ${noun} ${w} exists`); };
581
+ // (A name says what it is only when it names that kind: `config_dir` is a folder, but `path` can be a file or a folder,
582
+ // so `[ -d "$path" ]` is "the folder path exists", never just "path exists".)
583
+ const fileLeaf = (noun, x, neg) => { const w = sayWord(x); const own = noun === 'file' ? /(?:^|\s)file$/.test(w) : /(?:^|\s)(?:dir|directory|folder)$/.test(w); return neg ? (own ? `${w} does not exist` : `there is no ${noun} ${w}`) : (own ? `${w} exists` : `the ${noun} ${w} exists`); };
580
584
  const UNARY = {
581
585
  '-f': (x, n) => fileLeaf('file', x, n), '-d': (x, n) => fileLeaf('folder', x, n),
582
586
  '-e': (x, n) => `${sayWord(x)} ${n ? 'does not exist' : 'exists'}`, '-a': (x, n) => `${sayWord(x)} ${n ? 'does not exist' : 'exists'}`,
@@ -615,7 +619,7 @@ function testWords(ws, neg, double) {
615
619
  if (BINARY[ws[i + 1]] && ws[i + 2] !== undefined) {
616
620
  const [a, op, b] = [ws[i], ws[i + 1], ws[i + 2]];
617
621
  i += 3;
618
- if ((op === '==' || op === '=' || op === '!=') && double && isGlob(b)) { const pos = op !== '!='; return `${sayWord(a)} ${pos !== n ? 'matches' : 'does not match'} ${b}`; }
622
+ if ((op === '==' || op === '=' || op === '!=') && double && isGlob(b)) { const pos = op !== '!='; return `${sayWord(a)} ${pos !== n ? 'matches' : 'does not match'} the pattern \`${b}\``; }
619
623
  // Compared with "" is a question about being empty.
620
624
  if ((op === '=' || op === '==' || op === '!=') && /^(?:""|'')$/.test(b)) return `${sayWord(a)} is ${(op === '!=') !== n ? 'not empty' : 'empty'}`;
621
625
  const pair = BINARY[op];
@@ -715,6 +719,25 @@ const TRAP_WHEN = (sigs) => {
715
719
  return `When it gets the signal ${s.join(' or ')}`;
716
720
  };
717
721
 
722
+ /** The words of a list, split at spaces outside quotes, `$( … )`, `${ … }`, and backticks: `a "b c" $(ls -a)`. */
723
+ function shellWordsOf(text) {
724
+ const out = [];
725
+ let cur = '', depth = 0, q = null;
726
+ for (let i = 0; i < text.length; i++) {
727
+ const c = text[i];
728
+ if (q) { cur += c; if (c === '\\' && q === '"') { cur += text[++i] ?? ''; continue; } if (c === q) q = null; continue; }
729
+ if (c === '\\') { cur += c + (text[++i] ?? ''); continue; }
730
+ if (c === '"' || c === "'" || c === '`') { q = c; cur += c; continue; }
731
+ if (c === '$' && (text[i + 1] === '(' || text[i + 1] === '{')) { depth++; cur += c + text[++i]; continue; }
732
+ if (depth && (c === '(' || c === '{')) { depth++; cur += c; continue; }
733
+ if (depth && (c === ')' || c === '}')) { depth--; cur += c; continue; }
734
+ if (!depth && /\s/.test(c)) { if (cur) out.push(cur); cur = ''; continue; }
735
+ cur += c;
736
+ }
737
+ if (cur) out.push(cur);
738
+ return out;
739
+ }
740
+
718
741
  /** One assignment word (`X=val`, `X+=val`, `arr=(a b)`) in words. */
719
742
  function assignWords(a, { exported = false, readonly = false } = {}) {
720
743
  const m = a.match(/^([A-Za-z_]\w*)(\[[^\]]*\])?(\+?)=([\s\S]*)$/);
@@ -722,11 +745,12 @@ function assignWords(a, { exported = false, readonly = false } = {}) {
722
745
  const [, name, index, plus, val] = m;
723
746
  const who = `${varWords(name)}${index ? `'s ${sayWord(index.slice(1, -1))}` : ''}`;
724
747
  const tail = exported ? ' and shares it with the programs it runs' : readonly ? ' (it cannot change after this)' : '';
725
- if (name === 'PATH' && /\$\{?PATH\}?/.test(val)) { const added = val.split(':').filter((x) => !/\$\{?PATH\}?/.test(x)); return `Adds ${listWords(added.map(sayWord))} to the PATH (where commands are found)`; }
748
+ // (`"${BIN}:${PATH}"`: the quotes go round the whole value, so each part is read inside them.)
749
+ if (name === 'PATH' && /\$\{?PATH\}?/.test(val)) { const q = /^"[^"]*"$/.test(val); const added = (q ? val.slice(1, -1) : val).split(':').filter((x) => !/\$\{?PATH\}?/.test(x)).map((x) => (q ? `"${x}"` : x)); return `Adds ${listWords(added.map(sayWord))} to the PATH (where commands are found)`; }
726
750
  if (/^\(/.test(val)) {
727
751
  const inner = val.slice(1, -1).trim();
728
752
  if (!inner) return `Starts ${who} as an empty list`;
729
- const items = inner.split(/\s+/).filter(Boolean);
753
+ const items = shellWordsOf(inner);
730
754
  return `${plus ? 'Adds' : 'Sets'} ${plus ? `${listWords(items.map(sayWord))} to ${who}` : `${who} to the list ${listWords(items.slice(0, 6).map(sayWord))}${items.length > 6 ? ', …' : ''}`}${tail}`;
731
755
  }
732
756
  if (val === '' || val === '""' || val === "''") return `Empties ${who}${tail}`;
@@ -754,8 +778,21 @@ function redirWords(redirs) {
754
778
  }
755
779
  const toStderr = (redirs) => redirs.some((r) => (r.op === '>&' && r.target === '2' && (!r.fd || r.fd === '1')) || (r.fd === '1' && r.op === '>&' && r.target === '2') || ((r.op === '>' || r.op === '>>') && r.target === '/dev/stderr'));
756
780
 
757
- /** A simple command as { kind, says, ... }, or null when it does nothing a reader needs (`:`, `true`). */
781
+ /**
782
+ * `exec prog args` runs prog in place of this script: the script ends there (`exec -a NAME prog` names it NAME).
783
+ * (`exec >&2` with no command only moves the output, and the script carries on.)
784
+ */
758
785
  function simpleSays(n, ctx = null) {
786
+ const w0 = String(n.words[0] ?? '').replace(/^\\/, '');
787
+ if (w0 !== 'exec' || n.words.length < 2) return simpleSaysInner(n, ctx);
788
+ let ws = n.words.slice(1);
789
+ while (/^-/.test(ws[0] ?? '')) ws = ws[0] === '-a' ? ws.slice(2) : ws.slice(1);
790
+ if (!ws.length) return simpleSaysInner(n, ctx);
791
+ const r = simpleSaysInner({ ...n, words: ws }, ctx);
792
+ return { kind: 'return', says: `${r?.says || `Runs ${sayWord(ws[0])}`}, in place of this script (it does not come back here)`, exec: true };
793
+ }
794
+
795
+ function simpleSaysInner(n, ctx = null) {
759
796
  // `\command`, `\cd`: a leading backslash only skips aliases; the command is the same.
760
797
  let ws = n.words.map((w, i) => (i === 0 ? w.replace(/^\\(?=[\w.])/, '') : w));
761
798
  if (!ws.length) {