@skillstech/thunderlang 0.5.12 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +71 -0
- package/dist/core.cjs +11491 -9861
- package/dist/index.cjs +11488 -9858
- package/dist/learn.cjs +11054 -9428
- package/package.json +2 -2
- package/src/emit.mjs +1 -1
- package/src/libraries.mjs +2 -2
- package/src/meaning.mjs +2 -1
- package/src/model.mjs +13 -5
- package/src/powershell.mjs +24 -5
- package/src/read-repo.mjs +1 -0
- package/src/read.mjs +82 -8
- package/src/rlang.mjs +10 -3
- package/src/shell.mjs +45 -8
- package/src/sql-proc.mjs +1198 -0
- package/src/sql.mjs +87 -119
- package/src/steps.mjs +188 -37
package/src/steps.mjs
CHANGED
|
@@ -137,7 +137,9 @@ const possessivePlain = (path) => { const parts = String(path).replace(/^\$/, ''
|
|
|
137
137
|
|
|
138
138
|
/** Enum values read as words: Status.ON_SHELF -> "on shelf", Color.RED -> "red". */
|
|
139
139
|
// (Constants of the number and text classes are not choices: `Integer.TYPE`, `Long.MAX_VALUE` stay as written.)
|
|
140
|
-
|
|
140
|
+
// (Quoted text is left as written: `"{PodeHelpers.NEW_LINE}"` inside a string is text, not a constant to put in words.)
|
|
141
|
+
export const plainEnums = (text) => String(text).split(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/).map((part, i) => (i % 2 ? part : plainEnumsOutside(part))).join('');
|
|
142
|
+
const plainEnumsOutside = (text) => String(text).replace(/\b([A-Z][A-Za-z0-9]*)\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, owner, v) => (v.length > 1 && v === v.toUpperCase() && !/^(?:Integer|Long|Short|Byte|Float|Double|Character|Boolean|Void|Number|Math|BigInteger|BigDecimal|Int|UInt|Char)$/.test(owner) ? words(v) : m));
|
|
141
143
|
|
|
142
144
|
/** A condition as words when it can't be fully translated: c.ctx == nil -> "c.ctx is empty". */
|
|
143
145
|
/**
|
|
@@ -196,7 +198,7 @@ function sayAtom(atom) {
|
|
|
196
198
|
const said = sayAtomWords(a);
|
|
197
199
|
// (C and C++ write the empty pointer as NULL or nullptr: for the gate it is null, so `p != nullptr` is "p is set".)
|
|
198
200
|
// (`!strcmp(a, b)` and `strcmp(a, b) == 0` ask whether a is b; the reader says them that way.)
|
|
199
|
-
const gated = C_FAMILY.has(LANG) ? a.replace(/\b(?:nullptr|NULL)\b/g, 'null').replace(/(!\s*)?\b(?:strcmp|strcasecmp
|
|
201
|
+
const gated = C_FAMILY.has(LANG) ? a.replace(/\b(?:nullptr|NULL)\b/g, 'null').replace(/(!\s*)?(?:std::)?\b(?:strcmp|strcasecmp)\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*\)(\s*(==|!=)\s*0\b)?/g, (all, neg, x, y, cmp, op) => (neg || op === '==' ? `${x} == ${y}` : `${x} != ${y}`)) : a;
|
|
200
202
|
// The words are checked against the condition's tree when it parses (exact operators, no strings or comments in
|
|
201
203
|
// the way); otherwise against the text.
|
|
202
204
|
if (said == null || isCodeWords(said) || !accountsFor(gated, said, parseExpr(gated, readingLanguage()))) return null;
|
|
@@ -234,7 +236,7 @@ function sayCodeConditionInner(cond) {
|
|
|
234
236
|
if (C_FAMILY.has(LANG)) {
|
|
235
237
|
c = cNormalize(c).replace(/'\\0'/g, 'the end of the text');
|
|
236
238
|
// C text comparison: `strcmp(a, b) == 0` and `!strcmp(a, b)` are "a is b"; `strcmp(a, b)` alone is "a is not b".
|
|
237
|
-
c = c.replace(/(!\s*)?\b(?:strcmp|strcasecmp
|
|
239
|
+
c = c.replace(/(!\s*)?(?:std::)?\b(?:strcmp|strcasecmp)\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*\)(\s*(==|!=)\s*0\b)?/g, (all, neg, a, b, cmp, op) => (neg || op === '==' ? `${a} == ${b}` : op === '!=' || !cmp ? `${a} != ${b}` : all));
|
|
238
240
|
}
|
|
239
241
|
// Swift `T.self is String.Type` asks whether the type T is String.
|
|
240
242
|
if (LANG === 'swift' && (ty0 = String(c).match(/^([A-Za-z_]\w*)\.self\s+is\s+([A-Za-z_][\w.]*)\.Type$/))) return `${ty0[1]} is the type ${ty0[2]}`;
|
|
@@ -249,6 +251,8 @@ function sayCodeConditionInner(cond) {
|
|
|
249
251
|
// `x instanceof Foo` / `x is Foo` (Kotlin, C#) / isinstance(x, Foo): "x is a Foo".
|
|
250
252
|
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}a ${ty[3].split(/[.\\]/).pop()}`;
|
|
251
253
|
if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}a ${ty[3].split('.').pop()}`;
|
|
254
|
+
// Ruby `x.is_a?(String)` / `kind_of?` / `instance_of?`: "x is a String".
|
|
255
|
+
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.@]+)\.(?:is_a|kind_of|instance_of)\?\s*\(?\s*([A-Z][\w:]*)\s*\)?\s*\)?$/))) return `${possessiveWords(ty[2].replace(/^@/, ''))} is ${ty[1] ? 'not ' : ''}a ${ty[3].split('::').pop()}`;
|
|
252
256
|
if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` : `a ${kinds[0]}`}`; }
|
|
253
257
|
// A bare yes/no property reads as a sentence: `order.refunded` -> "order is refunded", `!user.isAdmin` -> "user is not admin".
|
|
254
258
|
const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
|
|
@@ -303,10 +307,12 @@ function conditionOperatorWords(c) {
|
|
|
303
307
|
return c
|
|
304
308
|
// Strict equality keeps null and undefined apart (a reader must be able to tell `=== null` from `=== undefined`).
|
|
305
309
|
.replace(/\s*===\s*(null|undefined)(?=\s|\)|$)/g, ' is $1').replace(/\s*!==\s*(null|undefined)(?=\s|\)|$)/g, ' is not $1')
|
|
306
|
-
|
|
310
|
+
// (A null check says null, never "is empty": a list or text that is there but empty is not null.)
|
|
311
|
+
.replace(/\s*(?<!!)(===|==)\s*(nil|null|None|undefined|NULL|nullptr)(?=\s|\)|$)/g, (m0, op, v) => ` is ${/^(?:NULL|nullptr)$/.test(v) ? 'null' : v}`)
|
|
312
|
+
.replace(/\s*(?<!!)(===|==)\s*(""|'')(?=\s|\)|$)/g, ' is empty')
|
|
307
313
|
.replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, ' is not empty')
|
|
308
314
|
.replace(/\s*(!==|!=)\s*(nil|null|None|undefined|NULL|nullptr)\b/g, ' is set')
|
|
309
|
-
.replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is
|
|
315
|
+
.replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is None')
|
|
310
316
|
.replace(/\s*(!==|!=)\s*/g, ' is not ').replace(/\s*(===|==)\s*/g, ' is ')
|
|
311
317
|
.replace(/\s*&&\s*/g, ' and ').replace(/\s*\|\|\s*/g, ' or ')
|
|
312
318
|
// Membership: `book not in student.books` -> "book is not in student.books".
|
|
@@ -325,6 +331,9 @@ const lastWords = (path) => words(String(path).split('.').pop());
|
|
|
325
331
|
function targetWords(path) {
|
|
326
332
|
// (C, C++, Swift: an index keeps its place, `events[i].mask` is "the mask of events[i]", never just "events".)
|
|
327
333
|
if ((C_FAMILY.has(LANG) || LANG === 'swift') && /\[[^\]]*\]\s*(?:\.|->)/.test(String(path))) return indexedWords(String(path).replace(/->/g, '.'));
|
|
334
|
+
// (A path that goes on past an index, `@ctx.registers[:site].cache[:url]`, is shown as written: its first two
|
|
335
|
+
// names alone would name a different thing.)
|
|
336
|
+
if (/\][^\]]|\[.*\]$/.test(String(path).trim()) && !/^[@$]?[\w.]+\[\s*['"]?[\w-]+['"]?\s*\]$/.test(String(path).trim())) return `\`${String(path).trim()}\``;
|
|
328
337
|
const parts = String(path).replace(/^[@$]+/, '').replace(/#/g, '').replace(/\[.*$/, '').split('.').filter((p) => !/^(this|self)$/.test(p));
|
|
329
338
|
if (parts.length <= 1) return words(parts[0] || path);
|
|
330
339
|
return `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}`;
|
|
@@ -359,6 +368,13 @@ function firstArgs(text) {
|
|
|
359
368
|
function sayValue(expr) {
|
|
360
369
|
if (/^[A-Z][A-Za-z0-9]*\.[A-Z][A-Z0-9_]+$/.test(stripTail(expr))) return plainEnums(stripTail(expr));
|
|
361
370
|
const e = stripTail(expr).replace(/\s+as\s+[\w.<>\[\]|, ]+$/, '');
|
|
371
|
+
// Rust `Some(v)` / `Ok(v)` hand back v (there is one / it worked); they are not calls.
|
|
372
|
+
let rw;
|
|
373
|
+
if (LANG === 'rust' && (rw = e.match(/^(Some|Ok)\s*\(/)) && closeOf(e, rw[0].length - 1) === e.length - 1) {
|
|
374
|
+
const inner = e.slice(rw[0].length, -1).trim();
|
|
375
|
+
const v = /^\*?[A-Za-z_][\w.]*$|^(["'])(?:\\.|(?!\1)[^\\])*\1$|^-?\d+(?:\.\d+)?$/.test(inner) ? sayValue(inner.replace(/^\*/, '')) : inner === '()' ? 'nothing' : null;
|
|
376
|
+
return v ? `${v}${rw[1] === 'Some' ? ' (Some)' : ' (Ok)'}` : null;
|
|
377
|
+
}
|
|
362
378
|
const py = sayPython(e);
|
|
363
379
|
if (py) return py;
|
|
364
380
|
const common = sayCommon(e);
|
|
@@ -367,7 +383,8 @@ function sayValue(expr) {
|
|
|
367
383
|
if (LANG === 'swift' && /^[A-Z][\w.]*\.init\(/.test(e) && closeOf(e, e.indexOf('(')) === e.length - 1) return `a new ${e.slice(0, e.indexOf('.init(')).split('.').pop()}`;
|
|
368
384
|
// Swift text with values inside: the literal kept exactly, each value a «placeholder» (docs/spec.md).
|
|
369
385
|
if (LANG === 'swift' && /^"/.test(e) && /\\\(/.test(e)) { const tv = swiftTextWithValues(e); if (tv) return tv.length > 90 ? `${tv.slice(0, 88)}…"` : tv; }
|
|
370
|
-
|
|
386
|
+
// Quoted text is kept exactly (its spaces, case, and escapes); a quote character inside keeps its own quotes ('"').
|
|
387
|
+
if (/^(["'`])(?:\\.|(?!\1)[^\\])*\1$/.test(e) && !(/^`/.test(e) && /\$\{/.test(e))) { const inner = e.slice(1, -1); return /"/.test(inner) && e[0] !== '"' ? e : /\n/.test(inner) ? `"${clip(inner, 40)}"` : `"${inner.length > 40 ? `${inner.slice(0, 39)}…` : inner}"`; }
|
|
371
388
|
if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
|
|
372
389
|
if (C_FAMILY.has(LANG) && /^-?(?:0[xX][\da-fA-F]+|\d+(?:\.\d+)?)[uUlLfF]*$/.test(e)) return e.replace(/(?<=\d|[a-fA-F])[uUlLfF]+$/, '').replace(/^(-?\d+(?:\.\d+)?)[uUlLfF]+$/, '$1');
|
|
373
390
|
if (C_FAMILY.has(LANG) && /^(?:NULL|nullptr)$/.test(e)) return 'nothing';
|
|
@@ -395,9 +412,12 @@ function sayValue(expr) {
|
|
|
395
412
|
if (/^[A-Za-z_$][\w$.]*$/.test(e)) {
|
|
396
413
|
const parts = e.replace(/^\$/, '').split('.').filter((p) => !/^(?:self|this)$/.test(p));
|
|
397
414
|
if (parts.length > 1 && /^[A-Z][A-Z0-9_]+$/.test(parts[parts.length - 1])) return parts.slice(-2).join('.');
|
|
415
|
+
// A constant keeps its name (`PATH_MAX`): "path max" would read as the variable path_max.
|
|
416
|
+
if (parts.length === 1 && /^[A-Z][A-Z0-9]*_[A-Z0-9_]+$/.test(parts[0])) return parts[0];
|
|
398
417
|
return parts.length > 1 ? possessiveWords(parts.join('.')) : words(parts[0] ?? e);
|
|
399
418
|
}
|
|
400
|
-
|
|
419
|
+
// (An index inside the path keeps the path as written: `cache[input].dup` is not "the input's dup".)
|
|
420
|
+
if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return /\]/.test(e) && !C_FAMILY.has(LANG) && LANG !== 'swift' ? `\`${e}\`` : possessiveWords(e);
|
|
401
421
|
return null;
|
|
402
422
|
}
|
|
403
423
|
|
|
@@ -470,7 +490,8 @@ function sayCommon(value) {
|
|
|
470
490
|
// Ruby `if a then b else c end`.
|
|
471
491
|
const ifValue = ifAsValue(e);
|
|
472
492
|
if (ifValue) return choice(ifValue.yes, ifValue.cond, ifValue.no);
|
|
473
|
-
|
|
493
|
+
// (Only when the new value is the whole expression: `Builder::new().x(1).build()` is what build makes, not a builder.)
|
|
494
|
+
if (((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) && [-1, (LANG === "rust" ? e.replace(/(?:\.unwrap\(\)|\?)$/, "") : e).length - 1].includes(closeOf(e, m[0].length - 1))) return `a new ${m[1]}`;
|
|
474
495
|
if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
|
|
475
496
|
if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
|
|
476
497
|
if ((m = e.match(/^[\w.]+\.(?:get|get_or_404|find|Find|findById|find_by_id)\(\s*([A-Z]\w*)\s*,\s*([\w.]+)\s*\)$/))) return `the ${m[1]} with ${lastSeg(m[2])}`;
|
|
@@ -478,21 +499,23 @@ function sayCommon(value) {
|
|
|
478
499
|
const wholeCall = (() => { const c = e.match(/^(?:new\s+)?[\w$.]+(?:<[^()]*?>)?\s*\(/); return !!c && closeOf(e, c[0].length - 1) === e.length - 1; })();
|
|
479
500
|
if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e) && !wholeCall) return 'text built from its parts';
|
|
480
501
|
// PHP joins text with ` . ` (spaced when PHP is read): `$a . ':' . $b`.
|
|
481
|
-
if (/\s\.\s/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q')) && !/[<>=!&|?]/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'))) return 'text built from its parts';
|
|
502
|
+
if (!wholeCall && /\s\.\s/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q')) && !/[<>=!&|?]/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'))) return 'text built from its parts';
|
|
482
503
|
if ((m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/))) return e.split(/\s*,\s*/).map(lastSeg).join(' and ');
|
|
483
|
-
|
|
504
|
+
// (`make([]string, len(m))` has len(m) items, each the empty value; only `make([]T, 0…)` is empty.)
|
|
505
|
+
if ((m = e.match(/^make\(\s*(\[\]|map\[)/))) { const a = splitTopArgs(e.slice(e.indexOf('(') + 1, -1)); if (m[1] === '[]' && a.length > 1 && !/^0$/.test(a[1].trim())) return null; return m[1] === '[]' ? 'an empty list' : 'an empty lookup table'; }
|
|
484
506
|
if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return 'text built from its parts';
|
|
485
507
|
if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
486
508
|
if ((m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
487
509
|
if (FN_CONTEXT?.language === 'ruby' && (m = e.match(/^@?([\w.]+)\[\s*:(\w+)\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
488
510
|
if ((m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/))) return `${lastSeg(m[1])} split at "${m[2]}"`;
|
|
489
511
|
if ((m = e.match(/^@?([\w.]+?)(?:\.copy|\.clone|\.Clone|\.dup)(?:\(\))?$/))) return `a copy of ${lastSeg(m[1])}`;
|
|
512
|
+
if ((m = e.match(/^@?([\w.]+\[[^\[\]]+\])(?:\.copy|\.clone|\.Clone|\.dup)(?:\(\))?$/))) return `a copy of \`${m[1]}\``;
|
|
490
513
|
if ((m = e.match(/^(?:str|String|string)\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:toString\(\)|to_s(?:\(\))?|ToString\(\))$/))) return `${lastSeg(m[1])} as text`;
|
|
491
514
|
if ((m = e.match(/^(?:int|float|Number|parseInt|parseFloat|strconv\.Atoi|Integer\.parseInt|int\.Parse)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} as a number`;
|
|
492
515
|
if ((m = e.match(/^(?:JSON\.parse|json\.loads|json\.load|JsonSerializer\.Deserialize\w*)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} read as JSON`;
|
|
493
516
|
if ((m = e.match(/^(?:JSON\.stringify|json\.dumps|JsonSerializer\.Serialize)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} written as JSON`;
|
|
494
|
-
if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)\
|
|
495
|
-
if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)\
|
|
517
|
+
if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty lookup table';
|
|
518
|
+
if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty list';
|
|
496
519
|
if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
|
|
497
520
|
return null;
|
|
498
521
|
}
|
|
@@ -512,13 +535,46 @@ function ifAsValue(e) {
|
|
|
512
535
|
return null;
|
|
513
536
|
}
|
|
514
537
|
|
|
538
|
+
/** The text with every bracketed group (and quoted text) replaced by one placeholder: what is left is top level. */
|
|
539
|
+
const topLevel = (e) => { let t = String(e).replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'); for (let k = 0; k < 20 && /\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}/.test(t); k++) t = t.replace(/\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}/g, 'P'); return t; };
|
|
540
|
+
/** One part of an and / or that is plainly a yes/no: a comparison, a negation, true/false, or a yes/no name or call. */
|
|
541
|
+
function boolish(term) {
|
|
542
|
+
let t = String(term).trim();
|
|
543
|
+
while (wrapped(t)) t = t.slice(1, -1).trim();
|
|
544
|
+
if (/^(?:!|not\s)/.test(t) || /^(?:true|false|True|False)$/.test(t)) return true;
|
|
545
|
+
const parts = splitLogic(t);
|
|
546
|
+
if (parts && parts.terms.length > 1) return parts.terms.every(boolish);
|
|
547
|
+
const top = topLevel(t);
|
|
548
|
+
if (/[=!]==?|<=|>=|(?<![-=<])<(?![<=-])|(?<![-=>])>(?![>=])|\binstanceof\b|\bis\b|\bin\b|\bnot in\b/.test(top)) return true;
|
|
549
|
+
return /(?:^|\.)(?:is|has|can|should|was|are|does|did|will|needs?|allows?|includes|contains|starts[Ww]ith|ends[Ww]ith|matches|test|exists?|isEmpty|isNaN|isArray|empty\??)(?:[A-Z_]\w*)?\s*(?:\(.*\))?\??$/.test(t) || /\w\?(?:\(.*\))?$/.test(t);
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* True when an and / or gives back one of its values, not yes or no: in JavaScript, Python, and Ruby
|
|
553
|
+
* `queue || []` is the queue (or a new list), and `x or default` is x when it has a value.
|
|
554
|
+
*/
|
|
555
|
+
function valueLogic(e) {
|
|
556
|
+
if (!/^(?:javascript|typescript|python|ruby)$/.test(LANG)) return false;
|
|
557
|
+
let t = String(e).trim();
|
|
558
|
+
while (wrapped(t)) t = t.slice(1, -1).trim();
|
|
559
|
+
const parts = splitLogic(t);
|
|
560
|
+
if (!parts || parts.terms.length < 2) return false;
|
|
561
|
+
// `a && b` gives back b when a holds: it is yes or no when b is. `a || b` is yes or no when every part is.
|
|
562
|
+
if (parts.ops.every((o) => o === 'and')) return !boolish(parts.terms[parts.terms.length - 1]);
|
|
563
|
+
return !parts.terms.every(boolish);
|
|
564
|
+
}
|
|
565
|
+
|
|
515
566
|
/** A boolean expression (comparison or logic), said as a yes/no question. */
|
|
516
567
|
const LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
|
|
517
568
|
function sayWhether(expr) {
|
|
518
569
|
const e = String(expr).trim();
|
|
519
|
-
|
|
570
|
+
// (Type arguments are not comparisons: `.filterIsInstance<Dns.Record>()` gives back a list.)
|
|
571
|
+
const noGenerics = e.replace(/([\w$])<[\w.?, <>\[\]*]*>(?=\s*[(.:]|\s*$)/g, '$1');
|
|
572
|
+
if (!LOGIC.test(noGenerics.replace(/->/g, '.')) || /=>|\blambda\b|\s\?\s.*:/.test(e)) return null;
|
|
573
|
+
if (valueLogic(e)) return null;
|
|
574
|
+
// (An assignment inside the value, `(cache ||= {})`, gives back what is stored: not yes or no.)
|
|
575
|
+
if (/\|\|=|&&=|\?\?=|[-+*/%]=|(?<![=!<>:])=(?![=>~])/.test(topLevel(e).replace(/^\((.*)\)$/, '$1')) || /\|\|=|&&=|\?\?=/.test(e)) return null;
|
|
520
576
|
// (`bin_sig << 4` shifts bits: it is not a comparison.)
|
|
521
|
-
if (
|
|
577
|
+
if (/<<|>>/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'))) return null;
|
|
522
578
|
// (A Swift range `a..<b` is not a comparison, and `(a, b)` is two values, not one yes/no.)
|
|
523
579
|
if (LANG === 'swift' && (/\.\.[.<]/.test(e) || splitTopArgs(e.replace(/^\((.*)\)$/, '$1')).length > 1)) return null;
|
|
524
580
|
const said = sayCodeCondition(e);
|
|
@@ -555,7 +611,8 @@ function nextKind() {
|
|
|
555
611
|
/** Classify one statement (its first line or header). Returns { kind, says, code } where code is the original text. */
|
|
556
612
|
const CHAIN = [
|
|
557
613
|
{ re: /\.(?:map|Select|flatMap|SelectMany|map_values|collect\{)\s*[({]/, say: (src) => `one for each item in ${src}` },
|
|
558
|
-
{ re: /\.(?:
|
|
614
|
+
{ re: /\.(?:reject|filterNot|exclude|delete_if|reject!)\s*[({]/, say: (src) => `the items in ${src} that do not match` },
|
|
615
|
+
{ re: /\.(?:filter|Where|filter_map|select|grep)\s*[({]/, say: (src) => `the items in ${src} that match` },
|
|
559
616
|
{ re: /\.(?:find|First|FirstOrDefault|find_first|detect)\s*[({]/, say: (src) => `the first item in ${src} that matches` },
|
|
560
617
|
{ re: /\.(?:some|Any|any)\s*[({]/, say: (src) => `whether any item in ${src} matches` },
|
|
561
618
|
{ re: /\.(?:every|All|all)\s*[({]/, say: (src) => `whether every item in ${src} matches` },
|
|
@@ -668,7 +725,7 @@ function cNormalize(head) {
|
|
|
668
725
|
.replace(/(\w|\))->(?=[A-Za-z_])/g, '$1.')
|
|
669
726
|
.replace(/\((?:const\s+)?(?:unsigned\s+|signed\s+|struct\s+|enum\s+)?(?:void|char|int|long|short|float|double|size_t|ssize_t|u?int\d+_t|bool|unsigned|[A-Za-z_]\w*\s*\*+)\s*\)\s*(?=[\w(&*"'])/g, '')
|
|
670
727
|
.replace(/^\*+\s*(?=[A-Za-z_][\w.]*\s*(?:[-+*/|&]?=)(?!=))/, '')
|
|
671
|
-
.replace(/\b(?:
|
|
728
|
+
.replace(/\b(?:reinterpret|const|dynamic)_cast\s*<[^<>()]*(?:<[^<>()]*>[^<>()]*)*>\s*\(\s*([\w.]+)\s*\)/g, '$1');
|
|
672
729
|
}
|
|
673
730
|
|
|
674
731
|
const NOT_A_TYPE = /^(?:return|throw|yield|await|new|delete|case|goto|else|typeof|let|const|var|val|if|for|while|do|switch|using|namespace|typedef|public|private|protected|def|func|fn|fun|import|export|from|echo|print|puts|go|defer|not|and|or|in|is|as|of|mut|ref|out|static|final|readonly|unless|until|when|guard|try|catch|sizeof|template|operator|class|struct|enum|union|co_return|co_await|raise|assert|super|this|self)$/;
|
|
@@ -745,6 +802,8 @@ function sayCLibrary(head) {
|
|
|
745
802
|
/** Swift and C++ make a value by calling its type (`Request()`, `Response.Body(…)`, `std::string(s)`). */
|
|
746
803
|
// (Apple's C functions are named like types but are calls: SecPolicyCreateSSL, CFStringCreateCopy, CGRectMake.)
|
|
747
804
|
const C_STYLE_FUNCTION = /[a-z0-9](?:Create|Copy|Get|Make|Set)(?:[A-Z0-9]\w*)?$/;
|
|
805
|
+
/** True when the called name is the declared type itself (`Foo f = Foo(…)`, `auto` excepted). */
|
|
806
|
+
const sameType = (c, type) => !!type && !/^(?:auto|var)$/.test(type) && String(c).split(/\.|::/).pop() === String(type).replace(/<.*$/, '').split('::').pop();
|
|
748
807
|
const makesType = (c) => (LANG === 'swift' || LANG === 'cpp') && /^(?:[A-Z]\w*\.)*[A-Z]\w*$/.test(String(c || '')) && !/^[A-Z][A-Z0-9_]+$/.test(String(c).split('.').pop()) && !C_STYLE_FUNCTION.test(String(c).split('.').pop());
|
|
749
808
|
|
|
750
809
|
/** Vapor's HTTP status names (`Abort(.notFound)`) and their numbers. */
|
|
@@ -764,6 +823,8 @@ function swiftCondition(cond) {
|
|
|
764
823
|
return parts.filter(Boolean).map((p) => {
|
|
765
824
|
let m;
|
|
766
825
|
if ((m = p.match(/^(?:let|var)\s+(\w+)(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/))) return `${words(m[1])} is set`;
|
|
826
|
+
// `case KingfisherError.responseError = context.error`: that one case of the type, not any value of it.
|
|
827
|
+
if ((m = p.match(/^case\s+(?:let\s+|var\s+)?([A-Z]\w*(?:\.[A-Z]\w*)*)\.([a-z]\w*)(?:\s*\([^()]*\))?\s*=\s*(.+)$/)) && /^[\w.]+$/.test(m[3].trim())) return `${possessiveWords(m[3].trim())} is ${m[1]}.${m[2]}`;
|
|
767
828
|
if ((m = p.match(/^case\s+(?:let\s+|var\s+)?\.?(\w+)(?:\s*\([^()]*\))?\s*=\s*(.+)$/)) && /^[\w.]+$/.test(m[2].trim())) return `${possessiveWords(m[2].trim())} is ${words(m[1])}`;
|
|
768
829
|
if ((m = p.match(/^case\s+(?:let\s+|var\s+)?\.?(\w+)/))) return `it is ${words(m[1])}`;
|
|
769
830
|
return sayCodeCondition(p);
|
|
@@ -815,6 +876,12 @@ function sayNativeShape(head, text, innerNote) {
|
|
|
815
876
|
return { kind: 'loop', says: `Counts ${words(m[1])} ${r.says}${innerNote}` };
|
|
816
877
|
}
|
|
817
878
|
}
|
|
879
|
+
// `for x in xs where cond {`: only the items for which cond holds.
|
|
880
|
+
if (swift && (m = head.match(/^for\s+(?:case\s+)?(?:let\s+)?([\w]+)\s+in\s+(.+?)\s+where\s+(.+?)\s*\{?\s*$/)) && balancedText(m[2])) {
|
|
881
|
+
const src = /^[\w.]+$/.test(m[2]) ? possessiveWords(m[2]) : `\`${m[2]}\``;
|
|
882
|
+
const c = sayCodeCondition(m[3]);
|
|
883
|
+
return { kind: 'loop', says: `For each ${words(m[1])} in ${src}, only those where ${c}${innerNote}` };
|
|
884
|
+
}
|
|
818
885
|
if (swift && (m = head.match(/^for\s+_\s+in\s+([\w.]+)\s*\{?\s*$/))) return { kind: 'loop', says: `Repeats once for each item in ${possessiveWords(m[1])}${innerNote}` };
|
|
819
886
|
if (swift && (m = head.match(/^while\s+(?:let|var)\s+(\w+)\s*=/))) return { kind: 'loop', says: `Repeats while there is a next ${words(m[1])}${innerNote}` };
|
|
820
887
|
// guard cond else { … }: the else block is the way out; the steps after it run only when the condition holds.
|
|
@@ -1145,8 +1212,16 @@ const stripQuotedText = (s) => String(s).replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g
|
|
|
1145
1212
|
* (thunder-expr-v1, see meaning.mjs): every name, argument, and value, or `{ kind: 'code', text }` when the statement
|
|
1146
1213
|
* is not fully understood. The words stay short; `expr` keeps everything one level down.
|
|
1147
1214
|
*/
|
|
1215
|
+
// Words that start a block or a statement: "Calls unsafe" / "Calls using" / "Calls foreach" would name a function
|
|
1216
|
+
// that does not exist, so such a step is shown as its code instead.
|
|
1217
|
+
const NOT_CALLED = /^Calls (unsafe|using|foreach|for|while|if|else|return|lock|fixed|checked|unchecked|try|do|switch|match|loop|static|const|let|var|val|mut|typeof|sizeof)$/;
|
|
1148
1218
|
export function classifyStatement(raw, opts) {
|
|
1149
|
-
|
|
1219
|
+
// Rust `unsafe { f(x) }` (and `return unsafe { … }`) with one expression inside is that expression.
|
|
1220
|
+
const un = LANG === 'rust' ? String(raw).trim().match(/^(return\s+)?unsafe\s*\{\s*([^{};]+?)\s*;?\s*\}\s*;?$/s) : null;
|
|
1221
|
+
if (un) { const r = classifyStatement(`${un[1] ?? ''}${un[2]}`, opts); return { ...r, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) }; }
|
|
1222
|
+
let r = classifyWords(raw, opts);
|
|
1223
|
+
const nc = r.kind === 'call' && String(r.says || '').match(NOT_CALLED);
|
|
1224
|
+
if (nc && new RegExp(`^(?:#\\w+\\s+)?${nc[1]}\\b(?![.(?!])`).test(String(raw).trim().replace(/^#.*\n\s*/, ''))) r = { kind: 'other', says: clip(String(raw).trim(), 70), code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) };
|
|
1150
1225
|
if (!r.expr) r.expr = statementExpr(raw);
|
|
1151
1226
|
return r;
|
|
1152
1227
|
}
|
|
@@ -1169,6 +1244,13 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1169
1244
|
const o = text.indexOf('('), c = closeOf(text, o);
|
|
1170
1245
|
if (c > 0 && c < 2000) first = `${text.slice(0, c + 1)}${text.slice(c + 1).split('\n')[0]}`.replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').trim();
|
|
1171
1246
|
}
|
|
1247
|
+
// Go and Rust write a condition with no brackets, which can go on over lines (`if a ||\n b {`): read it whole.
|
|
1248
|
+
if (/^(?:if|else\s+if|for|switch|while)\b/.test(first) && !/\{\s*$/.test(first) && /(?:\|\||&&|[,(+\-*/<>=!])\s*$/.test(first) && text.includes('\n')) {
|
|
1249
|
+
const lines = text.split('\n');
|
|
1250
|
+
let acc = lines[0].trim();
|
|
1251
|
+
for (let j = 1; j < lines.length && j < 12 && !/\{\s*$/.test(acc); j++) acc += ` ${lines[j].trim()}`;
|
|
1252
|
+
if (/\{\s*$/.test(acc)) first = acc;
|
|
1253
|
+
}
|
|
1172
1254
|
// A brace-less `if (x)` whose one statement is on the next line(s): `if (a)\n throw new E(…);` is one step.
|
|
1173
1255
|
if (/^(?:if|else\s+if)\s*\(/.test(text) && text.includes('\n')) {
|
|
1174
1256
|
const o = text.indexOf('('), c = closeOf(text, o);
|
|
@@ -1186,16 +1268,24 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1186
1268
|
}
|
|
1187
1269
|
// An annotation line (`@Override`) belongs to the declaration under it.
|
|
1188
1270
|
let jmp;
|
|
1271
|
+
// A bare `raise` (Python, Ruby) or `throw;` (C#, C++) passes on the error being handled: the function stops there,
|
|
1272
|
+
// it gives nothing back.
|
|
1273
|
+
// A name set to text written over several lines (`let haystack = "\` … `";`): its lines are text, not steps.
|
|
1274
|
+
const mls = text.match(/^(?:let(?:\s+mut)?|const|var|val)\s+([A-Za-z_]\w*)(?:\s*:[^=\n]+)?\s*=\s*(?:r#*)?("""|")/);
|
|
1275
|
+
if (mls && text.includes('\n') && !text.split('\n')[0].slice(mls[0].length).includes('"') && /"#*\s*;?$/.test(text)) return { kind: 'set', says: `Sets ${words(mls[1])} to a text written over several lines`, code: clip(text.split('\n')[0], 90) };
|
|
1276
|
+
if (!C_FAMILY.has(LANG) && /^(?:raise|throw)\s*;?$/.test(text)) return { kind: 'fail', says: 'Fails with the same error again (passes it on)', code: text, error: 'the same error' };
|
|
1189
1277
|
if ((jmp = text.match(/^(continue|break)(?:\s+([A-Za-z_]\w*))?;?$/))) return { kind: 'call', says: jmp[1] === 'break' ? `Leaves the loop${jmp[2] ? ` (${jmp[2]})` : ''}` : `Skips to the next one${jmp[2] ? ` (${jmp[2]})` : ''}`, code: text, jump: jmp[1] };
|
|
1190
1278
|
if (/^@\w+(?:\([^)]*\))?$/.test(first) && text.includes('\n')) first = text.split('\n').map((l) => l.trim()).find((l) => l && !/^@\w+(?:\([^)]*\))?$/.test(l)) ?? first;
|
|
1191
1279
|
// TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
|
|
1192
1280
|
// (PHP `foreach ($a as $k => $v)` is a loop, not a cast.)
|
|
1193
1281
|
let head = (/^foreach\b/.test(first) ? first : first
|
|
1194
|
-
.replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1$2').replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1($2)')).replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
|
|
1282
|
+
.replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1$2').replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1($2)')).replace(/([\w$\])])!(?=[.(\[])/g, LANG === 'rust' ? '$1!' : '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
|
|
1195
1283
|
// Java/C# casts: ((JsonTreeReader) reader).promote() -> reader.promote(); (int) x -> x
|
|
1196
1284
|
.replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1')
|
|
1197
1285
|
// .NET: `.ConfigureAwait(false)` only says which thread carries on; it changes nothing a reader needs.
|
|
1198
1286
|
.replace(/\.ConfigureAwait\(\s*(?:false|true)\s*\)/g, '');
|
|
1287
|
+
// Rust `static MSG: &str = "…";` / `const N: usize = 4;` inside a body names a fixed value; it calls nothing.
|
|
1288
|
+
if (LANG === 'rust') head = head.replace(/^(?:static|const)\s+(?:mut\s+)?([A-Za-z_]\w*)\s*:\s*[^=]+?=\s*/, 'let $1 = ');
|
|
1199
1289
|
// (C, C++, and Swift show the code exactly as written: `window!.root` stays `window!.root`.)
|
|
1200
1290
|
const code = clip(C_FAMILY.has(LANG) || LANG === 'swift' ? first : head, 90);
|
|
1201
1291
|
let m;
|
|
@@ -1220,6 +1310,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1220
1310
|
// Swift marks a call that can fail with `try` (and one that waits with `await`): the step is the call itself.
|
|
1221
1311
|
if (LANG === 'swift' && !/^do\b/.test(head)) head = head.replace(/^(return\s+)?(?:(?:try[?!]?|await)\s+)+/, '$1').replace(/(\w|\))\?(?=\()/g, '$1');
|
|
1222
1312
|
if (LANG === 'swift' && /^self\.init\s*\(/.test(head)) return { kind: 'call', says: 'Sets up the way another init does', code };
|
|
1313
|
+
let declType = null;
|
|
1223
1314
|
const cdecl = C_FAMILY.has(LANG) ? cDeclaration(head) : null;
|
|
1224
1315
|
if (cdecl) {
|
|
1225
1316
|
if (cdecl.value == null) return { kind: 'set', says: `Declares ${words(cdecl.name)}`, code };
|
|
@@ -1231,6 +1322,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1231
1322
|
return { kind: 'set', says: cdecl.array ? `Sets ${words(cdecl.name)} to a list of values` : keys.length ? `Sets ${words(cdecl.name)} to a new ${what} with ${listWords(keys.length > 4 ? [...keys.slice(0, 4), 'more'] : keys)}` : `Sets ${words(cdecl.name)} to a new ${what}`, code };
|
|
1232
1323
|
}
|
|
1233
1324
|
head = `var ${cdecl.name} = ${cdecl.value}`;
|
|
1325
|
+
declType = cdecl.type;
|
|
1234
1326
|
}
|
|
1235
1327
|
const cSays = C_FAMILY.has(LANG) ? sayCLibrary(head) : null;
|
|
1236
1328
|
if (cSays) return { ...cSays, code };
|
|
@@ -1250,7 +1342,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1250
1342
|
return { kind: 'branch', says: `If ${sayCodeCondition(cond)}`, cond, code, inline: body };
|
|
1251
1343
|
}
|
|
1252
1344
|
}
|
|
1253
|
-
if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/\[[^\]]*\bfor\b/.test(head)) {
|
|
1345
|
+
if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && balancedText(inl[1]) && balancedText(inl[3]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/\[[^\]]*\bfor\b/.test(head)) {
|
|
1254
1346
|
const cond = sayCodeCondition(inl[3]);
|
|
1255
1347
|
return { kind: 'branch', says: inl[2] === 'unless' ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === 'unless', code, inline: inl[1] };
|
|
1256
1348
|
}
|
|
@@ -1337,7 +1429,12 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1337
1429
|
const msg = firstText(expr);
|
|
1338
1430
|
return { kind: 'fail', says: `Returns an error${msg ? `: "${msg}"` : ''}`, code };
|
|
1339
1431
|
}
|
|
1432
|
+
// `return (@cache[:k] ||= {})` gives back what is stored there, set first when there is nothing yet.
|
|
1433
|
+
const memo = expr.replace(/^\((.*)\)$/, '$1').match(/^([@$]?[A-Za-z_][\w.@]*(?:\[[^\]]+\][\w.]*)*)\s*(\|\|=|\?\?=)\s*(.+)$/);
|
|
1434
|
+
if (memo && balancedText(memo[3])) { const v = sayValue(memo[3].trim()) ?? sayArithmetic(memo[3].trim()); return v ? { kind: 'return', says: `Returns ${targetWords(memo[1])}, first set to ${v} if it has no value yet`, code } : { kind: 'return', says: 'Returns a computed value', code, value: clip(expr, 60) }; }
|
|
1340
1435
|
const terms = splitLogic(expr);
|
|
1436
|
+
// `return queue || []` gives back the queue (or a new list), not yes or no.
|
|
1437
|
+
if (terms && terms.terms.length > 1 && valueLogic(expr)) { const fb = fallbackWords(expr); return fb ? { kind: 'return', says: `Returns ${fb}`, code } : { kind: 'return', says: 'Returns a computed value', code, value: clip(expr, 60) }; }
|
|
1341
1438
|
if (terms && terms.terms.length > 1) {
|
|
1342
1439
|
// `return a && b`: every part is said, or the code is shown; never only the first part.
|
|
1343
1440
|
const w = sayWhether(expr);
|
|
@@ -1364,20 +1461,22 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1364
1461
|
// A C-style loop with no counter of its own: `for (; pos < limit; i++)` / `for (;;)`.
|
|
1365
1462
|
if ((m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
|
|
1366
1463
|
// Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
|
|
1367
|
-
if ((m = head.match(/^for\b\s*\(?\s*(?:(?:const|let|var|val)\s+)
|
|
1464
|
+
if ((m = head.match(/^for\b\s*\(?\s*(?:(?:const|let|var|val)\s+)?&?[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
|
|
1368
1465
|
const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries|enumerated)\(\)$/, '');
|
|
1369
1466
|
return { kind: 'loop', says: `For each ${words(m[1])} and ${words(m[2])} in ${words(src.split('.').pop())}${innerNote}`, code };
|
|
1370
1467
|
}
|
|
1371
1468
|
if ((m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
|
|
1372
1469
|
return { kind: 'loop', says: `For each ${words(m[1].split(',').pop().trim())} in ${words(stripTail(m[2]).split('.').pop().replace(/\(\)$/, ''))}${innerNote}`, code };
|
|
1373
1470
|
}
|
|
1374
|
-
if ((m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/))) return { kind: 'loop', says: `For each item in ${words(stripTail(m[1]).split('.').pop())}${innerNote}`, code };
|
|
1471
|
+
if ((m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/))) return { kind: 'loop', says: `For each item in ${/^[A-Za-z_][\w.]*$/.test(stripTail(m[1])) ? targetWords(stripTail(m[1])) : words(stripTail(m[1]).split('.').pop())}${innerNote}`, code };
|
|
1375
1472
|
if ((m = head.match(/^(?:await\s+)?foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[1])} in ${words(m[2].split('.').pop())}${innerNote}`, code };
|
|
1376
1473
|
if ((m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:&?(\w+)\s*=>\s*)?&?(\w+)\s*\)\s*\{?$/))) return { kind: 'loop', says: `For each ${m[2] ? `${words(m[2])} and ` : ''}${words(m[3])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
|
|
1377
1474
|
// Ruby one-line blocks: `items.each { |e| e.save if e.dirty? }` is a loop whose step is the block's body.
|
|
1378
1475
|
if ((m = head.match(/^([\w.@]+(?:\([^()]*\))?)\.each(?:_with_index)?\s*\{\s*\|([^|]*)\|\s*(.+?)\s*\}$/))) return { kind: 'loop', says: `For each ${m[2].split(',').map((x) => words(x.replace(/^[*&]+/, '').trim())).join(', ')} in ${words(m[1].replace(/\(.*$/, '').replace(/^@/, '').split('.').pop())}`, code, inline: m[3] };
|
|
1379
1476
|
if ((m = head.match(/^@?([\w.]+(?:\([^()]*\))?)\.each(?:_with_index)?\s+do\s*\|(\w+)/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].replace(/\(.*$/, '').split('.').pop())}${innerNote}`, code };
|
|
1380
1477
|
if ((m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/))) return { kind: 'loop', says: `For each item in ${words(m[1].split('.').pop())}${innerNote}`, code };
|
|
1478
|
+
// Go `for {` repeats until something inside leaves the loop (or the function).
|
|
1479
|
+
if (/^for\s*\{$/.test(head)) return { kind: 'loop', says: `Repeats until something inside leaves the loop${innerNote}`, code };
|
|
1381
1480
|
if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
|
|
1382
1481
|
// Branches
|
|
1383
1482
|
// Go: `if err := open(); err != nil` -> "If open fails"; `if v, ok := m[k]; ok` -> "If k is in m".
|
|
@@ -1427,7 +1526,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1427
1526
|
// were dropped.)
|
|
1428
1527
|
if ((m = head.match(/^(?:async\s+)?with\s+(.+?):\s*$/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
|
|
1429
1528
|
if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
|
|
1430
|
-
if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version
|
|
1529
|
+
if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version', code };
|
|
1431
1530
|
// yield: in C# (`yield return x`), Python, and JavaScript generators it hands back one more value; in Ruby, bare
|
|
1432
1531
|
// `yield` runs the block the caller gave.
|
|
1433
1532
|
let y;
|
|
@@ -1436,7 +1535,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1436
1535
|
}
|
|
1437
1536
|
if (/^yield\s+break\b/.test(head)) return { kind: 'return', says: 'Stops giving back values', code, yields: true };
|
|
1438
1537
|
if (/^yield\b/.test(head)) return { kind: 'call', says: 'Hands control to the given block', code };
|
|
1439
|
-
if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
|
|
1538
|
+
if (((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) && !(closeOf(text, text.indexOf("{")) > 0 && text.slice(closeOf(text, text.indexOf("{")) + 1).trim())) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
|
|
1440
1539
|
if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
|
|
1441
1540
|
if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
|
|
1442
1541
|
// A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
|
|
@@ -1474,7 +1573,8 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1474
1573
|
if (c && wholeValueCall(value)) {
|
|
1475
1574
|
const known = sayCall(c, firstArgs(value));
|
|
1476
1575
|
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
1477
|
-
|
|
1576
|
+
// (C++: `Status s = FindTable(…)` calls FindTable; only `Foo f = Foo(…)` makes a new Foo.)
|
|
1577
|
+
if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, m[1])))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
1478
1578
|
return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
|
|
1479
1579
|
}
|
|
1480
1580
|
const v = value ? sayValue(value) : null;
|
|
@@ -1517,13 +1617,15 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1517
1617
|
if (m[2] === '.=') { const v = valueWords(value); return { kind: 'set', says: v ? `Adds ${v} to the end of ${target}` : `Adds to the end of ${target}`, code }; }
|
|
1518
1618
|
if (m[2] === '%=' || m[2] === '&&=') return { kind: 'other', says: clip(head, 70), code };
|
|
1519
1619
|
// A yes/no value: `ok = proxy and scheme != "https"` -> "Works out ok: whether proxy and scheme is not https".
|
|
1520
|
-
if (m[2] === '=' && fb == null && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(
|
|
1620
|
+
if (m[2] === '=' && fb == null && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && !valueLogic(value) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(topLevel(value.replace(/^\((.*)\)$/, '$1')).replace(/->|=>/g, '.')) && !/=>/.test(value) && !((C_FAMILY.has(LANG) || LANG === 'swift') && /<<|>>/.test(stripQuotedText(value)))) return { kind: 'set', says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
|
|
1521
1621
|
// self.max_books = max_books: the Thing keeps what it was given.
|
|
1522
1622
|
if (m[2] === '=' && /^[A-Za-z_]\w*$/.test(value) && m[1].split('.').pop() === value && /^(self|this)\./.test(m[1])) {
|
|
1523
1623
|
// Only an input is "given": a value made in this function is kept, not given (C, C++, Swift check the inputs).
|
|
1524
1624
|
const given = !(C_FAMILY.has(LANG) || LANG === 'swift') || !FN_CONTEXT?.params || FN_CONTEXT.params.some((p) => p.name === value);
|
|
1525
1625
|
return { kind: 'set', says: given ? `Keeps the ${words(value)} it is given` : `Keeps ${words(value)} as its own ${words(value)}`, code };
|
|
1526
1626
|
}
|
|
1627
|
+
// `bytesSent += chunk.length` adds to a running total: never "Sets bytes sent to …".
|
|
1628
|
+
if ((m[2] === '+=' || m[2] === '-=') && value) { const v = /^[\w.]+$/.test(value) && !/^\d/.test(value) ? value.split('.').filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words).join(' ') : valueWords(value) ?? sayCommon(value); const add = m[2] === '+='; return { kind: 'set', says: v ? `${add ? 'Adds' : 'Subtracts'} ${v} ${add ? 'to' : 'from'} ${target}` : `${add ? 'Adds to' : 'Subtracts from'} ${target}`, code }; }
|
|
1527
1629
|
const chain = value ? (sayPython(value) || sayChain(value)) : null;
|
|
1528
1630
|
if (chain) return { kind: 'set', says: `Works out ${target}: ${chain}`, code };
|
|
1529
1631
|
const common = value ? sayCommon(m[3].trim().replace(/;$/, '')) || sayCommon(value) : null;
|
|
@@ -1533,7 +1635,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1533
1635
|
if (c && wholeValueCall(value)) {
|
|
1534
1636
|
const known = sayCall(c, firstArgs(value));
|
|
1535
1637
|
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
1536
|
-
if (/^new\s/.test(value) || makesType(c)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
1638
|
+
if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, declType)))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
1537
1639
|
return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
|
|
1538
1640
|
}
|
|
1539
1641
|
if (!value) return { kind: 'set', says: `Works out ${target}`, code };
|
|
@@ -1914,7 +2016,7 @@ export function stepsFrom(statements) {
|
|
|
1914
2016
|
steps.push(arm);
|
|
1915
2017
|
continue;
|
|
1916
2018
|
}
|
|
1917
|
-
if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
|
|
2019
|
+
if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b(?!\s*(?:[-+*/%|&^]?=(?!=)|\+\+|--|\(|\[|->))|#)/.test(t0)) {
|
|
1918
2020
|
const st = stepsFrom([s]).steps;
|
|
1919
2021
|
into.push(...st);
|
|
1920
2022
|
// Earlier lines of a handler are calls; nothing in `ensure` is the value given back.
|
|
@@ -1943,8 +2045,16 @@ export function stepsFrom(statements) {
|
|
|
1943
2045
|
const prev = prev2;
|
|
1944
2046
|
const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? 'elif' : /^else\b/.test(t0) ? 'else' : /^(?:finally|ensure)\b/.test(t0) ? 'finally' : 'catch';
|
|
1945
2047
|
const inlineElse = kw === 'else' && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
|
|
1946
|
-
|
|
1947
|
-
|
|
2048
|
+
let clauseKids = inlineElse ? [{ text: inlineElse[1], line: s.line, endLine: s.line }, ...(s.children || [])] : s.children || [];
|
|
2049
|
+
let clauseHead = t0.replace(/:\s*$/, '');
|
|
2050
|
+
// A brace-less `else if (x)\n stmt;` (C, Java, JavaScript, …): the statement after the brackets is its side.
|
|
2051
|
+
const eo = kw === 'elif' && !s.children?.length ? t0.match(/^(?:\}\s*)?else\s+if\s*\(/) : null;
|
|
2052
|
+
if (eo) {
|
|
2053
|
+
const c = closeOf(t0, eo[0].length - 1);
|
|
2054
|
+
const rest = c > 0 ? t0.slice(c + 1).trim() : '';
|
|
2055
|
+
if (rest && !/^[{:]/.test(rest)) { clauseHead = t0.slice(0, c + 1).replace(/\s+/g, ' ').trim(); clauseKids = [{ text: rest, line: s.line + (t0.slice(0, t0.indexOf(rest)).match(/\n/g) || []).length, endLine: s.endLine ?? s.line }]; }
|
|
2056
|
+
}
|
|
2057
|
+
attachClause(prev, { kind: kw, head: clauseHead, line: s.line, endLine: s.endLine, children: clauseKids });
|
|
1948
2058
|
intoAlways = kw === 'finally';
|
|
1949
2059
|
into = s.children?.length ? null : kw === 'catch' ? prev.handlers?.[prev.handlers.length - 1]?.steps ?? null : kw === 'finally' ? prev.always?.steps ?? null : null;
|
|
1950
2060
|
prev.span = { ...prev.span, endLine: Math.max(prev.span.endLine, s.endLine ?? s.line) };
|
|
@@ -1961,7 +2071,7 @@ export function stepsFrom(statements) {
|
|
|
1961
2071
|
continue;
|
|
1962
2072
|
}
|
|
1963
2073
|
if (!C_FAMILY.has(LANG) && /^[A-Za-z_]\w*:$/.test(t0) && !/^(?:default|else|try|finally|begin|ensure|rescue)$/.test(t0.slice(0, -1))) { skipped.push(spanOf(s)); continue; }
|
|
1964
|
-
if (!t0 || /^(?:end\b|\}|pass$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
|
|
2074
|
+
if (!t0 || /^(?:end\b(?!\s*(?:[-+*/%|&^]?=(?!=)|\+\+|--|\(|\[|->))|\}|pass$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
|
|
1965
2075
|
if (/^(?:"""|'''|r"""|\/\*\*|\*(?![\w(*]))/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments (not C's `*out = n`)
|
|
1966
2076
|
// C/C++ `(void)x;` and `static_cast<void>(x);` only tell the compiler x is unused on purpose: nothing happens.
|
|
1967
2077
|
if (C_FAMILY.has(LANG) && /^(?:\(\s*void\s*\)|static_cast\s*<\s*void\s*>)\s*\(?\s*[\w.]+\s*\)?\s*;?$/.test(t0)) { skipped.push(spanOf(s)); continue; }
|
|
@@ -1991,11 +2101,11 @@ export function stepsFrom(statements) {
|
|
|
1991
2101
|
if (elvis && balancedText(elvis[1]) && balancedText(elvis[3])) {
|
|
1992
2102
|
steps.push({ ...classifyStatement(elvis[1]), line: s.line, span: spanOf(s) });
|
|
1993
2103
|
const out = classifyStatement(elvis[3]);
|
|
1994
|
-
steps.push({ kind: 'branch', says: `If ${words(elvis[2])} is
|
|
2104
|
+
steps.push({ kind: 'branch', says: `If ${words(elvis[2])} is null`, cond: `${elvis[2]} == null`, expr: { kind: 'if', test: { kind: 'compare', op: '==', left: { kind: 'name', name: elvis[2] }, right: { kind: 'literal', type: 'null', value: null, raw: 'null' } }, elvis: true }, code: clip(String(s.text).replace(/\s+/g, ' '), 90), line: s.line, span: spanOf(s), children: [{ ...out, line: s.line, span: spanOf(s) }] });
|
|
1995
2105
|
continue;
|
|
1996
2106
|
}
|
|
1997
2107
|
let step = { ...classifyStatement(s.implicitReturn ? `return ${s.text}` : s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
1998
|
-
if (s.implicitReturn) step.code = clip(headLine(s.text), 90);
|
|
2108
|
+
if (s.implicitReturn) step.code = clip(LANG === 'rust' && !s.children?.length ? String(s.text).replace(/\s+/g, ' ').trim() : headLine(s.text), 90);
|
|
1999
2109
|
// A Swift body that is one call with a trailing closure gives back what the last call makes, with the closure's
|
|
2000
2110
|
// steps under it: `parseDirectives(…).compactMap { … }` -> "Returns the result of compact map".
|
|
2001
2111
|
const closureHead = headLine(s.text).replace(/\{[^{}]*?(?<![\w$])in\s*$/, '{');
|
|
@@ -2047,7 +2157,7 @@ export function stepsFrom(statements) {
|
|
|
2047
2157
|
if (step.inline && !/^\{/.test(step.inline.trim())) { step.children = [inlineKid(step.inline, s)]; delete step.inline; }
|
|
2048
2158
|
else if (s.children?.length && (['branch', 'loop', 'try'].includes(step.kind) || (step.kind === 'check' && step.caseLabel) || /^(?:Defines a helper|Defines how|Opens |Uses |At the end, runs )/.test(step.says))) {
|
|
2049
2159
|
let kids = stepsFrom(s.children).steps;
|
|
2050
|
-
if (step.kind === 'branch' && /^(?:Chooses by|Checks these cases)/.test(step.says)) kids = groupCases(kids);
|
|
2160
|
+
if (step.kind === 'branch' && /^(?:Chooses by|Checks these cases)/.test(step.says)) { kids = groupCases(kids); if (/^switch\b/.test(head0)) caseBreaks(kids); }
|
|
2051
2161
|
if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); if (/^Defines/.test(step.says)) step.nested = true; }
|
|
2052
2162
|
// Go select: whichever channel is ready first (or, with a default, whichever is ready now).
|
|
2053
2163
|
if (/^select\s*\{/.test(head0) && step.children) {
|
|
@@ -2063,6 +2173,16 @@ export function stepsFrom(statements) {
|
|
|
2063
2173
|
if (step.kind === 'branch' || step.kind === 'try') for (const c of s.clauses || []) attachClause(step, c);
|
|
2064
2174
|
steps.push(step);
|
|
2065
2175
|
}
|
|
2176
|
+
// "Handles any error" only when something catches any error: `try … finally` catches nothing (the error goes on to
|
|
2177
|
+
// the caller after the steps at the end), and a Swift `do { … }` with no `catch` is only a scope for its names.
|
|
2178
|
+
for (let i = 0; i < steps.length; i++) {
|
|
2179
|
+
const st = steps[i];
|
|
2180
|
+
if (st.kind !== 'try' || !/handles any error/.test(st.says || '')) continue;
|
|
2181
|
+
const hs = st.handlers || [];
|
|
2182
|
+
if (!hs.length && !st.always && LANG === 'swift' && /^do\b/.test(String(st.code || ''))) { const kids = st.children || []; steps.splice(i, 1, ...kids); i += kids.length - 1; continue; }
|
|
2183
|
+
if (!hs.length) st.says = st.says.replace(/^Tries (the next|these) steps and handles any error/, st.always ? 'Runs $1 steps, then always the steps at the end (an error is not caught here: it still goes on to the caller)' : 'Runs $1 steps (an error is not caught here)');
|
|
2184
|
+
else if (!hs.some((h) => /^If anything goes wrong/.test(h.says || ''))) st.says = st.says.replace(/^Tries (the next|these) steps and handles any error/, 'Tries $1 steps and handles the errors named below');
|
|
2185
|
+
}
|
|
2066
2186
|
// A bare word is only a returned value when it is the last statement; before that it is a call (Ruby: `rollback`).
|
|
2067
2187
|
for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
|
|
2068
2188
|
// A value chosen by if / match / when: each side's last value is what the name is set to (or what is returned).
|
|
@@ -2073,6 +2193,21 @@ export function stepsFrom(statements) {
|
|
|
2073
2193
|
return { steps, more, skipped, readable: readableShare(steps) };
|
|
2074
2194
|
}
|
|
2075
2195
|
|
|
2196
|
+
/**
|
|
2197
|
+
* In a switch (C, C++, Java, C#, JavaScript, PHP, Go, Swift), `break` ends the case and goes on after the switch: it
|
|
2198
|
+
* does not leave a loop around it. (Not inside a loop or a switch of its own, where `break` is theirs.)
|
|
2199
|
+
*/
|
|
2200
|
+
function caseBreaks(kids) {
|
|
2201
|
+
const walk = (list) => {
|
|
2202
|
+
for (const k of list || []) {
|
|
2203
|
+
if (k.jump === 'break' && !/\(/.test(k.says) && /^break\b/.test(String(k.code || '').trim())) { k.says = 'Leaves the choice (goes on after it)'; if (k.expr?.kind === 'jump') k.expr = { ...k.expr, of: 'switch' }; continue; }
|
|
2204
|
+
if (k.kind === 'loop' || (k.kind === 'branch' && /^(?:Chooses by|Checks these cases)/.test(k.says || ''))) continue;
|
|
2205
|
+
walk(k.children); walk(k.otherwise); for (const h of k.handlers || []) walk(h.steps); walk(k.always?.steps);
|
|
2206
|
+
}
|
|
2207
|
+
};
|
|
2208
|
+
for (const c of kids) if (c.caseLabel) walk(c.children);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2076
2211
|
/**
|
|
2077
2212
|
* A step that only puts the code's syntax into English ("Works out actives", "Returns the result of any") tells a
|
|
2078
2213
|
* reader nothing the code did not. It is kept, but marked `restates` and not counted as read.
|
|
@@ -2335,6 +2470,21 @@ export function braceStatements(stmts, split = null) {
|
|
|
2335
2470
|
const m = rest.match(/^\s*(else\s+if\b|elseif\b|elsif\b|else\b|catch\b|rescue\b|finally\b|ensure\b)/);
|
|
2336
2471
|
if (!m) break;
|
|
2337
2472
|
const kw = m[1].replace(/\s+/g, ' ');
|
|
2473
|
+
// A clause written without braces (`} else if (x)\n y += 1;`, `} else return z;`): its one statement is
|
|
2474
|
+
// the rest of this statement. (Looking for the next `{` would take some later block for it, or drop it.)
|
|
2475
|
+
const kwEnd = pos + m[0].length;
|
|
2476
|
+
let hdrEnd = kwEnd, parenHead = false;
|
|
2477
|
+
if (/^(?:else if|elseif|elsif|catch)$/.test(kw)) { const po = kwEnd + text.slice(kwEnd).search(/\S/); if (text[po] === '(') { const pc = closeOf(text, po); if (pc > 0) { hdrEnd = pc + 1; parenHead = true; } } }
|
|
2478
|
+
const nb = text.slice(hdrEnd).search(/\S/);
|
|
2479
|
+
// (Only where braces are optional: Go, Rust, and Swift always write them, and their conditions have no brackets.)
|
|
2480
|
+
if (!/^(?:go|rust|swift)$/.test(LANG) && (kw === 'else' || parenHead) && nb >= 0 && text[hdrEnd + nb] !== '{' && kw !== 'catch' && !(kw === 'else' && /^if\b/.test(text.slice(hdrEnd + nb)))) {
|
|
2481
|
+
const at = hdrEnd + nb;
|
|
2482
|
+
const body = text.slice(at).replace(/[\s;]+$/, '');
|
|
2483
|
+
const head = text.slice(pos + m[0].length - m[1].length, hdrEnd).trim();
|
|
2484
|
+
const kids = split && body ? braceStatements([{ text: body, line: lineAtPos(at), endLine: lineAtPos(at + body.length - 1), ...(s.start != null ? { start: s.start + at, end: s.start + at + body.length } : {}) }], split) : [];
|
|
2485
|
+
clauses.push({ kind: /^(else if|elseif|elsif)$/.test(kw) ? 'elif' : kw === 'else' ? 'else' : kw === 'finally' || kw === 'ensure' ? 'finally' : 'catch', head, line: lineAtPos(pos + rest.indexOf(m[1])), children: kids });
|
|
2486
|
+
break;
|
|
2487
|
+
}
|
|
2338
2488
|
const o = text.indexOf('{', pos + m[0].length);
|
|
2339
2489
|
if (o < 0) break;
|
|
2340
2490
|
const e = blockEnd(text, o);
|
|
@@ -2441,7 +2591,7 @@ function groupClassicCases(kids, split) {
|
|
|
2441
2591
|
* Python lines that continue a statement (inside open brackets, or after a `\`) belong to the line that opened it:
|
|
2442
2592
|
* `elif (\n a\n and b\n):` is one condition, not a question with "Calls and" inside it.
|
|
2443
2593
|
*/
|
|
2444
|
-
function joinContinued(lines) {
|
|
2594
|
+
function joinContinued(lines, { braces = true } = {}) {
|
|
2445
2595
|
const out = [];
|
|
2446
2596
|
let open = null, depth = 0;
|
|
2447
2597
|
for (const l of lines) {
|
|
@@ -2453,8 +2603,8 @@ function joinContinued(lines) {
|
|
|
2453
2603
|
const c = t[i];
|
|
2454
2604
|
if (c === '#') break;
|
|
2455
2605
|
if (c === '"' || c === "'") { const q = c; for (i++; i < t.length && t[i] !== q; i++) if (t[i] === '\\') i++; continue; }
|
|
2456
|
-
if (c === '(' || c === '[' || c === '{') depth++;
|
|
2457
|
-
else if (c === ')' || c === ']' || c === '}') depth = Math.max(0, depth - 1);
|
|
2606
|
+
if (c === '(' || c === '[' || (braces && c === '{')) depth++;
|
|
2607
|
+
else if (c === ')' || c === ']' || (braces && c === '}')) depth = Math.max(0, depth - 1);
|
|
2458
2608
|
}
|
|
2459
2609
|
back = /\\\s*$/.test(t);
|
|
2460
2610
|
if (depth === 0 && !back) { out.push(open); open = null; }
|
|
@@ -2476,7 +2626,8 @@ export function indentStatements(body, { depthKey = 'indent' } = {}) {
|
|
|
2476
2626
|
if (q) { const doc = { ...l, text: q, endLine: l.line }; kept.push(doc); if (t.slice(t.indexOf(q) + 3).includes(q) === false) { inDoc = q; docEntry = doc; } continue; }
|
|
2477
2627
|
kept.push(l);
|
|
2478
2628
|
}
|
|
2479
|
-
|
|
2629
|
+
// (Ruby: a call written over lines, `Body.new(\n a,\n b\n)`, is one statement; its blocks are read by depth.)
|
|
2630
|
+
body = depthKey === 'indent' ? joinContinued(kept) : joinContinued(kept, { braces: false });
|
|
2480
2631
|
if (!body.length) return [];
|
|
2481
2632
|
const base = Math.min(...body.map((l) => l[depthKey] ?? 0));
|
|
2482
2633
|
const out = [];
|