@skillstech/thunderlang 1.0.4 → 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.
- package/CHANGELOG.md +140 -0
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +1963 -315
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
// Thunder Core parser: lines of tokens -> a syntax tree with a line number on every node.
|
|
2
|
+
//
|
|
3
|
+
// Two passes, both deterministic:
|
|
4
|
+
// 1. Collect every name the program declares (Set/Keep targets, Receive inputs, For each items, functions,
|
|
5
|
+
// records and their fields, Use aliases). Names may be several words ("tax rate"), so expressions need
|
|
6
|
+
// this list to know where one name ends.
|
|
7
|
+
// 2. Parse each statement. In an expression, a run of words is matched against the known names, longest first.
|
|
8
|
+
//
|
|
9
|
+
// The grammar is in docs/core.md. Nothing here guesses: a line that does not fit the grammar
|
|
10
|
+
// gets a diagnostic with a code, never a best-effort reading.
|
|
11
|
+
|
|
12
|
+
import { lex } from './lexer.mjs';
|
|
13
|
+
import { diag, CoreError, closest } from './diagnostics.mjs';
|
|
14
|
+
|
|
15
|
+
// Words that belong to Thunder and cannot be part of a name.
|
|
16
|
+
export const RESERVED = new Set(['is', 'are', 'and', 'or', 'not', 'to', 'at', 'of', 'with', 'from', 'where', 'by', 'in', 'as',
|
|
17
|
+
'than', 'the', 'a', 'an', 'plus', 'minus', 'times', 'divided', 'mod', 'true', 'false', 'yes', 'no', 'nothing', 'otherwise',
|
|
18
|
+
'sorted', 'descending', 'ascending', 'equals', 'contains', 'between', 'yes/no', 'joined', 'split', 'replacing', 'starts', 'ends']);
|
|
19
|
+
|
|
20
|
+
// Built-in operations written "the <op> of <value>".
|
|
21
|
+
export const OPS = {
|
|
22
|
+
sum: 'sum', total: 'sum', average: 'average', mean: 'average', count: 'count', number: 'count',
|
|
23
|
+
min: 'min', minimum: 'min', smallest: 'min', lowest: 'min', max: 'max', maximum: 'max', largest: 'max', highest: 'max',
|
|
24
|
+
length: 'length', words: 'words', lines: 'lines', lowercase: 'lowercase', uppercase: 'uppercase', trimmed: 'trimmed',
|
|
25
|
+
keys: 'keys', values: 'values', first: 'first', last: 'last', parts: 'parts',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const STATEMENT_WORDS = ['say', 'print', 'set', 'keep', 'give', 'stop', 'when', 'if', 'otherwise', 'for each', 'repeat',
|
|
29
|
+
'to', 'receive', 'a … has', 'expect', 'never allow', 'use', 'test', 'add', 'remove', 'increase', 'decrease', 'sort', 'reverse'];
|
|
30
|
+
export const LIST_ACTIONS = ['sort', 'reverse', 'add', 'remove'];
|
|
31
|
+
|
|
32
|
+
const keyOf = (words) => words.map((w) => w.lower).join(' ');
|
|
33
|
+
const isWord = (t, w) => t && t.t === 'word' && (w === undefined || t.lower === w);
|
|
34
|
+
const isSym = (t, s) => t && t.t === 'sym' && t.text === s;
|
|
35
|
+
|
|
36
|
+
// ---------------------------------------------------------------- blocks
|
|
37
|
+
|
|
38
|
+
// A condition may continue on the next line: a more-indented line that starts with "and" or "or" belongs to
|
|
39
|
+
// the line above (when that line has not opened a block with ":"). No statement starts with "and" or "or",
|
|
40
|
+
// so this never changes what another line means.
|
|
41
|
+
// When member is yes
|
|
42
|
+
// and total is at least 100:
|
|
43
|
+
function joinContinuations(lines) {
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const l of lines) {
|
|
46
|
+
const prev = out[out.length - 1];
|
|
47
|
+
const startsJoin = isWord(l.tokens[0], 'and') || isWord(l.tokens[0], 'or');
|
|
48
|
+
if (prev && startsJoin && l.indent > prev.indent && !isSym(prev.tokens[prev.tokens.length - 1], ':')) {
|
|
49
|
+
out[out.length - 1] = { ...prev, tokens: [...prev.tokens, ...l.tokens], raw: `${prev.raw} ${l.raw.trim()}` };
|
|
50
|
+
} else out.push(l);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildBlocks(lines, diagnostics) {
|
|
56
|
+
lines = joinContinuations(lines);
|
|
57
|
+
let i = 0;
|
|
58
|
+
const endsColon = (l) => isSym(l.tokens[l.tokens.length - 1], ':');
|
|
59
|
+
function block(indent) {
|
|
60
|
+
const out = [];
|
|
61
|
+
while (i < lines.length) {
|
|
62
|
+
const l = lines[i];
|
|
63
|
+
if (l.indent < indent) break;
|
|
64
|
+
if (l.indent > indent) {
|
|
65
|
+
diagnostics.push(out.length && endsColon(out[out.length - 1])
|
|
66
|
+
? diag('TC104', l.line, 'This line is indented differently from the lines above it.', 'Use the same number of spaces for every line in a block (two per level).')
|
|
67
|
+
: diag('TC102', l.line, 'This line is indented, but the line above does not end with ":", so nothing opens a block here.', 'Remove the extra spaces, or end the line above with ":".'));
|
|
68
|
+
i++; continue;
|
|
69
|
+
}
|
|
70
|
+
const node = { line: l.line, tokens: l.tokens, raw: l.raw, children: [] };
|
|
71
|
+
i++;
|
|
72
|
+
if (endsColon(l)) {
|
|
73
|
+
if (i < lines.length && lines[i].indent > indent) node.children = block(lines[i].indent);
|
|
74
|
+
else diagnostics.push(diag('TC103', l.line, `"${l.raw}" ends with ":", so the lines under it should be indented.`, 'Indent the lines that belong to it by two spaces.'));
|
|
75
|
+
}
|
|
76
|
+
out.push(node);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
return block(lines.length ? lines[0].indent : 0);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------- pass 1: names
|
|
84
|
+
|
|
85
|
+
function splitTop(tokens, pred) {
|
|
86
|
+
let depth = 0;
|
|
87
|
+
for (let k = 0; k < tokens.length; k++) {
|
|
88
|
+
const t = tokens[k];
|
|
89
|
+
if (isSym(t, '(') || isSym(t, '[')) depth++;
|
|
90
|
+
else if (isSym(t, ')') || isSym(t, ']')) depth--;
|
|
91
|
+
else if (depth === 0 && pred(t, k)) return k;
|
|
92
|
+
}
|
|
93
|
+
return -1;
|
|
94
|
+
}
|
|
95
|
+
function lastTop(tokens, pred) {
|
|
96
|
+
let depth = 0, found = -1;
|
|
97
|
+
for (let k = 0; k < tokens.length; k++) {
|
|
98
|
+
const t = tokens[k];
|
|
99
|
+
if (isSym(t, '(') || isSym(t, '[')) depth++;
|
|
100
|
+
else if (isSym(t, ')') || isSym(t, ']')) depth--;
|
|
101
|
+
else if (depth === 0 && pred(t, k)) found = k;
|
|
102
|
+
}
|
|
103
|
+
return found;
|
|
104
|
+
}
|
|
105
|
+
const allWords = (ts) => ts.length > 0 && ts.every((t) => t.t === 'word');
|
|
106
|
+
const stripArticle = (ts) => (isWord(ts[0], 'the') || isWord(ts[0], 'a') || isWord(ts[0], 'an') ? ts.slice(1) : ts);
|
|
107
|
+
const noColon = (ts) => (isSym(ts[ts.length - 1], ':') ? ts.slice(0, -1) : ts);
|
|
108
|
+
|
|
109
|
+
function collectNames(nodes, names) {
|
|
110
|
+
const add = (kind, words) => {
|
|
111
|
+
if (!words.length) return;
|
|
112
|
+
if (kind === 'record') { names.records.add(keyOf(words)); return; }
|
|
113
|
+
const cur = names.known.get(keyOf(words));
|
|
114
|
+
if (!cur || cur === 'var') names.known.set(keyOf(words), kind);
|
|
115
|
+
};
|
|
116
|
+
for (const n of nodes) {
|
|
117
|
+
const ts = n.tokens;
|
|
118
|
+
const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
|
|
119
|
+
if (w0 === 'set') {
|
|
120
|
+
const k = splitTop(ts, (t) => isWord(t, 'to'));
|
|
121
|
+
const target = stripArticle(ts.slice(1, k < 0 ? ts.length : k));
|
|
122
|
+
if (allWords(target) && !target.some((t) => RESERVED.has(t.lower)) && !names.known.has(keyOf(target))) add('var', target);
|
|
123
|
+
} else if (w0 === 'keep') {
|
|
124
|
+
const k = splitTop(ts, (t) => isWord(t, 'at'));
|
|
125
|
+
add('const', stripArticle(ts.slice(1, k < 0 ? ts.length : k)));
|
|
126
|
+
} else if (w0 === 'receive') {
|
|
127
|
+
for (const p of paramGroups(ts.slice(1))) add('var', p.words);
|
|
128
|
+
} else if (w0 === 'for' && isWord(ts[1], 'each')) {
|
|
129
|
+
const k = splitTop(ts, (t) => isWord(t, 'in') || isWord(t, 'from'));
|
|
130
|
+
const head = ts.slice(2, k < 0 ? ts.length : k);
|
|
131
|
+
const andAt = head.findIndex((t) => isWord(t, 'and'));
|
|
132
|
+
if (andAt >= 0) { add('var', head.slice(0, andAt)); add('var', head.slice(andAt + 1)); } else add('var', head);
|
|
133
|
+
} else if (w0 === 'to' && isSym(ts[ts.length - 1], ':')) {
|
|
134
|
+
add('func', ts.slice(1, -1));
|
|
135
|
+
} else if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has')) {
|
|
136
|
+
const words = ts.slice(1, -2);
|
|
137
|
+
add('record', words);
|
|
138
|
+
for (const c of n.children) {
|
|
139
|
+
const k = c.tokens.findIndex((t) => isWord(t, 'is'));
|
|
140
|
+
if (k > 0 && !isWord(c.tokens[0], 'never')) names.fields.add(keyOf(c.tokens.slice(0, k)));
|
|
141
|
+
}
|
|
142
|
+
} else if (w0 === 'use') {
|
|
143
|
+
const k = ts.findIndex((t) => isWord(t, 'as'));
|
|
144
|
+
if (k > 0) add('module', ts.slice(k + 1)); else if (ts[1]?.t === 'word') add('module', [ts[1]]);
|
|
145
|
+
} else if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
|
|
146
|
+
add('var', [{ lower: 'error' }]);
|
|
147
|
+
}
|
|
148
|
+
collectNames(n.children, names);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// "total and member", "total as money, member as yes/no", "price and rate (7% if not given)"
|
|
153
|
+
function paramGroups(ts) {
|
|
154
|
+
const groups = [];
|
|
155
|
+
let cur = [];
|
|
156
|
+
let depth = 0;
|
|
157
|
+
for (const t of ts) {
|
|
158
|
+
if (isSym(t, '(')) depth++;
|
|
159
|
+
if (isSym(t, ')')) depth--;
|
|
160
|
+
if (depth === 0 && (isSym(t, ',') || isWord(t, 'and'))) { if (cur.length) groups.push(cur); cur = []; } else cur.push(t);
|
|
161
|
+
}
|
|
162
|
+
if (cur.length) groups.push(cur);
|
|
163
|
+
return groups.map((g) => {
|
|
164
|
+
// A default: "(<value> if not given)" at the end of the input.
|
|
165
|
+
let defaultTokens = null;
|
|
166
|
+
if (isSym(g[g.length - 1], ')')) {
|
|
167
|
+
let d = 0, open = -1;
|
|
168
|
+
for (let i = g.length - 1; i >= 0; i--) { if (isSym(g[i], ')')) d++; if (isSym(g[i], '(')) { d--; if (d === 0) { open = i; break; } } }
|
|
169
|
+
const inner = open >= 0 ? g.slice(open + 1, -1) : [];
|
|
170
|
+
const n = inner.length;
|
|
171
|
+
if (n > 3 && isWord(inner[n - 3], 'if') && isWord(inner[n - 2], 'not') && isWord(inner[n - 1], 'given')) { defaultTokens = inner.slice(0, -3); g = g.slice(0, open); }
|
|
172
|
+
}
|
|
173
|
+
const k = g.findIndex((t) => isWord(t, 'as'));
|
|
174
|
+
return { words: stripArticle(k < 0 ? g : g.slice(0, k)), typeTokens: k < 0 ? null : g.slice(k + 1), defaultTokens };
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---------------------------------------------------------------- expressions
|
|
179
|
+
|
|
180
|
+
class Stream {
|
|
181
|
+
constructor(tokens, line) { this.ts = tokens; this.i = 0; this.line = line; }
|
|
182
|
+
peek(k = 0) { return this.ts[this.i + k]; }
|
|
183
|
+
next() { return this.ts[this.i++]; }
|
|
184
|
+
done() { return this.i >= this.ts.length; }
|
|
185
|
+
word(w) { if (isWord(this.peek(), w)) { this.i++; return true; } return false; }
|
|
186
|
+
words(...ws) { if (ws.every((w, k) => isWord(this.peek(k), w))) { this.i += ws.length; return true; } return false; }
|
|
187
|
+
sym(s) { if (isSym(this.peek(), s)) { this.i++; return true; } return false; }
|
|
188
|
+
fail(msg, hint, code = 'TC105') { throw new CoreError(diag(code, this.line, msg, hint)); }
|
|
189
|
+
expectSym(s, what) { if (!this.sym(s)) this.fail(`I expected "${s}" ${what}${this.peek() ? `, but found "${show(this.peek())}"` : ''}.`, null, 'TC108'); }
|
|
190
|
+
}
|
|
191
|
+
export const show = (t) => (t.t === 'word' ? t.text : t.t === 'sym' ? t.text : t.t === 'num' ? t.text : t.t === 'money' ? `$${t.text}` : t.t === 'percent' ? `${t.text}%` : t.t === 'poss' ? "'s" : '"…"');
|
|
192
|
+
|
|
193
|
+
export class ExprParser {
|
|
194
|
+
constructor(names) { this.names = names; }
|
|
195
|
+
|
|
196
|
+
parse(tokens, line, opts = {}) {
|
|
197
|
+
const s = new Stream(tokens, line);
|
|
198
|
+
if (s.done()) s.fail('A value is missing here.', null, 'TC108');
|
|
199
|
+
const e = this.expr(s, opts);
|
|
200
|
+
if (!s.done()) s.fail(`I understood the line up to "${show(s.peek())}", but not from there on.`, opts.extraHint ?? 'Check the spelling, or put parentheses around a part to group it.', 'TC112');
|
|
201
|
+
return e;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
expr(s, o = {}) { return this.or(s, o); }
|
|
205
|
+
or(s, o) {
|
|
206
|
+
let l = this.and(s, o);
|
|
207
|
+
while (isWord(s.peek(), 'or')) { s.next(); l = { k: 'bin', op: 'or', l, r: this.and(s, o), line: s.line }; }
|
|
208
|
+
return l;
|
|
209
|
+
}
|
|
210
|
+
and(s, o) {
|
|
211
|
+
let l = this.not(s, o);
|
|
212
|
+
while (!o.noAnd && isWord(s.peek(), 'and')) { s.next(); l = { k: 'bin', op: 'and', l, r: this.not(s, o), line: s.line }; }
|
|
213
|
+
return l;
|
|
214
|
+
}
|
|
215
|
+
not(s, o) {
|
|
216
|
+
if (s.word('not')) return { k: 'not', e: this.not(s, o), line: s.line };
|
|
217
|
+
return this.cmp(s, o);
|
|
218
|
+
}
|
|
219
|
+
cmp(s, o) {
|
|
220
|
+
const l = this.add(s, o);
|
|
221
|
+
const t = s.peek();
|
|
222
|
+
const line = s.line;
|
|
223
|
+
if (t?.t === 'sym' && ['=', '==', '!=', '<', '<=', '>', '>='].includes(t.text)) {
|
|
224
|
+
s.next();
|
|
225
|
+
const op = { '=': '==', '==': '==' }[t.text] ?? t.text;
|
|
226
|
+
return { k: 'cmp', op, l, r: this.add(s, o), line };
|
|
227
|
+
}
|
|
228
|
+
if (s.word('equals')) return { k: 'cmp', op: '==', l, r: this.add(s, o), line };
|
|
229
|
+
if (s.word('contains')) return { k: 'contains', l, r: this.add(s, o), line };
|
|
230
|
+
if (s.words('starts', 'with')) return { k: 'affix', end: false, l, r: this.add(s, o), line };
|
|
231
|
+
if (s.words('ends', 'with')) return { k: 'affix', end: true, l, r: this.add(s, o), line };
|
|
232
|
+
if (s.words('does', 'not', 'contain')) return { k: 'not', e: { k: 'contains', l, r: this.add(s, o), line }, line };
|
|
233
|
+
if (isWord(t, 'is') || isWord(t, 'are')) {
|
|
234
|
+
s.next();
|
|
235
|
+
const neg = s.word('not');
|
|
236
|
+
const wrap = (e) => (neg ? { k: 'not', e, line } : e);
|
|
237
|
+
const rel = [[['at', 'least'], '>='], [['at', 'most'], '<='], [['more', 'than'], '>'], [['greater', 'than'], '>'], [['less', 'than'], '<'],
|
|
238
|
+
[['fewer', 'than'], '<'], [['above'], '>'], [['below'], '<'], [['equal', 'to'], '==']];
|
|
239
|
+
for (const [ws, op] of rel) if (s.words(...ws)) return wrap({ k: 'cmp', op, l, r: this.add(s, o), line });
|
|
240
|
+
if (s.word('nothing')) return { k: 'isNothing', e: l, neg, line };
|
|
241
|
+
for (const adj of ['empty', 'positive', 'negative', 'zero']) {
|
|
242
|
+
if (isWord(s.peek(), adj) && (s.i + 1 >= s.ts.length || !(s.ts[s.i + 1].t === 'word' && !RESERVED.has(s.ts[s.i + 1].lower)))) { s.next(); return wrap({ k: 'adj', adj, e: l, line }); }
|
|
243
|
+
}
|
|
244
|
+
if (s.word('between')) {
|
|
245
|
+
const lo = this.add(s, o);
|
|
246
|
+
if (!s.word('and')) s.fail('"is between" needs "and": is between 1 and 10.', null, 'TC108');
|
|
247
|
+
const hi = this.add(s, o);
|
|
248
|
+
return wrap({ k: 'between', e: l, lo, hi, line });
|
|
249
|
+
}
|
|
250
|
+
if (s.word('in')) return wrap({ k: 'contains', l: this.add(s, o), r: l, line });
|
|
251
|
+
if (s.done()) s.fail('Something is missing after "is".', 'For example: is 10, is at least 18, is nothing, is empty.', 'TC108');
|
|
252
|
+
return { k: 'cmp', op: neg ? '!=' : '==', l, r: this.add(s, o), line };
|
|
253
|
+
}
|
|
254
|
+
return l;
|
|
255
|
+
}
|
|
256
|
+
add(s, o) {
|
|
257
|
+
let l = this.mul(s, o);
|
|
258
|
+
for (;;) {
|
|
259
|
+
const t = s.peek();
|
|
260
|
+
if (isSym(t, '+') || isWord(t, 'plus')) { s.next(); l = { k: 'bin', op: '+', l, r: this.mul(s, o), line: s.line }; }
|
|
261
|
+
else if (isSym(t, '-') || isWord(t, 'minus')) { s.next(); l = { k: 'bin', op: '-', l, r: this.mul(s, o), line: s.line }; }
|
|
262
|
+
else return l;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
mul(s, o) {
|
|
266
|
+
let l = this.unary(s, o);
|
|
267
|
+
for (;;) {
|
|
268
|
+
const t = s.peek();
|
|
269
|
+
if (isSym(t, '*') || isWord(t, 'times')) { s.next(); l = { k: 'bin', op: '*', l, r: this.unary(s, o), line: s.line }; }
|
|
270
|
+
else if (isSym(t, '/')) { s.next(); l = { k: 'bin', op: '/', l, r: this.unary(s, o), line: s.line }; }
|
|
271
|
+
else if (isWord(t, 'divided') && isWord(s.peek(1), 'by')) { s.i += 2; l = { k: 'bin', op: '/', l, r: this.unary(s, o), line: s.line }; }
|
|
272
|
+
else if (isWord(t, 'mod')) { s.next(); l = { k: 'bin', op: 'mod', l, r: this.unary(s, o), line: s.line }; }
|
|
273
|
+
else return l;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
unary(s, o) {
|
|
277
|
+
if (s.sym('-')) return { k: 'neg', e: this.unary(s, o), line: s.line };
|
|
278
|
+
return this.postfix(s, o);
|
|
279
|
+
}
|
|
280
|
+
postfix(s, o) {
|
|
281
|
+
let e = this.primary(s, o);
|
|
282
|
+
for (;;) {
|
|
283
|
+
const t = s.peek();
|
|
284
|
+
if (t?.t === 'poss') {
|
|
285
|
+
s.next();
|
|
286
|
+
const run = this.wordRun(s);
|
|
287
|
+
if (!run.length) s.fail(`I expected a field name after "'s".`, null, 'TC108');
|
|
288
|
+
const k = this.longest(run, (key) => this.names.fields.has(key)) || run.length;
|
|
289
|
+
s.i -= run.length - k;
|
|
290
|
+
e = { k: 'field', obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(' '), line: s.line };
|
|
291
|
+
} else if (isWord(t, 'at') && !isWord(s.peek(1), 'least') && !isWord(s.peek(1), 'most')) {
|
|
292
|
+
s.next();
|
|
293
|
+
const key = this.unary(s, { ...o, noAnd: true });
|
|
294
|
+
let dflt = null;
|
|
295
|
+
if (s.word('otherwise')) dflt = this.unary(s, { ...o, noAnd: true });
|
|
296
|
+
e = { k: 'at', obj: e, key, dflt, line: s.line };
|
|
297
|
+
} else if (isWord(t, 'as')) {
|
|
298
|
+
s.next();
|
|
299
|
+
e = { k: 'conv', e, type: this.typeRef(s), line: s.line };
|
|
300
|
+
} else if (isWord(t, 'where')) {
|
|
301
|
+
s.next();
|
|
302
|
+
e = { k: 'where', list: e, cond: this.or(s, { ...o, stopSorted: true }), line: s.line };
|
|
303
|
+
} else if (isWord(t, 'sorted') && isWord(s.peek(1), 'by')) {
|
|
304
|
+
s.i += 2;
|
|
305
|
+
const run = this.wordRun(s);
|
|
306
|
+
if (!run.length) s.fail('"sorted by" needs a field: sorted by date.', null, 'TC108');
|
|
307
|
+
const desc = s.word('descending') ? true : (s.word('ascending'), false);
|
|
308
|
+
e = { k: 'sorted', list: e, by: keyOf(run), text: run.map((w) => w.text).join(' '), desc, line: s.line };
|
|
309
|
+
} else if (isWord(t, 'sorted')) {
|
|
310
|
+
// "xs sorted" / "xs sorted descending": the values themselves, smallest first.
|
|
311
|
+
s.next();
|
|
312
|
+
const desc = s.word('descending') ? true : (s.word('ascending'), false);
|
|
313
|
+
e = { k: 'sortedValues', list: e, desc, line: s.line };
|
|
314
|
+
} else if (isWord(t, 'joined') && isWord(s.peek(1), 'with')) {
|
|
315
|
+
s.i += 2;
|
|
316
|
+
e = { k: 'joined', list: e, sep: this.unary(s, { ...o, noAnd: true }), line: s.line };
|
|
317
|
+
} else if (isWord(t, 'split') && isWord(s.peek(1), 'at')) {
|
|
318
|
+
s.i += 2;
|
|
319
|
+
e = { k: 'splitAt', text: e, sep: this.unary(s, { ...o, noAnd: true }), line: s.line };
|
|
320
|
+
} else if (isWord(t, 'replacing')) {
|
|
321
|
+
s.next();
|
|
322
|
+
const from = this.unary(s, { ...o, noAnd: true });
|
|
323
|
+
if (!s.word('with')) s.fail('"replacing" needs "with": name replacing "-" with " ".', null, 'TC108');
|
|
324
|
+
e = { k: 'replacing', text: e, from, to: this.unary(s, { ...o, noAnd: true }), line: s.line };
|
|
325
|
+
} else if (isSym(t, '.') && s.peek(1)?.t === 'word') {
|
|
326
|
+
s.next();
|
|
327
|
+
const attr = s.next().text;
|
|
328
|
+
let args = null;
|
|
329
|
+
if (isSym(s.peek(), '(')) args = this.parenArgs(s);
|
|
330
|
+
e = { k: 'dot', obj: e, attr, args, line: s.line };
|
|
331
|
+
} else return e;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// words that may form a name (stops at reserved words and non-words)
|
|
336
|
+
wordRun(s) {
|
|
337
|
+
const run = [];
|
|
338
|
+
while (s.peek()?.t === 'word' && !RESERVED.has(s.peek().lower)) run.push(s.next());
|
|
339
|
+
return run;
|
|
340
|
+
}
|
|
341
|
+
// Does a known field name start k tokens ahead? (So "," inside a list is not read as "and the next field".)
|
|
342
|
+
fieldAhead(s, k) {
|
|
343
|
+
const run = [];
|
|
344
|
+
for (let j = s.i + k; s.ts[j]?.t === 'word' && !RESERVED.has(s.ts[j].lower); j++) run.push(s.ts[j]);
|
|
345
|
+
return this.longest(run, (key) => this.names.fields.has(key)) > 0;
|
|
346
|
+
}
|
|
347
|
+
longest(run, ok) {
|
|
348
|
+
for (let k = run.length; k > 0; k--) if (ok(keyOf(run.slice(0, k)))) return k;
|
|
349
|
+
return 0;
|
|
350
|
+
}
|
|
351
|
+
parenArgs(s) {
|
|
352
|
+
s.expectSym('(', 'to start the values');
|
|
353
|
+
const args = [];
|
|
354
|
+
if (s.sym(')')) return args;
|
|
355
|
+
for (;;) {
|
|
356
|
+
args.push(this.expr(s, {}));
|
|
357
|
+
if (s.sym(')')) return args;
|
|
358
|
+
s.expectSym(',', 'between values');
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
withArgs(s) {
|
|
362
|
+
const args = [this.expr(s, { noAnd: true })];
|
|
363
|
+
while (s.sym(',') || s.word('and')) args.push(this.expr(s, { noAnd: true }));
|
|
364
|
+
return args;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
typeRef(s) {
|
|
368
|
+
s.word('a'); s.word('an');
|
|
369
|
+
const t = s.next();
|
|
370
|
+
if (!t || t.t !== 'word') s.fail('A kind of value is missing (number, whole number, text, yes/no, money, date, list, map, or a record name).', null, 'TC306');
|
|
371
|
+
const w = t.lower;
|
|
372
|
+
if (w === 'optional') return { k: 'optional', of: this.typeRef(s) };
|
|
373
|
+
if (w === 'whole' && s.word('number')) return { k: 'whole' };
|
|
374
|
+
if (w === 'yes' && s.word('or') && s.word('no')) return { k: 'bool' };
|
|
375
|
+
if (w === 'list') { if (s.word('of')) return { k: 'list', of: this.typeRef(s) }; return { k: 'list', of: { k: 'unknown' } }; }
|
|
376
|
+
if (w === 'map') { if (s.word('of')) { const key = this.typeRef(s); if (!s.word('to')) s.fail('"map of" needs "to": map of text to number.', null, 'TC306'); return { k: 'map', key, of: this.typeRef(s) }; } return { k: 'map', key: { k: 'unknown' }, of: { k: 'unknown' } }; }
|
|
377
|
+
const simple = { number: 'number', numbers: 'number', text: 'text', texts: 'text', 'yes/no': 'bool', money: 'money', date: 'date', integer: 'whole' }[w];
|
|
378
|
+
if (simple) return { k: simple };
|
|
379
|
+
const run = [t, ...this.wordRun(s)];
|
|
380
|
+
const k = this.longest(run, (key) => this.names.records.has(key)) || this.longest(run, (key) => this.names.records.has(key.replace(/s$/, '')));
|
|
381
|
+
if (!k) s.fail(`I don't know the kind of value "${run.map((x) => x.text).join(' ')}".`, 'Kinds: number, whole number, text, yes/no, money, date, list of …, map of … to …, optional …, or a record you defined with "A … has:".', 'TC306');
|
|
382
|
+
s.i -= run.length - k;
|
|
383
|
+
const key = keyOf(run.slice(0, k));
|
|
384
|
+
return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, '') };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
primary(s, o) {
|
|
388
|
+
const t = s.peek();
|
|
389
|
+
const line = s.line;
|
|
390
|
+
if (!t) s.fail('A value is missing at the end of this line.', null, 'TC108');
|
|
391
|
+
if (t.t === 'num') { s.next(); return { k: 'num', text: t.text, whole: t.whole, line }; }
|
|
392
|
+
if (t.t === 'money') { s.next(); return { k: 'money', text: t.text, line }; }
|
|
393
|
+
if (t.t === 'percent') {
|
|
394
|
+
s.next();
|
|
395
|
+
const p = { k: 'percent', text: t.text, line };
|
|
396
|
+
if (s.word('of')) return { k: 'bin', op: '*', l: p, r: this.unary(s, o), line, percentOf: true };
|
|
397
|
+
return p;
|
|
398
|
+
}
|
|
399
|
+
if (t.t === 'str') {
|
|
400
|
+
s.next();
|
|
401
|
+
return { k: 'str', parts: t.parts.map((p) => (typeof p === 'string' ? p : { e: this.parse(p.tokens, line), source: p.source })), line };
|
|
402
|
+
}
|
|
403
|
+
if (isSym(t, '(')) { s.next(); const e = this.expr(s, {}); s.expectSym(')', 'to close the parenthesis'); return { k: 'paren', e, line }; }
|
|
404
|
+
if (isSym(t, '[')) {
|
|
405
|
+
s.next();
|
|
406
|
+
const items = [];
|
|
407
|
+
if (!s.sym(']')) for (;;) { items.push(this.expr(s, {})); if (s.sym(']')) break; s.expectSym(',', 'between list items'); }
|
|
408
|
+
return { k: 'list', items, line };
|
|
409
|
+
}
|
|
410
|
+
if (t.t !== 'word') s.fail(`I didn't expect "${show(t)}" here.`, null, 'TC105');
|
|
411
|
+
const w = t.lower;
|
|
412
|
+
if (w === 'true' || w === 'yes') { s.next(); return { k: 'bool', v: true, line }; }
|
|
413
|
+
if (w === 'false' || w === 'no') { s.next(); return { k: 'bool', v: false, line }; }
|
|
414
|
+
if (w === 'nothing') { s.next(); return { k: 'nothing', line }; }
|
|
415
|
+
if ((w === 'an' || w === 'a') && isWord(s.peek(1), 'empty') && (isWord(s.peek(2), 'list') || isWord(s.peek(2), 'map'))) {
|
|
416
|
+
s.i += 3;
|
|
417
|
+
const kind = s.ts[s.i - 1].lower === 'list' ? 'list' : 'map';
|
|
418
|
+
if (kind === 'list' && isWord(s.peek(), 'of')) { s.next(); return { k: 'list', items: [], of: this.typeRef(s), line }; }
|
|
419
|
+
return { k: kind, items: [], line };
|
|
420
|
+
}
|
|
421
|
+
if (w === 'the' || w === 'a' || w === 'an') { s.next(); return this.primary(s, { ...o, article: w !== 'the' }); }
|
|
422
|
+
// the absolute value of x, the JSON text of v, the JSON data in t
|
|
423
|
+
if (w === 'absolute' && isWord(s.peek(1), 'value') && isWord(s.peek(2), 'of')) { s.i += 3; return { k: 'op', op: 'abs', word: 'absolute value', arg: this.unary(s, o), line }; }
|
|
424
|
+
if (w === 'json' && isWord(s.peek(1), 'text') && isWord(s.peek(2), 'of')) { s.i += 3; return { k: 'op', op: 'jsonText', word: 'JSON text', arg: this.unary(s, o), line }; }
|
|
425
|
+
if (w === 'json' && isWord(s.peek(1), 'data') && isWord(s.peek(2), 'in')) { s.i += 3; return { k: 'op', op: 'jsonData', word: 'JSON data', arg: this.unary(s, o), line }; }
|
|
426
|
+
// the <op> of <value>
|
|
427
|
+
if (OPS[w] && isWord(s.peek(1), 'of')) {
|
|
428
|
+
s.i += 2;
|
|
429
|
+
return { k: 'op', op: OPS[w], word: t.text, arg: this.unary(s, o), line };
|
|
430
|
+
}
|
|
431
|
+
if (w === 'round') {
|
|
432
|
+
s.next();
|
|
433
|
+
const e = this.unary(s, { ...o, noAnd: true });
|
|
434
|
+
let places = null;
|
|
435
|
+
if (s.word('to')) {
|
|
436
|
+
places = this.unary(s, o);
|
|
437
|
+
s.word('decimal');
|
|
438
|
+
if (!s.word('places') && !s.word('place')) s.fail('Write "round X to 2 places" (or "to 2 decimal places").', null, 'TC108');
|
|
439
|
+
}
|
|
440
|
+
return { k: 'round', e, places, line };
|
|
441
|
+
}
|
|
442
|
+
if (w === 'read' && isWord(s.peek(1), 'file')) { s.i += 2; return { k: 'readFile', path: this.unary(s, o), line }; }
|
|
443
|
+
if (w === 'today' && !this.names.known.has('today')) { s.next(); return { k: 'today', line }; }
|
|
444
|
+
if (w === 'date' && s.peek(1)?.t === 'str') { s.next(); const str = s.next(); return { k: 'date', text: str.parts.join(''), line }; }
|
|
445
|
+
if (RESERVED.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, 'TC105');
|
|
446
|
+
|
|
447
|
+
const run = this.wordRun(s);
|
|
448
|
+
// a record: "a Customer with name "Ann" and balance $10", "a new Customer"
|
|
449
|
+
let off = run[0]?.lower === 'new' && run.length > 1 ? 1 : 0;
|
|
450
|
+
const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
|
|
451
|
+
const wantsRecord = o.article || off || isWord(s.peek(), 'with') || !this.longest(run, (key) => this.names.known.has(key));
|
|
452
|
+
if (recK && wantsRecord && (recK + off === run.length)) {
|
|
453
|
+
s.i -= run.length - off - recK;
|
|
454
|
+
const name = keyOf(run.slice(off, off + recK));
|
|
455
|
+
const fields = [];
|
|
456
|
+
if (s.word('with')) {
|
|
457
|
+
do {
|
|
458
|
+
const fr = this.wordRun(s);
|
|
459
|
+
if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
|
|
460
|
+
const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
|
|
461
|
+
s.i -= fr.length - fk;
|
|
462
|
+
fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
|
|
463
|
+
} while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
|
|
464
|
+
}
|
|
465
|
+
return { k: 'new', record: name, fields, line };
|
|
466
|
+
}
|
|
467
|
+
off = 0;
|
|
468
|
+
// a field taken from each item: "prices from orders"
|
|
469
|
+
if (isWord(s.peek(), 'from')) {
|
|
470
|
+
s.next();
|
|
471
|
+
return { k: 'from', name: keyOf(run), text: run.map((x) => x.text).join(' '), list: this.unary(s, o), line };
|
|
472
|
+
}
|
|
473
|
+
const k = this.longest(run, (key) => this.names.known.has(key));
|
|
474
|
+
if (k) {
|
|
475
|
+
s.i -= run.length - k;
|
|
476
|
+
const key = keyOf(run.slice(0, k));
|
|
477
|
+
const text = run.slice(0, k).map((x) => x.text).join(' ');
|
|
478
|
+
if (this.names.known.get(key) === 'func') {
|
|
479
|
+
if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, args: this.parenArgs(s), line };
|
|
480
|
+
if (s.word('with')) return { k: 'call', name: key, text, args: this.withArgs(s), line };
|
|
481
|
+
return { k: 'call', name: key, text, args: [], line, bare: true };
|
|
482
|
+
}
|
|
483
|
+
return { k: 'name', name: key, text, line };
|
|
484
|
+
}
|
|
485
|
+
const fk = this.longest(run, (key) => this.names.fields.has(key));
|
|
486
|
+
if (fk) { s.i -= run.length - fk; return { k: 'name', name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(' '), line, unknown: true }; }
|
|
487
|
+
// An unknown name: kept whole, so the checker can say exactly what it did not know.
|
|
488
|
+
return { k: 'name', name: keyOf(run), text: run.map((x) => x.text).join(' '), line, unknown: true };
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// ---------------------------------------------------------------- statements
|
|
493
|
+
|
|
494
|
+
export function parseCore(source, { seed = null } = {}) {
|
|
495
|
+
const { lines, diagnostics } = lex(source);
|
|
496
|
+
const tree = buildBlocks(lines, diagnostics);
|
|
497
|
+
const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []) };
|
|
498
|
+
collectNames(tree, names);
|
|
499
|
+
const ep = new ExprParser(names);
|
|
500
|
+
const body = parseBlock(tree, ep, names, diagnostics, { top: true });
|
|
501
|
+
return { kind: 'program', body, names, diagnostics };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
505
|
+
const out = [];
|
|
506
|
+
for (const n of nodes) {
|
|
507
|
+
try {
|
|
508
|
+
const st = parseStatement(n, ep, names, diagnostics, ctx, out);
|
|
509
|
+
if (st) out.push(st);
|
|
510
|
+
} catch (e) {
|
|
511
|
+
if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function nameWords(ts, line, what) {
|
|
518
|
+
const words = stripArticle(ts);
|
|
519
|
+
if (!words.length) throw new CoreError(diag('TC108', line, `${what} is missing a name.`));
|
|
520
|
+
for (const t of words) {
|
|
521
|
+
if (t.t !== 'word') throw new CoreError(diag('TC105', line, `A name can only use words, but "${show(t)}" is not a word.`));
|
|
522
|
+
if (RESERVED.has(t.lower)) throw new CoreError(diag('TC202', line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
|
|
523
|
+
}
|
|
524
|
+
return { name: keyOf(words), text: words.map((x) => x.text).join(' ') };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
528
|
+
const ts = n.tokens;
|
|
529
|
+
const line = n.line;
|
|
530
|
+
const E = (tokens, opts) => ep.parse(tokens, line, opts);
|
|
531
|
+
const children = (c = ctx) => parseBlock(n.children, ep, names, diagnostics, c);
|
|
532
|
+
const fail = (code, msg, hint) => { throw new CoreError(diag(code, line, msg, hint)); };
|
|
533
|
+
const header = () => { if (!isSym(ts[ts.length - 1], ':')) fail('TC108', `This line should end with ":".`); return ts.slice(0, -1); };
|
|
534
|
+
const w0 = ts[0].t === 'word' ? ts[0].lower : '';
|
|
535
|
+
const rest = ts.slice(1);
|
|
536
|
+
|
|
537
|
+
if (w0 === 'say' || w0 === 'print') return { k: 'say', e: E(rest), line };
|
|
538
|
+
if (w0 === 'set') {
|
|
539
|
+
const at = splitTop(rest, (t) => isWord(t, 'to'));
|
|
540
|
+
if (at < 0) fail('TC108', '"Set" needs "to": Set total to 0.');
|
|
541
|
+
const targetTs = stripArticle(rest.slice(0, at));
|
|
542
|
+
if (!targetTs.length) fail('TC108', '"Set" is missing the name to set.');
|
|
543
|
+
const target = allWords(targetTs) && !targetTs.some((t) => RESERVED.has(t.lower)) ? { k: 'name', ...nameWords(targetTs, line, '"Set"'), line } : E(targetTs);
|
|
544
|
+
if (!['name', 'field', 'at'].includes(target.k)) fail('TC305', 'Only a name, a field (customer\'s balance), or an entry (counts at word) can be set.');
|
|
545
|
+
return { k: 'set', target, e: E(rest.slice(at + 1)), line };
|
|
546
|
+
}
|
|
547
|
+
if (w0 === 'keep') {
|
|
548
|
+
const at = splitTop(rest, (t) => isWord(t, 'at'));
|
|
549
|
+
if (at < 0) fail('TC108', '"Keep" needs "at": Keep tax rate at 7%.');
|
|
550
|
+
return { k: 'keep', ...nameWords(rest.slice(0, at), line, '"Keep"'), e: E(rest.slice(at + 1)), line };
|
|
551
|
+
}
|
|
552
|
+
if (w0 === 'give') {
|
|
553
|
+
let r = rest;
|
|
554
|
+
if (isWord(r[0], 'back')) r = r.slice(1);
|
|
555
|
+
return { k: 'give', e: r.length ? E(r) : { k: 'nothing', line }, line };
|
|
556
|
+
}
|
|
557
|
+
if (w0 === 'stop') {
|
|
558
|
+
let r = rest;
|
|
559
|
+
if (isWord(r[0], 'with') || isSym(r[0], ':')) r = r.slice(1);
|
|
560
|
+
return { k: 'stop', e: r.length ? E(r) : { k: 'str', parts: ['Stopped'], line }, line };
|
|
561
|
+
}
|
|
562
|
+
if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
|
|
563
|
+
header();
|
|
564
|
+
const prev = siblings[siblings.length - 1];
|
|
565
|
+
if (!prev || prev.k === 'func' || prev.k === 'record' || prev.k === 'test' || prev.k === 'tryFail') fail('TC110', '"If this fails:" goes right after the statement it protects.');
|
|
566
|
+
siblings.pop();
|
|
567
|
+
return { k: 'tryFail', stmt: prev, handler: children(), line };
|
|
568
|
+
}
|
|
569
|
+
if (w0 === 'when' || w0 === 'if') {
|
|
570
|
+
const cond = E(header().slice(1));
|
|
571
|
+
return { k: 'if', branches: [{ cond, body: children(), line }], otherwise: null, line };
|
|
572
|
+
}
|
|
573
|
+
if (w0 === 'otherwise') {
|
|
574
|
+
const prev = siblings[siblings.length - 1];
|
|
575
|
+
if (!prev || prev.k !== 'if' || prev.otherwise) fail('TC109', '"Otherwise" must come right after a "When" or "If" block (at the same indentation).');
|
|
576
|
+
const h = header();
|
|
577
|
+
if (h.length === 1) { prev.otherwise = children(); return null; }
|
|
578
|
+
if (!isWord(h[1], 'when') && !isWord(h[1], 'if')) fail('TC108', 'Write "Otherwise:" or "Otherwise when <condition>:".');
|
|
579
|
+
prev.branches.push({ cond: E(h.slice(2)), body: children(), line });
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
if (w0 === 'for' && isWord(ts[1], 'each')) {
|
|
583
|
+
const h = header().slice(2);
|
|
584
|
+
const inAt = splitTop(h, (t) => isWord(t, 'in'));
|
|
585
|
+
const fromAt = splitTop(h, (t) => isWord(t, 'from'));
|
|
586
|
+
if (inAt >= 0) {
|
|
587
|
+
const head = h.slice(0, inAt);
|
|
588
|
+
const andAt = head.findIndex((t) => isWord(t, 'and'));
|
|
589
|
+
const vars = andAt >= 0 ? [nameWords(head.slice(0, andAt), line, '"For each"'), nameWords(head.slice(andAt + 1), line, '"For each"')] : [nameWords(head, line, '"For each"')];
|
|
590
|
+
return { k: 'each', vars, iter: E(h.slice(inAt + 1)), body: children(), line };
|
|
591
|
+
}
|
|
592
|
+
if (fromAt >= 0) {
|
|
593
|
+
const toAt = splitTop(h, (t) => isWord(t, 'to'));
|
|
594
|
+
if (toAt < 0) fail('TC108', '"For each … from" needs "to": For each n from 1 to 10:');
|
|
595
|
+
return { k: 'range', v: nameWords(h.slice(0, fromAt), line, '"For each"'), from: E(h.slice(fromAt + 1, toAt)), to: E(h.slice(toAt + 1)), body: children(), line };
|
|
596
|
+
}
|
|
597
|
+
fail('TC108', 'Write "For each item in list:" or "For each n from 1 to 10:".');
|
|
598
|
+
}
|
|
599
|
+
if (w0 === 'repeat') {
|
|
600
|
+
const h = header().slice(1);
|
|
601
|
+
if (isWord(h[0], 'while')) return { k: 'while', cond: E(h.slice(1)), body: children(), line };
|
|
602
|
+
if (isWord(h[0], 'until')) return { k: 'while', until: true, cond: E(h.slice(1)), body: children(), line };
|
|
603
|
+
if (isWord(h[h.length - 1], 'times')) return { k: 'times', count: E(h.slice(0, -1)), body: children(), line };
|
|
604
|
+
fail('TC108', 'Write "Repeat while <condition>:", "Repeat until <condition>:", or "Repeat 3 times:".');
|
|
605
|
+
}
|
|
606
|
+
if (w0 === 'to' && isSym(ts[ts.length - 1], ':')) {
|
|
607
|
+
if (!ctx.top) fail('TC402', 'A "To" block (a function) must be written at the left edge, not inside another block.');
|
|
608
|
+
const { name, text } = nameWords(header().slice(1), line, '"To"');
|
|
609
|
+
const kids = n.children;
|
|
610
|
+
let params = [];
|
|
611
|
+
let bodyNodes = kids;
|
|
612
|
+
// One "Receive" line, or several in a row ("Receive total as a number", "Receive member as yes or no").
|
|
613
|
+
let r = 0;
|
|
614
|
+
while (kids[r] && isWord(kids[r].tokens[0], 'receive')) {
|
|
615
|
+
const kid = kids[r];
|
|
616
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.words, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
617
|
+
r++;
|
|
618
|
+
}
|
|
619
|
+
bodyNodes = kids.slice(r);
|
|
620
|
+
return { k: 'func', name, text, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
|
|
621
|
+
}
|
|
622
|
+
if (w0 === 'receive') fail('TC111', '"Receive" must be the first line inside a "To" block.');
|
|
623
|
+
if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
|
|
624
|
+
if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
|
|
625
|
+
const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
|
|
626
|
+
const fields = [], rules = [];
|
|
627
|
+
for (const c of n.children) {
|
|
628
|
+
try {
|
|
629
|
+
if (isWord(c.tokens[0], 'never')) { rules.push(parseNever(c.tokens, c.line, ep)); continue; }
|
|
630
|
+
const k = c.tokens.findIndex((t) => isWord(t, 'is') || isWord(t, 'are'));
|
|
631
|
+
if (k <= 0) throw new CoreError(diag('TC108', c.line, 'A field is written "<name> is <kind>", for example: Balance is money.'));
|
|
632
|
+
fields.push({ ...nameWords(c.tokens.slice(0, k), c.line, 'A field'), type: typeOf(ep, c.tokens.slice(k + 1), c.line), line: c.line });
|
|
633
|
+
} catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
634
|
+
}
|
|
635
|
+
return { k: 'record', name, text, fields, rules, line };
|
|
636
|
+
}
|
|
637
|
+
if (w0 === 'expect') return { ...parseExpect(rest, line, ep), raw: n.raw };
|
|
638
|
+
if (w0 === 'never') return parseNever(ts, line, ep);
|
|
639
|
+
if (w0 === 'use') {
|
|
640
|
+
if (!ctx.top) fail('TC402', '"Use" must be written at the left edge of the file.');
|
|
641
|
+
const asAt = rest.findIndex((t) => isWord(t, 'as'));
|
|
642
|
+
const modTs = asAt < 0 ? rest : rest.slice(0, asAt);
|
|
643
|
+
const module = modTs.map((t) => (t.t === 'word' ? t.text : t.t === 'sym' && t.text === '.' ? '.' : '\u0000')).join('');
|
|
644
|
+
if (!module || module.includes('\u0000') || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module)) fail('TC108', 'Write "Use <python module> as <name>", for example: Use csv as csv.');
|
|
645
|
+
const alias = asAt < 0 ? { name: module.split('.')[0].toLowerCase(), text: module.split('.')[0] } : nameWords(rest.slice(asAt + 1), line, '"Use"');
|
|
646
|
+
return { k: 'use', module, ...alias, line };
|
|
647
|
+
}
|
|
648
|
+
if (w0 === 'test') {
|
|
649
|
+
if (!ctx.top) fail('TC402', 'A "Test" block must be written at the left edge of the file.');
|
|
650
|
+
const h = header().slice(1);
|
|
651
|
+
const title = h.length === 1 && h[0].t === 'str' ? h[0].parts.filter((p) => typeof p === 'string').join('') : h.map((t) => show(t)).join(' ');
|
|
652
|
+
if (!title) fail('TC108', 'A test needs a name: Test "members get 20% off":');
|
|
653
|
+
return { k: 'test', title, body: children({ inFunc: true, inTest: true }), line };
|
|
654
|
+
}
|
|
655
|
+
if (w0 === 'add' || w0 === 'remove') {
|
|
656
|
+
const word = w0 === 'add' ? 'to' : 'from';
|
|
657
|
+
const at = lastTop(rest, (t) => isWord(t, word));
|
|
658
|
+
if (at < 0) fail('TC108', w0 === 'add' ? '"Add" needs "to": Add 5 to total, or Add order to orders.' : '"Remove" needs "from": Remove item from cart.');
|
|
659
|
+
return { k: w0, e: E(rest.slice(0, at)), target: E(rest.slice(at + 1)), line };
|
|
660
|
+
}
|
|
661
|
+
if (w0 === 'increase' || w0 === 'decrease') {
|
|
662
|
+
const at = splitTop(rest, (t) => isWord(t, 'by'));
|
|
663
|
+
if (at < 0) fail('TC108', `"${ts[0].text}" needs "by": ${ts[0].text} balance by 10.`);
|
|
664
|
+
return { k: w0, target: E(rest.slice(0, at)), e: E(rest.slice(at + 1)), line };
|
|
665
|
+
}
|
|
666
|
+
if (w0 === 'sort') {
|
|
667
|
+
const at = splitTop(rest, (t) => isWord(t, 'by'));
|
|
668
|
+
const target = E(at < 0 ? rest : rest.slice(0, at));
|
|
669
|
+
let by = null, desc = false, text = null;
|
|
670
|
+
if (at >= 0) {
|
|
671
|
+
let f = rest.slice(at + 1);
|
|
672
|
+
if (isWord(f[f.length - 1], 'descending')) { desc = true; f = f.slice(0, -1); } else if (isWord(f[f.length - 1], 'ascending')) f = f.slice(0, -1);
|
|
673
|
+
by = keyOf(f); text = f.map((x) => x.text).join(' ');
|
|
674
|
+
}
|
|
675
|
+
return { k: 'sort', target, by, text, desc, line };
|
|
676
|
+
}
|
|
677
|
+
if (w0 === 'reverse') return { k: 'reverse', target: E(rest), line };
|
|
678
|
+
|
|
679
|
+
// A call used as a statement: "greet with "Ann"", "csv.writer(out)".
|
|
680
|
+
if (ts[0].t === 'word' && !RESERVED.has(w0)) {
|
|
681
|
+
const run = [];
|
|
682
|
+
for (const t of ts) { if (t.t === 'word' && !RESERVED.has(t.lower)) run.push(t); else break; }
|
|
683
|
+
const known = ep.longest(run, (key) => names.known.has(key));
|
|
684
|
+
if (!known) {
|
|
685
|
+
const restTs = ts.slice(1);
|
|
686
|
+
return { k: 'unknownVerb', verb: ts[0].text, object: restTs.length ? safeParse(ep, restTs, line) : null, line, raw: n.raw };
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const e = E(ts);
|
|
690
|
+
if (e.k !== 'call' && !(e.k === 'dot' && e.args)) fail('TC401', `I don't know what to do with "${n.raw}".`, `A line starts with an action: ${STATEMENT_WORDS.slice(0, 12).join(', ')}, …`);
|
|
691
|
+
return { k: 'do', e, line };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function safeParse(ep, ts, line) { try { return ep.parse(ts, line); } catch { return null; } }
|
|
695
|
+
|
|
696
|
+
function typeOf(ep, tokens, line) {
|
|
697
|
+
const s = new Stream(tokens, line);
|
|
698
|
+
const t = ep.typeRef(s);
|
|
699
|
+
if (!s.done()) s.fail(`I understood the kind of value up to "${show(s.peek())}", but not after it.`, null, 'TC112');
|
|
700
|
+
return t;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function parseExpect(rest, line, ep) {
|
|
704
|
+
const at = splitTop(rest, (t, k) => isWord(t, 'to') && (isWord(rest[k + 1], 'be') || isWord(rest[k + 1], 'fail') || isWord(rest[k + 1], 'contain')));
|
|
705
|
+
if (at < 0) return { k: 'expect', mode: 'true', e: ep.parse(rest, line), line, text: rest.map(show).join(' ') };
|
|
706
|
+
const actual = ep.parse(rest.slice(0, at), line);
|
|
707
|
+
const tail = rest.slice(at + 1);
|
|
708
|
+
if (isWord(tail[0], 'fail')) {
|
|
709
|
+
let msg = null;
|
|
710
|
+
if (isWord(tail[1], 'with')) msg = ep.parse(tail.slice(2), line);
|
|
711
|
+
else if (tail.length > 1) throw new CoreError(diag('TC112', line, 'Write "Expect <action> to fail" or "Expect <action> to fail with "message"".'));
|
|
712
|
+
return { k: 'expect', mode: 'fail', e: actual, msg, line };
|
|
713
|
+
}
|
|
714
|
+
if (isWord(tail[0], 'contain')) return { k: 'expect', mode: 'cmp', op: 'contains', e: actual, want: ep.parse(tail.slice(1), line), line };
|
|
715
|
+
// to be …: reuse the comparison words by parsing "<actual> is …"
|
|
716
|
+
const s = new Stream([{ t: 'word', text: 'is', lower: 'is' }, ...tail.slice(1)], line);
|
|
717
|
+
const placeholder = { k: 'hole', line };
|
|
718
|
+
const fake = new ExprParser(ep.names);
|
|
719
|
+
fake.add = function (st, o) { if (st.i === 0) return placeholder; return ExprParser.prototype.add.call(this, st, o); };
|
|
720
|
+
const cmp = fake.cmp(s, {});
|
|
721
|
+
if (!s.done()) throw new CoreError(diag('TC112', line, `I understood "Expect … to be" up to "${show(s.peek())}", but not after it.`));
|
|
722
|
+
return { k: 'expect', mode: 'be', e: actual, check: cmp, line };
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Never allow a negative quantity | Never allow quantity to be negative | Never allow balance is less than 0
|
|
726
|
+
function parseNever(ts, line, ep) {
|
|
727
|
+
if (!isWord(ts[1], 'allow')) throw new CoreError(diag('TC108', line, 'Write "Never allow …", for example: Never allow a negative quantity.'));
|
|
728
|
+
let r = ts.slice(2);
|
|
729
|
+
const text = `Never allow ${r.map(show).join(' ')}`;
|
|
730
|
+
const ADJ = { negative: 'negative', zero: 'zero', empty: 'empty', missing: 'nothing' };
|
|
731
|
+
const r2 = stripArticle(r);
|
|
732
|
+
if (r2[0]?.t === 'word' && ADJ[r2[0].lower] && allWords(r2.slice(1)) && r2.length > 1) {
|
|
733
|
+
const subj = { k: 'name', name: keyOf(r2.slice(1)), text: r2.slice(1).map((x) => x.text).join(' '), line };
|
|
734
|
+
const adj = ADJ[r2[0].lower];
|
|
735
|
+
return { k: 'never', text, cond: adj === 'nothing' ? { k: 'isNothing', e: subj, neg: false, line } : { k: 'adj', adj, e: subj, line }, line };
|
|
736
|
+
}
|
|
737
|
+
const toBe = splitTop(r, (t, k) => isWord(t, 'to') && isWord(r[k + 1], 'be'));
|
|
738
|
+
if (toBe > 0) r = [...r.slice(0, toBe), { t: 'word', text: 'is', lower: 'is' }, ...r.slice(toBe + 2)];
|
|
739
|
+
return { k: 'never', text, cond: ep.parse(r, line), line };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
export { closest };
|