@skillstech/thunderlang 1.5.0 → 1.6.1

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.
@@ -0,0 +1,239 @@
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
+ class Unknown extends Error { constructor(word) { super(word); this.word = word; } }
55
+
56
+ /** The function's inputs, from its signature (the first parentheses in `scope`). */
57
+ export function inputsOf(scope) {
58
+ const code = codeOnly(scope || ''), open = code.indexOf('(');
59
+ if (open < 0) return [];
60
+ let depth = 0, end = open;
61
+ for (; end < code.length; end++) { if (code[end] === '(') depth++; else if (code[end] === ')' && --depth === 0) break; }
62
+ const out = [];
63
+ for (const part of code.slice(open + 1, end).split(',')) {
64
+ const id = part.replace(/^\s*[*&.]*\s*/, '').match(/^[A-Za-z_]\w*/)?.[0];
65
+ if (id && !KEYWORDS.has(id) && id !== 'self' && id !== 'cls' && !out.includes(id)) out.push(id);
66
+ }
67
+ return out;
68
+ }
69
+ const unknownWord = (word, scope) => {
70
+ const inputs = inputsOf(scope);
71
+ return `"${word}" is not a name in this function or file${inputs.length ? `; its inputs are ${inputs.map((i) => `"${nameWords(i) || i}"`).join(', ')}` : ''}. Use one of its names, or add an input first (addInput).`;
72
+ };
73
+ const no = (why) => { throw new Unsaid(why); };
74
+
75
+ /** A Core expression (core/parser.mjs) as a meaning tree for `language`. */
76
+ function toTree(n, language, names) {
77
+ const T = (x) => toTree(x, language, names);
78
+ const py = language === 'python', go = language === 'go', js = language === 'typescript' || language === 'javascript';
79
+ const call = (callee, args) => ({ kind: 'call', callee, args });
80
+ const member = (object, property) => ({ kind: 'member', object, property });
81
+ const nm = (name) => ({ kind: 'name', name });
82
+ switch (n.k) {
83
+ case 'paren': return T(n.e);
84
+ case 'num': return lit('number', Number(n.text), n.text);
85
+ case 'str':
86
+ if (n.parts.some((p) => typeof p !== 'string')) no('a text with values inside it ({…})');
87
+ return lit('text', n.parts.join(''), JSON.stringify(n.parts.join('')));
88
+ case 'bool': return lit('bool', n.v, py ? (n.v ? 'True' : 'False') : String(n.v));
89
+ case 'nothing': return lit('null', null, NULL_RAW[language]);
90
+ case 'name': {
91
+ // Only a name the code already has: a word that is no name in the function or the file is refused, never
92
+ // written as a new name the code would fail on.
93
+ const id = names.get(n.name);
94
+ if (!id) throw new Unknown(n.name);
95
+ return nm(id);
96
+ }
97
+ case 'field': case 'dot': {
98
+ if (n.args) no('a call written with a dot');
99
+ const prop = n.k === 'field' ? n.name : n.attr;
100
+ return member(T(n.obj), names.get(prop) ?? prop.replace(/ /g, '_'));
101
+ }
102
+ case 'neg': return { kind: 'unary', op: '-', value: T(n.e) };
103
+ case 'not': return { kind: 'not', value: T(n.e) };
104
+ case 'bin': {
105
+ if (n.op === 'and' || n.op === 'or') {
106
+ const operands = [];
107
+ 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); }
108
+ return { kind: 'logic', op: n.op, operands };
109
+ }
110
+ const op = { '+': '+', '-': '-', '*': '*', '/': '/', mod: '%', '%': '%' }[n.op];
111
+ if (!op) no(`"${n.op}"`);
112
+ return { kind: 'binary', op, left: T(n.l), right: T(n.r) };
113
+ }
114
+ case 'cmp': {
115
+ // "member is true" means equal to true, not truthy (in Python 1 and "x" are truthy): `member is True` in Python,
116
+ // `=== true` in JavaScript. A person who means truthy writes "member" or "not member".
117
+ 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) };
118
+ const op = n.op === '==' ? (js ? '===' : '==') : n.op === '!=' ? (js ? '!==' : '!=') : n.op;
119
+ return { kind: 'compare', op, left: T(n.l), right: T(n.r) };
120
+ }
121
+ case 'isNothing': {
122
+ // "is nothing": Python's `is None`; JavaScript's `== null` (null or undefined); Go's `== nil`.
123
+ const op = py ? (n.neg ? 'is not' : 'is') : n.neg ? '!=' : '==';
124
+ return { kind: 'compare', op, left: T(n.e), right: lit('null', null, NULL_RAW[language]) };
125
+ }
126
+ case 'between': {
127
+ const e = T(n.e);
128
+ return { kind: 'logic', op: 'and', operands: [{ kind: 'compare', op: '>=', left: e, right: T(n.lo) }, { kind: 'compare', op: '<=', left: e, right: T(n.hi) }] };
129
+ }
130
+ case 'contains': {
131
+ if (py) return { kind: 'compare', op: 'in', left: T(n.r), right: T(n.l) };
132
+ if (js) return call(member(T(n.l), 'includes'), [T(n.r)]);
133
+ no('"contains" in Go (strings.Contains or slices.Contains depends on the value)');
134
+ break;
135
+ }
136
+ case 'affix': {
137
+ const l = T(n.l), r = T(n.r);
138
+ if (py) return call(member(l, n.end ? 'endswith' : 'startswith'), [r]);
139
+ if (js) return call(member(l, n.end ? 'endsWith' : 'startsWith'), [r]);
140
+ return call(member(nm('strings'), n.end ? 'HasSuffix' : 'HasPrefix'), [l, r]);
141
+ }
142
+ case 'op': {
143
+ const a = T(n.arg);
144
+ if (n.op === 'length' || n.op === 'count') return js ? member(a, 'length') : call(nm('len'), [a]);
145
+ if (n.op === 'lowercase') return py ? call(member(a, 'lower'), []) : js ? call(member(a, 'toLowerCase'), []) : call(member(nm('strings'), 'ToLower'), [a]);
146
+ if (n.op === 'uppercase') return py ? call(member(a, 'upper'), []) : js ? call(member(a, 'toUpperCase'), []) : call(member(nm('strings'), 'ToUpper'), [a]);
147
+ if (n.op === 'trimmed') return py ? call(member(a, 'strip'), []) : js ? call(member(a, 'trim'), []) : call(member(nm('strings'), 'TrimSpace'), [a]);
148
+ if (n.op === 'first') return { kind: 'index', object: a, index: lit('number', 0, '0') };
149
+ 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') } };
150
+ no(`"the ${n.word} of"`);
151
+ break;
152
+ }
153
+ default: no(`"${n.k}"`);
154
+ }
155
+ return null;
156
+ }
157
+
158
+ function parseThunder(text, source, scope) {
159
+ const names = namesOf(source, scope);
160
+ const known = new Map([...names.keys()].map((k) => [k, 'var']));
161
+ 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() });
162
+ const lexed = tokenizeLine(String(text), 1);
163
+ const tokens = Array.isArray(lexed) ? lexed : lexed.tokens;
164
+ return { node: ep.parse(tokens, 1), names };
165
+ }
166
+
167
+ /**
168
+ * A condition or value in Thunder's words, as a meaning tree for `language`, or { error } when it is not Thunder or
169
+ * cannot be said in that language. `source`: the file, whose names the words are matched against.
170
+ */
171
+ export function thunderTree(text, language, source, scope = '') {
172
+ let parsed;
173
+ try { parsed = parseThunder(text, source, scope); } catch (e) { return { error: String(e.message).replace(/^Line 1: /, '').split('\n')[0] }; }
174
+ try { return { tree: toTree(parsed.node, language, parsed.names) }; } catch (e) {
175
+ if (e instanceof Unsaid) return { error: `Thunder write cannot say ${e.message} in ${language} yet.` };
176
+ if (e instanceof Unknown) return { error: unknownWord(e.word, scope), unknown: e.word };
177
+ throw e;
178
+ }
179
+ }
180
+
181
+ /** Does the text use words only Thunder uses (so it is read as Thunder before it is read as code)? */
182
+ export const looksThunder = (text) => typeof text === 'string' && THUNDER_MARKERS.test(text);
183
+
184
+ /**
185
+ * A step in Thunder's words: `Give <value>`, `Set <name> to <value>`, or `Stop with "<message>"`.
186
+ * Returns { tree } (a return or an assignment), { stop: message }, { error }, or null when it is not one of these.
187
+ */
188
+ export function thunderStep(text, language, source, scope = '') {
189
+ const t = String(text).trim();
190
+ let m;
191
+ if ((m = t.match(/^stop with\s+(["'])(.*)\1\s*$/i))) return { stop: m[2] };
192
+ if ((m = t.match(/^give(?: back)?\s+(.+)$/i))) {
193
+ const v = thunderTree(m[1], language, source, scope);
194
+ return v.tree ? { tree: { kind: 'return', value: v.tree } } : { error: v.error };
195
+ }
196
+ if ((m = t.match(/^set\s+(.+?)\s+to\s+(.+)$/i))) {
197
+ const target = thunderTree(m[1], language, source, scope), value = thunderTree(m[2], language, source, scope);
198
+ if (!target.tree) return { error: target.error };
199
+ if (!value.tree) return { error: value.error };
200
+ if (target.tree.kind !== 'name' && target.tree.kind !== 'member') return { error: `"${m[1]}" is not a name to set.` };
201
+ return { tree: { kind: 'assign', op: '=', target: target.tree, value: value.tree } };
202
+ }
203
+ return null;
204
+ }
205
+
206
+ // Names every program in the language has without writing them: built-in functions, types, and globals.
207
+ const BUILTINS = {
208
+ python: 'abs all any ascii bin bool bytearray bytes callable chr dict dir divmod enumerate filter float format frozenset getattr globals hasattr hash hex id int isinstance issubclass iter len list locals map max min next object oct open ord pow print range repr reversed round set setattr slice sorted str sum super tuple type vars zip Exception ValueError TypeError KeyError IndexError RuntimeError AttributeError NotImplementedError StopIteration LookupError ArithmeticError ZeroDivisionError OSError NotImplemented Ellipsis __name__ __file__',
209
+ typescript: 'Math JSON Object Array String Number Boolean Date Error TypeError RangeError Promise Map Set WeakMap Symbol BigInt RegExp console parseInt parseFloat isNaN isFinite undefined NaN Infinity globalThis window document process require module exports',
210
+ go: 'len cap append make new copy delete panic recover print println close complex real imag min max clear error string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float32 float64 bool byte rune any iota fmt errors strings strconv',
211
+ };
212
+ BUILTINS.javascript = BUILTINS.typescript;
213
+
214
+ /**
215
+ * The first name in `tree` that the code does not have (not in the file, not built in), or null. Names the step
216
+ * itself introduces are allowed: assignment and declaration targets, loop variables, and a function's own inputs.
217
+ */
218
+ export function unknownName(tree, language, source, scope = '') {
219
+ const known = new Set(BUILTINS[language]?.split(' ') ?? []);
220
+ // The function's own code counts as code even where the file is read as text around it (a docstring example).
221
+ for (const text of [codeOnly(source), codeOnly(scope)]) for (const m of text.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*\b/g)) known.add(m[0]);
222
+ for (const k of KEYWORDS) known.add(k);
223
+ const bound = new Set();
224
+ const all = [];
225
+ const walk = (n) => {
226
+ if (Array.isArray(n)) { n.forEach(walk); return; }
227
+ if (!n || typeof n !== 'object') return;
228
+ if (n.kind === 'lambda' || n.kind === 'code') { bound.add('*'); return; }
229
+ if (n.kind === 'name') all.push(n.name);
230
+ if ((n.kind === 'assign' || n.kind === 'declare') && n.target?.kind === 'name') bound.add(n.target.name);
231
+ if (n.kind === 'declare' && typeof n.name === 'string') bound.add(n.name);
232
+ if (n.kind === 'loop') for (const v of [n.variable, n.var, n.name, n.target]) { if (typeof v === 'string') bound.add(v); else if (v?.kind === 'name') bound.add(v.name); }
233
+ for (const [k, v] of Object.entries(n)) if (k !== 'raw' && v && typeof v === 'object') walk(v);
234
+ };
235
+ walk(tree);
236
+ if (bound.has('*')) return null;
237
+ return all.find((id) => !known.has(id) && !bound.has(id)) ?? null;
238
+ }
239
+ export const unknownNameReason = (word, scope) => unknownWord(word, scope);
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;