@skillstech/thunderlang 1.5.0 → 1.6.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 +28 -0
- package/dist/core.cjs +1036 -134
- package/dist/index.cjs +5543 -4624
- package/dist/learn.cjs +12 -1
- package/package.json +1 -1
- package/src/cli.mjs +7 -4
- package/src/emit.mjs +1 -1
- package/src/mcp.mjs +18 -1
- package/src/write-steps.mjs +152 -23
- package/src/write-words.mjs +182 -0
- package/src/write.mjs +12 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Thunder write in Thunder's own words: a condition, a value, or a step written the way Thunder reads code
|
|
2
|
+
// ("amount is at least 100", "the length of words is 0", "name is nothing", Stop with "Amount must be positive")
|
|
3
|
+
// becomes the meaning tree (thunder-expr-v1) that thunder write turns into code for the file's language.
|
|
4
|
+
//
|
|
5
|
+
// thunderTree("total is below 0 and not member", "python", source) -> total < 0 and not member
|
|
6
|
+
// thunderStep('Give the length of words', "go", source) -> return len(words)
|
|
7
|
+
//
|
|
8
|
+
// Names are the code's own names said as words: `max_length`, `maxLength`, and "max length" are the same name, matched
|
|
9
|
+
// against the names written in the file. A Thunder word with no fixed meaning in the target language (a position
|
|
10
|
+
// "item 1 of", money, percent, dates) is refused rather than guessed. Browser-safe; nothing is run.
|
|
11
|
+
import { ExprParser } from './core/parser.mjs';
|
|
12
|
+
import { tokenizeLine } from './core/lexer.mjs';
|
|
13
|
+
|
|
14
|
+
/** The words a code name is made of: max_length, maxLength, MaxLength -> "max length". */
|
|
15
|
+
export const nameWords = (id) => id.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/_+/g, ' ').trim().toLowerCase();
|
|
16
|
+
|
|
17
|
+
const KEYWORDS = new Set(['def', 'return', 'if', 'elif', 'else', 'for', 'while', 'in', 'is', 'not', 'and', 'or', 'None', 'True', 'False', 'class', 'import', 'from', 'as', 'with', 'try', 'except', 'finally', 'raise', 'lambda', 'pass', 'break', 'continue', 'yield', 'function', 'const', 'let', 'var', 'new', 'this', 'null', 'undefined', 'true', 'false', 'typeof', 'instanceof', 'throw', 'catch', 'switch', 'case', 'default', 'func', 'package', 'nil', 'type', 'struct', 'interface', 'go', 'defer', 'chan', 'map', 'range', 'export', 'async', 'await', 'self', 'cls']);
|
|
18
|
+
|
|
19
|
+
// Code with its comments and text values blanked out: a word in a docstring ("Value of ...") is not a name.
|
|
20
|
+
const codeOnly = (src) => String(src ?? '')
|
|
21
|
+
.replace(/"""[\s\S]*?"""|'''[\s\S]*?'''/g, ' ')
|
|
22
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
23
|
+
.replace(/`(?:\\[\s\S]|[^`\\])*`|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'/g, ' ')
|
|
24
|
+
.replace(/(#|\/\/)[^\n]*/g, ' ');
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Every name written in the code, by its words: Map("max length" -> "max_length"). The names in `scope` (the edited
|
|
28
|
+
* function's own code) come first; then the rest of the file. A word that is itself a name (`value`) is that name,
|
|
29
|
+
* never another spelling of the same words (`Value`).
|
|
30
|
+
*/
|
|
31
|
+
function namesOf(source, scope) {
|
|
32
|
+
const byWords = new Map(), exact = new Set();
|
|
33
|
+
for (const text of [scope, source]) {
|
|
34
|
+
for (const m of codeOnly(text).matchAll(/\b[A-Za-z_][A-Za-z0-9_]*\b/g)) {
|
|
35
|
+
const id = m[0];
|
|
36
|
+
if (KEYWORDS.has(id)) continue;
|
|
37
|
+
exact.add(id);
|
|
38
|
+
const w = nameWords(id);
|
|
39
|
+
if (w && !byWords.has(w)) byWords.set(w, id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const id of exact) byWords.set(id, id);
|
|
43
|
+
for (const [w, id] of byWords) if (exact.has(w)) byWords.set(w, w);
|
|
44
|
+
return byWords;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Words and shapes only Thunder uses: when one is in the text, it is read as Thunder before it is read as code.
|
|
48
|
+
const THUNDER_MARKERS = /\b(is (not )?(at least|at most|more than|less than|greater than|fewer than|below|above|under|over|nothing|missing|between|true|false|empty)|the (length|number|count|lowercase|uppercase|first|last|sum|total|trimmed) of|contains|starts with|ends with|plus|minus|times|divided by|equals)\b|'s\b/i;
|
|
49
|
+
|
|
50
|
+
const lit = (type, value, raw) => ({ kind: 'literal', type, value, raw });
|
|
51
|
+
const NULL_RAW = { python: 'None', go: 'nil', typescript: 'null', javascript: 'null' };
|
|
52
|
+
|
|
53
|
+
class Unsaid extends Error {}
|
|
54
|
+
const no = (why) => { throw new Unsaid(why); };
|
|
55
|
+
|
|
56
|
+
/** A Core expression (core/parser.mjs) as a meaning tree for `language`. */
|
|
57
|
+
function toTree(n, language, names) {
|
|
58
|
+
const T = (x) => toTree(x, language, names);
|
|
59
|
+
const py = language === 'python', go = language === 'go', js = language === 'typescript' || language === 'javascript';
|
|
60
|
+
const call = (callee, args) => ({ kind: 'call', callee, args });
|
|
61
|
+
const member = (object, property) => ({ kind: 'member', object, property });
|
|
62
|
+
const nm = (name) => ({ kind: 'name', name });
|
|
63
|
+
switch (n.k) {
|
|
64
|
+
case 'paren': return T(n.e);
|
|
65
|
+
case 'num': return lit('number', Number(n.text), n.text);
|
|
66
|
+
case 'str':
|
|
67
|
+
if (n.parts.some((p) => typeof p !== 'string')) no('a text with values inside it ({…})');
|
|
68
|
+
return lit('text', n.parts.join(''), JSON.stringify(n.parts.join('')));
|
|
69
|
+
case 'bool': return lit('bool', n.v, py ? (n.v ? 'True' : 'False') : String(n.v));
|
|
70
|
+
case 'nothing': return lit('null', null, NULL_RAW[language]);
|
|
71
|
+
case 'name': {
|
|
72
|
+
const id = names.get(n.name) ?? (/^[A-Za-z_]\w*$/.test(n.name) ? n.name : null);
|
|
73
|
+
if (!id) no(`"${n.name}" (no name in the file is said that way)`);
|
|
74
|
+
return nm(id);
|
|
75
|
+
}
|
|
76
|
+
case 'field': case 'dot': {
|
|
77
|
+
if (n.args) no('a call written with a dot');
|
|
78
|
+
const prop = n.k === 'field' ? n.name : n.attr;
|
|
79
|
+
return member(T(n.obj), names.get(prop) ?? prop.replace(/ /g, '_'));
|
|
80
|
+
}
|
|
81
|
+
case 'neg': return { kind: 'unary', op: '-', value: T(n.e) };
|
|
82
|
+
case 'not': return { kind: 'not', value: T(n.e) };
|
|
83
|
+
case 'bin': {
|
|
84
|
+
if (n.op === 'and' || n.op === 'or') {
|
|
85
|
+
const operands = [];
|
|
86
|
+
for (const side of [n.l, n.r]) { const t = T(side); if (t.kind === 'logic' && t.op === n.op) operands.push(...t.operands); else operands.push(t); }
|
|
87
|
+
return { kind: 'logic', op: n.op, operands };
|
|
88
|
+
}
|
|
89
|
+
const op = { '+': '+', '-': '-', '*': '*', '/': '/', mod: '%', '%': '%' }[n.op];
|
|
90
|
+
if (!op) no(`"${n.op}"`);
|
|
91
|
+
return { kind: 'binary', op, left: T(n.l), right: T(n.r) };
|
|
92
|
+
}
|
|
93
|
+
case 'cmp': {
|
|
94
|
+
// "member is true" means equal to true, not truthy (in Python 1 and "x" are truthy): `member is True` in Python,
|
|
95
|
+
// `=== true` in JavaScript. A person who means truthy writes "member" or "not member".
|
|
96
|
+
if (py && (n.op === '==' || n.op === '!=') && n.r.k === 'bool') return { kind: 'compare', op: n.op === '==' ? 'is' : 'is not', left: T(n.l), right: T(n.r) };
|
|
97
|
+
const op = n.op === '==' ? (js ? '===' : '==') : n.op === '!=' ? (js ? '!==' : '!=') : n.op;
|
|
98
|
+
return { kind: 'compare', op, left: T(n.l), right: T(n.r) };
|
|
99
|
+
}
|
|
100
|
+
case 'isNothing': {
|
|
101
|
+
// "is nothing": Python's `is None`; JavaScript's `== null` (null or undefined); Go's `== nil`.
|
|
102
|
+
const op = py ? (n.neg ? 'is not' : 'is') : n.neg ? '!=' : '==';
|
|
103
|
+
return { kind: 'compare', op, left: T(n.e), right: lit('null', null, NULL_RAW[language]) };
|
|
104
|
+
}
|
|
105
|
+
case 'between': {
|
|
106
|
+
const e = T(n.e);
|
|
107
|
+
return { kind: 'logic', op: 'and', operands: [{ kind: 'compare', op: '>=', left: e, right: T(n.lo) }, { kind: 'compare', op: '<=', left: e, right: T(n.hi) }] };
|
|
108
|
+
}
|
|
109
|
+
case 'contains': {
|
|
110
|
+
if (py) return { kind: 'compare', op: 'in', left: T(n.r), right: T(n.l) };
|
|
111
|
+
if (js) return call(member(T(n.l), 'includes'), [T(n.r)]);
|
|
112
|
+
no('"contains" in Go (strings.Contains or slices.Contains depends on the value)');
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
case 'affix': {
|
|
116
|
+
const l = T(n.l), r = T(n.r);
|
|
117
|
+
if (py) return call(member(l, n.end ? 'endswith' : 'startswith'), [r]);
|
|
118
|
+
if (js) return call(member(l, n.end ? 'endsWith' : 'startsWith'), [r]);
|
|
119
|
+
return call(member(nm('strings'), n.end ? 'HasSuffix' : 'HasPrefix'), [l, r]);
|
|
120
|
+
}
|
|
121
|
+
case 'op': {
|
|
122
|
+
const a = T(n.arg);
|
|
123
|
+
if (n.op === 'length' || n.op === 'count') return js ? member(a, 'length') : call(nm('len'), [a]);
|
|
124
|
+
if (n.op === 'lowercase') return py ? call(member(a, 'lower'), []) : js ? call(member(a, 'toLowerCase'), []) : call(member(nm('strings'), 'ToLower'), [a]);
|
|
125
|
+
if (n.op === 'uppercase') return py ? call(member(a, 'upper'), []) : js ? call(member(a, 'toUpperCase'), []) : call(member(nm('strings'), 'ToUpper'), [a]);
|
|
126
|
+
if (n.op === 'trimmed') return py ? call(member(a, 'strip'), []) : js ? call(member(a, 'trim'), []) : call(member(nm('strings'), 'TrimSpace'), [a]);
|
|
127
|
+
if (n.op === 'first') return { kind: 'index', object: a, index: lit('number', 0, '0') };
|
|
128
|
+
if (n.op === 'last') return py ? { kind: 'index', object: a, index: { kind: 'unary', op: '-', value: lit('number', 1, '1') } } : { kind: 'index', object: a, index: { kind: 'binary', op: '-', left: js ? member(a, 'length') : call(nm('len'), [a]), right: lit('number', 1, '1') } };
|
|
129
|
+
no(`"the ${n.word} of"`);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
default: no(`"${n.k}"`);
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parseThunder(text, source, scope) {
|
|
138
|
+
const names = namesOf(source, scope);
|
|
139
|
+
const known = new Map([...names.keys()].map((k) => [k, 'var']));
|
|
140
|
+
const ep = new ExprParser({ known, fields: new Set(names.keys()), records: new Set(), recordFields: new Map(), funcInputs: new Map(), recordText: new Map(), screens: new Map() });
|
|
141
|
+
const lexed = tokenizeLine(String(text), 1);
|
|
142
|
+
const tokens = Array.isArray(lexed) ? lexed : lexed.tokens;
|
|
143
|
+
return { node: ep.parse(tokens, 1), names };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* A condition or value in Thunder's words, as a meaning tree for `language`, or { error } when it is not Thunder or
|
|
148
|
+
* cannot be said in that language. `source`: the file, whose names the words are matched against.
|
|
149
|
+
*/
|
|
150
|
+
export function thunderTree(text, language, source, scope = '') {
|
|
151
|
+
let parsed;
|
|
152
|
+
try { parsed = parseThunder(text, source, scope); } catch (e) { return { error: String(e.message).replace(/^Line 1: /, '').split('\n')[0] }; }
|
|
153
|
+
try { return { tree: toTree(parsed.node, language, parsed.names) }; } catch (e) {
|
|
154
|
+
if (e instanceof Unsaid) return { error: `Thunder write cannot say ${e.message} in ${language} yet.` };
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Does the text use words only Thunder uses (so it is read as Thunder before it is read as code)? */
|
|
160
|
+
export const looksThunder = (text) => typeof text === 'string' && THUNDER_MARKERS.test(text);
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* A step in Thunder's words: `Give <value>`, `Set <name> to <value>`, or `Stop with "<message>"`.
|
|
164
|
+
* Returns { tree } (a return or an assignment), { stop: message }, { error }, or null when it is not one of these.
|
|
165
|
+
*/
|
|
166
|
+
export function thunderStep(text, language, source, scope = '') {
|
|
167
|
+
const t = String(text).trim();
|
|
168
|
+
let m;
|
|
169
|
+
if ((m = t.match(/^stop with\s+(["'])(.*)\1\s*$/i))) return { stop: m[2] };
|
|
170
|
+
if ((m = t.match(/^give(?: back)?\s+(.+)$/i))) {
|
|
171
|
+
const v = thunderTree(m[1], language, source, scope);
|
|
172
|
+
return v.tree ? { tree: { kind: 'return', value: v.tree } } : { error: v.error };
|
|
173
|
+
}
|
|
174
|
+
if ((m = t.match(/^set\s+(.+?)\s+to\s+(.+)$/i))) {
|
|
175
|
+
const target = thunderTree(m[1], language, source, scope), value = thunderTree(m[2], language, source, scope);
|
|
176
|
+
if (!target.tree) return { error: target.error };
|
|
177
|
+
if (!value.tree) return { error: value.error };
|
|
178
|
+
if (target.tree.kind !== 'name' && target.tree.kind !== 'member') return { error: `"${m[1]}" is not a name to set.` };
|
|
179
|
+
return { tree: { kind: 'assign', op: '=', target: target.tree, value: value.tree } };
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
package/src/write.mjs
CHANGED
|
@@ -53,6 +53,14 @@ function scanSource(source, from, to, language) {
|
|
|
53
53
|
continue;
|
|
54
54
|
}
|
|
55
55
|
if (/[0-9]/.test(c)) {
|
|
56
|
+
// 0xFF, 0o17, 0b101: one number, written back in the same base.
|
|
57
|
+
const based = source.slice(i, to).match(/^0([xXoObB])([0-9A-Fa-f_]+)/);
|
|
58
|
+
if (based) {
|
|
59
|
+
const radix = { x: 16, o: 8, b: 2 }[based[1].toLowerCase()];
|
|
60
|
+
out.push({ t: 'num', v: parseInt(based[2].replace(/_/g, ''), radix), start: i, end: i + based[0].length, raw: based[0], suffix: '', decimal: false, base: based[1], upper: /[A-F]/.test(based[2]) });
|
|
61
|
+
i += based[0].length;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
56
64
|
const m = source.slice(i, to).match(/^[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9]+)?(f64|f32|i32|i64|u32|u64|[fFdDmMlLuU]{0,2})/);
|
|
57
65
|
const raw = m[0];
|
|
58
66
|
const suffix = m[3] || '';
|
|
@@ -89,6 +97,10 @@ function spell(srcTok, next) {
|
|
|
89
97
|
return next.v;
|
|
90
98
|
}
|
|
91
99
|
if (next.t === 'num') {
|
|
100
|
+
if (srcTok.base && Number.isInteger(next.v) && next.v >= 0) {
|
|
101
|
+
const d = next.v.toString({ x: 16, o: 8, b: 2 }[srcTok.base.toLowerCase()]);
|
|
102
|
+
return `0${srcTok.base}${srcTok.upper ? d.toUpperCase() : d}`;
|
|
103
|
+
}
|
|
92
104
|
let s = String(next.v);
|
|
93
105
|
if (srcTok.decimal && Number.isInteger(next.v)) s += '.0';
|
|
94
106
|
return s + srcTok.suffix;
|