@skillstech/thunderlang 1.0.3 → 1.1.0

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.
Files changed (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/dist/core.cjs +13779 -10043
  3. package/dist/index.cjs +28500 -24392
  4. package/dist/learn.cjs +12853 -9579
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/libraries.mjs +2 -2
  33. package/src/mcp.mjs +23 -0
  34. package/src/meaning.mjs +47 -7
  35. package/src/model.d.mts +7 -3
  36. package/src/model.mjs +30 -9
  37. package/src/money.d.mts +18 -0
  38. package/src/money.mjs +124 -0
  39. package/src/plain-contract.mjs +18 -2
  40. package/src/powershell.mjs +24 -5
  41. package/src/read-repo.mjs +1 -0
  42. package/src/read.d.mts +11 -0
  43. package/src/read.mjs +121 -13
  44. package/src/review-comment.d.mts +16 -0
  45. package/src/review-comment.mjs +145 -0
  46. package/src/rlang.mjs +10 -3
  47. package/src/say-less.mjs +1432 -0
  48. package/src/shell.mjs +45 -8
  49. package/src/sql-proc.mjs +1198 -0
  50. package/src/sql.mjs +87 -119
  51. package/src/steps.mjs +188 -37
  52. package/src/system.mjs +153 -44
  53. package/src/target-cs.mjs +39 -34
  54. package/src/target-elixir.mjs +40 -30
  55. package/src/target-go.mjs +41 -36
  56. package/src/target-java.mjs +34 -27
  57. package/src/target-kotlin.mjs +43 -35
  58. package/src/target-py.mjs +57 -55
  59. package/src/target-result.d.mts +48 -0
  60. package/src/target-result.mjs +112 -0
  61. package/src/target-rust.mjs +42 -38
  62. package/src/target-scala.mjs +45 -35
  63. package/src/target-ts.mjs +37 -45
  64. package/src/target-types.mjs +41 -5
  65. package/src/target-util.mjs +55 -2
  66. package/src/trace-cli.mjs +58 -0
  67. package/src/trace-fs.mjs +76 -0
  68. package/src/trace.mjs +261 -0
  69. package/src/translate.d.mts +3 -0
  70. package/src/translate.mjs +62 -32
  71. package/src/why-cli.mjs +31 -0
  72. package/src/why.d.mts +28 -0
  73. package/src/why.mjs +532 -0
  74. package/src/write-steps.mjs +22 -5
package/src/sql.mjs CHANGED
@@ -4,6 +4,8 @@
4
4
  // triggers are steps a person can follow. Deterministic, browser-safe, no SQL engine: read by pattern, like every
5
5
  // other language Thunder reads. Dialects: PostgreSQL first; MySQL, SQLite, and SQL Server syntax where it agrees.
6
6
 
7
+ import { sqlRoutines } from './sql-proc.mjs';
8
+
7
9
  const words = (s) => String(s).replace(/^["`[]|["`\]]$/g, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
8
10
  const unquote = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/, '$1');
9
11
  const bare = (name) => unquote(String(name).split('.').pop());
@@ -83,29 +85,71 @@ function defaultWords(v) {
83
85
  return 'worked out when it is saved';
84
86
  }
85
87
 
88
+ const LOGIC_WORD = /^(?:is|and|or|not|no)$/;
89
+ const SQL_KEYWORD = /^(?:AND|OR|NOT|IS|IN|NULL|LIKE|ILIKE|BETWEEN|TRUE|FALSE|EXISTS|NO)$/i;
90
+ /** True for a name whose words would read as logic: v_is_default, v_not_found, read_or_write (not the keywords). */
91
+ export const sqlLogicName = (id) => !SQL_KEYWORD.test(id) && String(id).split('.').some((p) => words(p.replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, '')).split(' ').some((w) => LOGIC_WORD.test(w)));
92
+
86
93
  /** A SQL condition as Thunder words: total >= 0 AND status IN ('a','b') -> "total is at least 0 and status is one of a, b". */
87
- export function sqlCondition(cond, { aliases = {}, vars = false } = {}) {
88
- let c = String(cond).trim().replace(/\s+/g, ' ');
94
+ export function sqlCondition(cond, { aliases = {}, vars = false, keepAt = true, raw = false } = {}) {
95
+ // Quoted text is held aside first and put back exactly as written: no rewrite (words, `=` -> "is") reaches inside
96
+ // it. `"…"` is a quoted text; a held raw value (an IN list's item, a MySQL @variable) is put back as it is.
97
+ const held = [];
98
+ const hold = (text) => `\u0001${held.push(text) - 1}\u0002`;
99
+ const back = (s) => { let out = String(s); for (let k = 0; k < 4 && /\u0001\d+\u0002/.test(out); k++) out = out.replace(/\u0001(\d+)\u0002/g, (m, n) => held[Number(n)]); return out; };
100
+ // (N'…' is SQL Server's Unicode text and E'…' PostgreSQL's text with escapes: the text is as written.)
101
+ let c = String(cond).trim().replace(/(?<![\w$])[NnEe]?'((?:[^']|'')*)'/g, (m, v) => hold(`"${v.replace(/''/g, "'")}"`));
102
+ // A system value (@@ROWCOUNT, @@FETCH_STATUS) is a name as written.
103
+ c = c.replace(/@@[A-Za-z_][\w$.]*/g, (m) => hold(`\`${m}\``));
104
+ // An extension's schema placeholder (@extschema@.fn(…)) is not part of the name.
105
+ c = c.replace(/@\w+@\.([A-Za-z_]\w*)(?=\s*\()/g, (m, fn) => hold(words(fn))).replace(/@\w+@/g, (m) => hold(`\`${m}\``));
106
+ // A MySQL @variable is a name as written, shown as code so no rewrite turns `@sys.debug` into words.
107
+ if (keepAt) c = c.replace(/@@?[A-Za-z_][\w.$]*/g, (m) => hold(`\`${m}\``));
108
+ else c = c.replace(/@(?=[A-Za-z_])/g, '');
109
+ // A name whose words would read as logic (v_is_default, v_not_found, read_or_write) is kept as written: in words
110
+ // it would be mistaken for the question's own "is", "not", or "or".
111
+ c = c.replace(/(?<![\w.$\u0001])[A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*)*(?![\w$])/g, (m) => (sqlLogicName(m) ? hold(`\`${m}\``) : m));
112
+ c = c.replace(/\s+/g, ' ');
89
113
  while (/^\(.*\)$/.test(c) && parenEnd(mask(c), 0) === c.length - 1) c = c.slice(1, -1).trim();
90
- // Strings first, in Thunder's quotes, so a possessive apostrophe is never mistaken for one.
91
- c = c.replace(/'((?:[^']|'')*)'/g, (m, v) => `"${v.replace(/''/g, "'")}"`);
92
- const plain = (x) => words(vars ? String(x).replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, '') : x);
93
- const name = (x) => { const p = String(x).split('.'); if (p.length < 2) return plain(x); const table = aliases[p[0].toLowerCase()] ?? p[0]; return `the ${singular(words(table))}'s ${words(p[1])}`; };
94
- return c
114
+ // In a routine, v_total and p_total read as "total"; when that would make both sides of a comparison the same
115
+ // words ("parent table is parent table"), the prefixed names are kept as written instead (raw).
116
+ const prefixed = /^(?:p|v|l|in|out|var)_(?=\w)/i;
117
+ const plain = (x) => (raw && prefixed.test(x) ? `\`${x}\`` : words(vars ? String(x).replace(prefixed, '') : x));
118
+ // Two names compared (a = b) read "a is the same as b": "Is parent interval the same as interval?", not "Is
119
+ // parent interval interval?".
120
+ if (vars) c = c.replace(/(?<![\w."@\u0002])([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)\s*(=|<>|!=)\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)(?![\w.(\u0001])/g, (m, a, op, b) => (/^(?:NULL|TRUE|FALSE|AND|OR|NOT|IS|IN|CURRENT_TIMESTAMP|CURRENT_DATE|NOW)$/i.test(a) || /^(?:NULL|TRUE|FALSE|AND|OR|NOT|IS|IN)$/i.test(b) ? m : `${a} ${op === '=' ? '\u0003' : '\u0004'} ${b}`));
121
+ const name = (x) => {
122
+ if (/^\u0001\d+\u0002$/.test(x) || /\(/.test(x)) return x;
123
+ const p = String(x).split('.');
124
+ if (p.length < 2) return plain(x);
125
+ const table = aliases[p[0].toLowerCase()];
126
+ return table ? `the ${singular(words(table))}'s ${words(p[1])}` : vars ? `the ${plain(p[0])}'s ${words(p[1])}` : `the ${singular(words(p[0]))}'s ${words(p[1])}`;
127
+ };
128
+ // An IN list's items, exactly as they are written (a quoted text stays quoted).
129
+ const items = (l) => l.split(',').map((x) => hold(x.trim())).join(', ');
130
+ const pattern = (n) => held[Number(n)].slice(1, -1);
131
+ const out = c
95
132
  .replace(/\b(NEW|OLD)\.(\w+)/g, (m, which, col) => `the ${which === 'NEW' ? 'new' : 'old'} ${words(col)}`)
96
- .replace(/([\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is not one of ${l.split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).join(', ')}`)
97
- .replace(/([\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => (/^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${l.split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).join(', ')}`))
98
- .replace(/([\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`)
99
- .replace(/([\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is empty`)
100
- .replace(/([\w.]+)\s+NOT\s+LIKE\s+"([^"]*)"/gi, (m, a, p) => `${name(a)} does not match "${p.replace(/%/g, '…')}"`)
101
- .replace(/([\w.]+)\s+I?LIKE\s+"([^"]*)"/gi, (m, a, p) => (/^[^%]+%$/.test(p) ? `${name(a)} starts with "${p.slice(0, -1)}"` : /^%[^%]+%$/.test(p) ? `${name(a)} contains "${p.slice(1, -1)}"` : `${name(a)} matches "${p.replace(/%/g, '…')}"`))
133
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is none of ${items(l)}`)
134
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => (/^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${items(l)}`))
135
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`)
136
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is missing`)
137
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w.]+)\s+NOT\s+LIKE\s+\u0001(\d+)\u0002/gi, (m, a, n) => `${name(a)} does not match ${hold(`"${pattern(n).replace(/%/g, '…')}"`)}`)
138
+ .replace(/(\u0001\d+\u0002|(?!NOT\b)[A-Za-z_][\w.]*\([^()]*\)|(?!NOT\b)[\w.]+)\s+I?LIKE\s+\u0001(\d+)\u0002/gi, (m, a, n) => { const p = pattern(n); return /^[^%_]+%$/.test(p) ? `${name(a)} starts with ${hold(`"${p.slice(0, -1)}"`)}` : /^%[^%_]+%$/.test(p) ? `${name(a)} contains ${hold(`"${p.slice(1, -1)}"`)}` : `${name(a)} matches ${hold(`"${p.replace(/%/g, '…')}"`)}`; })
102
139
  .replace(/([\w."]+)\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)/gi, (m, a, lo, hi) => `${name(a)} is from ${lo} to ${hi}`)
103
- .replace(/\s*(<>|!=)\s*/g, ' is not ').replace(/\s*>=\s*/g, ' is at least ').replace(/\s*<=\s*/g, ' is at most ')
140
+ // `<>` and NOT IN read as a positive question ("is different from", "is none of"), never "is not" turned round:
141
+ // with a NULL the code's condition is not true, so the code takes the No side, and so does the question.
142
+ .replace(/\s*(<>|!=)\s*/g, ' is different from ').replace(/\s*>=\s*/g, ' is at least ').replace(/\s*<=\s*/g, ' is at most ')
104
143
  .replace(/\s*>\s*/g, ' is more than ').replace(/\s*<\s*/g, ' is less than ').replace(/\s*=\s*/g, ' is ')
105
144
  .replace(/\bAND\b/gi, 'and').replace(/\bOR\b/gi, 'or').replace(/\bNOT\s+/gi, 'not ')
106
145
  .replace(/\b(?:length|char_length)\s*\(\s*([\w."]+)\s*\)/gi, (m, a) => `the length of ${name(a)}`)
107
- .replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b)([a-z_][\w]*\.)?([a-z_][\w]*)\b(?![^"]*"(?:[^"]*"[^"]*")*[^"]*$)/gi, (m, t, col) => (t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)))
146
+ .replace(/\b[a-z_]\w*\.([a-z_]\w*)(?=\s*\()/gi, (m, fn) => hold(/^[A-Z_]+$/.test(fn) ? fn : words(fn)))
147
+ .replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b(?!\.))([a-z_][\w]*\.)?([a-z_][\w]*)\b/gi, (m, t, col) => (t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)))
148
+ .replace(/\s*\u0003\s*/g, ' is the same as ').replace(/\s*\u0004\s*/g, ' is different from ')
108
149
  .replace(/\s+/g, ' ').trim();
150
+ const said = back(out);
151
+ if (vars && !raw && /(?:^|\(|\b(?:and|or|not) )((?:the [\w ]+'s )?[a-z][\w ]*?) (?:is (?:not )?(?:the same as )?|and |or )\1(?=$|[\s),])/.test(said)) return sqlCondition(cond, { aliases, vars, keepAt, raw: true });
152
+ return said;
109
153
  }
110
154
 
111
155
  // ── Tables, types: Things, Data, and Choices ─────────────────────────────────────────────────────────────
@@ -191,7 +235,7 @@ const colWords = (expr) => {
191
235
  const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
192
236
 
193
237
  /** The steps of one SELECT: finds, joins, keeps only, groups, sorts, takes, gives back. */
194
- function selectSteps(sql, line, { give = true, vars = false } = {}) {
238
+ export function selectSteps(sql, line, { give = true, vars = false } = {}) {
195
239
  const s = sql.replace(/\s+/g, ' ').trim().replace(/;$/, '');
196
240
  const m = mask(s);
197
241
  const at = (kw) => { const r = new RegExp(`\\b${kw}\\b`, 'i').exec(m); return r ? r.index : -1; };
@@ -234,89 +278,21 @@ function selectSteps(sql, line, { give = true, vars = false } = {}) {
234
278
  return steps;
235
279
  }
236
280
 
237
- /** One statement in a function or procedure body, read as a step. */
238
- function bodyStatement(text, line) {
239
- const cnd = (x) => sqlCondition(x, { vars: true });
240
- const v = (x) => words(String(x).replace(/^(?:p|v|l|var)_(?=\w)/i, ''));
241
- const t = text.replace(/\s+/g, ' ').trim().replace(/;$/, '');
242
- const code = t;
243
- let x;
244
- if ((x = t.match(/^RAISE\s+(?:EXCEPTION|ERROR)\s+'((?:[^']|'')*)'/i))) { const msg = x[1].replace(/''/g, "'").replace(/%/g, '…'); return { kind: 'fail', says: `Fails with an error: "${msg}"`, error: 'an error', message: msg, code, line }; }
245
- if ((x = t.match(/^(?:RAISERROR|THROW)\s*\(?\s*(?:\d+\s*,\s*)?N?'((?:[^']|'')*)'/i)) || (x = t.match(/^SIGNAL\s+SQLSTATE\s+'\w+'\s+SET\s+MESSAGE_TEXT\s*=\s*'((?:[^']|'')*)'/i))) return { kind: 'fail', says: `Fails with an error: "${x[1].replace(/''/g, "'")}"`, error: 'an error', message: x[1].replace(/''/g, "'"), code, line };
246
- if ((x = t.match(/^RETURN\s+QUERY\s+(SELECT\b.*)$/i))) return { kind: 'return', says: selectSteps(x[1], line).at(-1)?.says ?? 'Returns the rows a query finds', code, line, query: selectSteps(x[1], line, { give: false }) };
247
- if ((x = t.match(/^RETURN\s+(NEW|OLD)$/i))) return { kind: 'return', says: x[1].toUpperCase() === 'NEW' ? 'Lets the change go ahead' : 'Keeps the old row', code, line };
248
- if ((x = t.match(/^RETURN\s*(.*)$/i))) return { kind: 'return', says: x[1] ? (/^'(.*)'$/.test(x[1]) ? `Returns "${x[1].slice(1, -1)}"` : /^(true|false)$/i.test(x[1]) ? `Returns ${x[1].toLowerCase() === 'true' ? 'yes' : 'no'}` : `Returns ${cnd(x[1])}`) : 'Stops here', code, line };
249
- if ((x = t.match(/^INSERT\s+INTO\s+([\w."]+)(?:\s*\(([^)]*)\))?/i))) return { kind: 'call', says: `Records a new ${singular(words(bare(x[1])))}${x[2] ? ` with ${listWords(x[2].split(',').map((c) => words(c.trim())))}` : ''}`, code, line };
250
- if ((x = t.match(/^UPDATE\s+([\w."]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/i))) {
251
- const sets = splitTop(x[2]).map((p) => { const kv = p.text.match(/^\s*([\w."]+)\s*=\s*(.*)$/s); return kv ? `${words(bare(kv[1]))} to ${/^'.*'$/.test(kv[2].trim()) ? `"${kv[2].trim().slice(1, -1)}"` : cnd(kv[2])}` : null; }).filter(Boolean);
252
- return { kind: 'call', says: `Records the change in ${words(bare(x[1]))}: sets ${listWords(sets)}${x[3] ? ` where ${cnd(x[3])}` : ''}`, code, line };
253
- }
254
- if ((x = t.match(/^DELETE\s+FROM\s+([\w."]+)(?:\s+WHERE\s+(.*))?$/i))) return { kind: 'call', says: `Removes ${words(bare(x[1]))}${x[2] ? ` where ${cnd(x[2])}` : ''}`, code, line };
255
- if ((x = t.match(/^SELECT\s+(.*?)\s+INTO\s+(?:STRICT\s+)?([\w,\s]+?)\s+FROM\s+(.*)$/i))) {
256
- const from = x[3].match(/^([\w."]+)(?:\s+(?:AS\s+)?\w+)?(?:\s+WHERE\s+(.*))?$/i);
257
- const what = listWords(x[2].split(',').map((n) => v(n.trim())));
258
- if (from) return { kind: 'call', callee: 'find', says: `Finds ${what} in the ${words(bare(from[1]))}${from[2] ? ` where ${cnd(from[2])}` : ''}`, code, line };
259
- const found = selectSteps(`SELECT ${x[1]} FROM ${x[3]}`, line, { give: false, vars: true });
260
- return { kind: 'call', callee: 'find', says: `Finds ${what}: ${found.map((f) => f.says.charAt(0).toLowerCase() + f.says.slice(1)).join(', ')}`, code, line };
261
- }
262
- if ((x = t.match(/^(?:PERFORM|CALL|EXEC(?:UTE)?)\s+([\w.]+)\s*\(/i))) return { kind: 'call', says: `Runs ${words(bare(x[1]))}`, code, line };
263
- if ((x = t.match(/^(?:SET\s+)?@?([\w.]+)\s*:?=\s*(.+)$/i))) return { kind: 'set', says: `Sets ${v(bare(x[1]))} to ${/^'.*'$/.test(x[2].trim()) ? `"${x[2].trim().slice(1, -1)}"` : cnd(x[2])}`, code, line };
264
- return { kind: 'other', says: code, code, line, restates: code };
281
+ /** The offset where a (1-based) line starts. */
282
+ function srcIndexOfLine(src, line) {
283
+ let at = 0;
284
+ for (let k = 1; k < line && at >= 0; k++) at = src.indexOf('\n', at) + 1;
285
+ return Math.max(0, at);
265
286
  }
266
287
 
267
288
  /**
268
- * The steps of a procedural body (PL/pgSQL and friends): IF/ELSIF/ELSE/END IF become branches with their other
269
- * side, everything else one step per statement.
289
+ * Why a .sql file is not read, when it is a template (dbt, Jinja): its SQL is only known once the template is filled
290
+ * in, so reading it would be a guess. Null for plain SQL.
270
291
  */
271
- function procSteps(body, firstLine) {
272
- const m = mask(body);
273
- const stmts = [];
274
- let start = 0;
275
- // Split at semicolons and around THEN/ELSE/ELSIF/END IF/LOOP keywords so IF headers stand alone.
276
- const re = /;|\bTHEN\b|\bELSE\b(?!\s*IF)|\bELSIF\b|\bELSEIF\b|\bEND\s+IF\b|\bBEGIN\b|\bEND\b(?!\s+IF)/gi;
277
- const lineAt = lineFinder(body);
278
- let r;
279
- while ((r = re.exec(m))) {
280
- const kw = r[0].toUpperCase().replace(/\s+/g, ' ');
281
- if (kw === ';') { const text = body.slice(start, r.index).trim(); if (text) stmts.push({ text, line: firstLine + lineAt(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1 }); start = r.index + 1; continue; }
282
- if (kw === 'THEN') { stmts.push({ text: body.slice(start, r.index).trim(), line: firstLine + lineAt(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1, then: true }); start = r.index + r[0].length; continue; }
283
- const before = body.slice(start, r.index).trim();
284
- if (before) stmts.push({ text: before, line: firstLine + lineAt(start) - 1 });
285
- stmts.push({ keyword: kw === 'ELSEIF' ? 'ELSIF' : kw });
286
- start = r.index + r[0].length;
287
- }
288
- const tail = body.slice(start).trim();
289
- if (tail) stmts.push({ text: tail, line: firstLine + lineAt(start) - 1 });
290
- let i = 0;
291
- const block = (stop) => {
292
- const out = [];
293
- while (i < stmts.length) {
294
- const s = stmts[i];
295
- if (s.keyword && stop.includes(s.keyword)) return out;
296
- i++;
297
- if (s.keyword === 'BEGIN' || s.keyword === 'END') continue;
298
- if (s.then && /^(IF|ELSIF)\b/i.test(s.text)) {
299
- const cond = s.text.replace(/^(IF|ELSIF)\s+/i, '');
300
- const step = { kind: 'branch', says: `If ${sqlCondition(cond, { vars: true })}`, code: s.text, line: s.line, children: block(['ELSIF', 'ELSE', 'END IF']) };
301
- let tail = step;
302
- while (stmts[i]?.keyword === 'ELSIF') {
303
- i++;
304
- const h = stmts[i++];
305
- const next = { kind: 'branch', says: `If ${sqlCondition(h.text.replace(/^ELSIF\s+/i, ''), { vars: true })}`, code: h.text, line: h.line, children: block(['ELSIF', 'ELSE', 'END IF']) };
306
- tail.otherwise = [next]; tail = next;
307
- }
308
- if (stmts[i]?.keyword === 'ELSE') { i++; tail.otherwise = block(['END IF']); }
309
- if (stmts[i]?.keyword === 'END IF') i++;
310
- out.push(step);
311
- continue;
312
- }
313
- if (s.text && !/^(DECLARE|LANGUAGE|AS)\b/i.test(s.text) && !/^\w+\s+[\w(),]+(\s*:=.*)?$/.test(s.text) || /:=/.test(s.text ?? '')) {
314
- if (s.text && !/^DECLARE\b/i.test(s.text)) out.push(bodyStatement(s.text.replace(/^DECLARE\s+/i, ''), s.line));
315
- }
316
- }
317
- return out;
318
- };
319
- return block([]);
292
+ export function sqlTemplateReason(src) {
293
+ const m = mask(src);
294
+ if (/\{\{[\s\S]{0,400}?\}\}|\{%-?[\s\S]{0,400}?-?%\}/.test(m)) return 'A dbt or Jinja template ({{ … }} / {% … %}): its SQL is only known once the template is filled in, so it is not read, never guessed.';
295
+ return null;
320
296
  }
321
297
 
322
298
  /** Functions, procedures, views, triggers, and CHECK/UNIQUE rules as reading items (kind 'function'). */
@@ -329,37 +305,26 @@ export function sqlItems(src) {
329
305
  items.push({ id: `${name}:${line}`, name, label: words(name).charAt(0).toUpperCase() + words(name).slice(1), line, inputs: extra.inputs ?? [], returns: extra.returns ?? null,
330
306
  ...(extra.doc ? { doc: extra.doc } : {}), provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0,
331
307
  stepsReadable: steps.length ? Math.round(((steps.length - code) / steps.length) * 100) / 100 : 0,
332
- says: extra.says ?? `${words(name)} has ${steps.length} step${steps.length === 1 ? '' : 's'}.`, headline: extra.headline ?? `${words(name)}.`, guards: [], unread: [] });
308
+ says: extra.says ?? `${words(name)} has ${steps.length} step${steps.length === 1 ? '' : 's'}.`, headline: extra.headline ?? `${words(name)}.`, guards: [], unread: extra.unread ?? [],
309
+ // The member spans its whole definition, not only its first line.
310
+ ...(extra.endLine && extra.endLine > line ? { endLine: extra.endLine } : {}) });
333
311
  };
334
312
  // Views: the query, as steps.
335
313
  for (const v of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)(?:\s*\([^)]*\))?\s+AS\s+/gi)) {
336
314
  const end = m.indexOf(';', v.index);
337
315
  const query = src.slice(v.index + v[0].length, end < 0 ? src.length : end);
338
316
  const name = bare(v[1]);
339
- push(name, lineAt(v.index), selectSteps(query, lineAt(v.index + v[0].length)), { doc: docAbove(src, v.index), says: `${words(name)} is a saved query.`, headline: `${words(name)}: a saved query.` });
317
+ push(name, lineAt(v.index), selectSteps(query, lineAt(v.index + v[0].length)), { doc: docAbove(src, v.index), endLine: lineAt(end < 0 ? src.length : end), says: `${words(name)} is a saved query.`, headline: `${words(name)}: a saved query.` });
340
318
  }
341
- // Functions and procedures: their parameters and body.
342
- for (const f of m.matchAll(/\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:DEFINER\s*=\s*\S+\s+)?(FUNCTION|PROCEDURE|PROC)\s+([\w."[\]]+)\s*\(/gi)) {
343
- const open = f.index + f[0].length - 1;
344
- const close = parenEnd(m, open);
345
- if (close < 0) continue;
346
- const name = bare(f[2]);
347
- const inputs = splitTop(src.slice(open + 1, close)).map((p) => {
348
- const pm = p.text.trim().match(/^(?:IN\s+|OUT\s+|INOUT\s+)?@?([\w"]+)\s+(.+?)(?:\s+(?:DEFAULT|=)\s+.+)?$/i);
349
- return pm ? { name: unquote(pm[1]).replace(/^p_|^_/, ''), type: pm[2].trim() } : null;
350
- }).filter(Boolean);
351
- const after = src.slice(close + 1);
352
- const ret = after.match(/^\s*RETURNS\s+(TABLE\s*\([^)]*\)|SETOF\s+[\w.]+|[\w.]+(?:\[\])?)/i);
353
- const dollar = after.match(/\$(\w*)\$([\s\S]*?)\$\1\$/);
354
- const beginAt = mask(after).search(/\bBEGIN\b/i);
355
- const bodyText = dollar ? dollar[2] : beginAt >= 0 ? after.slice(beginAt) : '';
356
- const bodyStart = close + 1 + (dollar ? dollar.index + dollar[0].indexOf(dollar[2]) : Math.max(beginAt, 0));
357
- const isTrigger = ret && /^trigger$/i.test(ret[1]);
358
- const steps = procSteps(bodyText, lineAt(bodyStart));
359
- const returns = ret && !isTrigger ? (typeWords(ret[1]) ?? (/^(SETOF|TABLE)\b/i.test(ret[1]) ? 'rows' : words(ret[1]))) : null;
360
- push(name, lineAt(f.index), steps, { inputs, returns, doc: docAbove(src, f.index),
361
- says: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}${returns ? ` and returns ${returns}` : ''}.`,
362
- headline: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}.` });
319
+ // Functions and procedures: their inputs and their body, read block by block (sql-proc.mjs).
320
+ for (const r of sqlRoutines(src, lineAt)) {
321
+ const inputs = r.inputs.map(({ name, type }) => ({ name, type }));
322
+ const returns = r.returns ?? (r.outs.length ? listWords(r.outs.map((o) => words(o.name))) : null);
323
+ const steps = r.unreadWhy ? [] : r.steps;
324
+ push(r.name, r.line, steps, { inputs, returns, doc: docAbove(src, srcIndexOfLine(src, r.line)), endLine: r.endLine,
325
+ ...(r.unreadWhy ? { unread: [{ line: r.line, text: src.split('\n')[r.line - 1].trim().slice(0, 120), reason: `Not read: ${r.unreadWhy}. Its code is shown instead.` }] } : {}),
326
+ says: `${words(r.name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}${returns ? ` and returns ${returns}` : ''}.`,
327
+ headline: `${words(r.name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}.` });
363
328
  }
364
329
  // Triggers: when the database runs a function by itself.
365
330
  for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+([\w."]+)\s+(BEFORE|AFTER|INSTEAD\s+OF)\s+([\w\s,]+?)\s+ON\s+([\w."]+)[\s\S]*?EXECUTE\s+(?:FUNCTION|PROCEDURE)\s+([\w.]+)/gi)) {
@@ -386,3 +351,6 @@ export function sqlItems(src) {
386
351
  items.sort((a, b) => a.line - b.line);
387
352
  return items;
388
353
  }
354
+
355
+ // Shared with the routine reader (sql-proc.mjs).
356
+ export { words as sqlWords, bare as sqlBare, singular as sqlSingular, typeWords as sqlTypeWords, listWords as sqlListWords };