@bascik/language-server 1.0.0 → 1.1.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,1208 @@
1
+ /**
2
+ * throw-non-error: a `throw`, a `Promise.reject()` or a Promise executor's
3
+ * `reject()` whose value can never be an Error. Such a value has no stack,
4
+ * so when a server, stream, build or routes script (or an API route, or a
5
+ * module one of them runs) throws it, Bascik's report can name only where
6
+ * the script starts. This marks the line instead, while the code is written.
7
+ *
8
+ * The same idea as ESLint's `no-throw-literal` and
9
+ * `prefer-promise-reject-errors` (and typescript-eslint's `only-throw-error`
10
+ * without types): an identifier, a call, `new`, a member access, `await`,
11
+ * `yield` or a tagged template could hold an Error, so it is never reported;
12
+ * a literal, a template, an object or array literal, `undefined`, a function
13
+ * and unary, binary and update expressions never can. A conditional or a
14
+ * logical expression is reported only when no branch could be an Error, and
15
+ * a sequence by its last expression.
16
+ *
17
+ * Syntactic and deterministic: no type checker. It reads the tokens of
18
+ * `scanJavaScript`, so strings, comments, template text and regular
19
+ * expressions hide what they hold, and it walks each expression's top-level
20
+ * tokens, stepping over a bracketed group in one step, so a script costs one
21
+ * pass however its throws nest. Anything it cannot read for certain (a
22
+ * TypeScript construct it does not know, a cast it cannot step over) is not
23
+ * reported.
24
+ */
25
+ import { scanJavaScript } from "./module-specifiers.js";
26
+ export const THROW_NON_ERROR_RULE = "throw-non-error";
27
+ const COULD_BE_ERROR = {
28
+ couldBeError: true,
29
+ kind: "",
30
+ wrappable: false,
31
+ };
32
+ const plain = (kind) => ({
33
+ couldBeError: false,
34
+ kind,
35
+ wrappable: false,
36
+ });
37
+ /** Punctuators longer than one character, longest first. */
38
+ const OPERATORS = [
39
+ ">>>=",
40
+ "...",
41
+ "===",
42
+ "!==",
43
+ "**=",
44
+ "<<=",
45
+ ">>=",
46
+ ">>>",
47
+ "&&=",
48
+ "||=",
49
+ "??=",
50
+ "=>",
51
+ "==",
52
+ "!=",
53
+ "<=",
54
+ ">=",
55
+ "&&",
56
+ "||",
57
+ "??",
58
+ "?.",
59
+ "**",
60
+ "++",
61
+ "--",
62
+ "<<",
63
+ ">>",
64
+ "+=",
65
+ "-=",
66
+ "*=",
67
+ "/=",
68
+ "%=",
69
+ "&=",
70
+ "|=",
71
+ "^=",
72
+ ];
73
+ /** OPERATORS by their first character, longest first, so a one-character punctuator costs one lookup. */
74
+ const OPERATORS_BY_FIRST = new Map();
75
+ for (const operator of OPERATORS) {
76
+ const list = OPERATORS_BY_FIRST.get(operator[0]);
77
+ if (list)
78
+ list.push(operator);
79
+ else
80
+ OPERATORS_BY_FIRST.set(operator[0], [operator]);
81
+ }
82
+ /** A bigint literal: decimal, hex, octal or binary digits followed by `n`. */
83
+ const BIGINT = /^(?:0[xXoObB][0-9a-fA-F_]+|[0-9][0-9_]*)n$/;
84
+ const BINARY_PRECEDENCE = {
85
+ "??": 1,
86
+ "||": 1,
87
+ "&&": 2,
88
+ "|": 3,
89
+ "^": 4,
90
+ "&": 5,
91
+ "==": 6,
92
+ "!=": 6,
93
+ "===": 6,
94
+ "!==": 6,
95
+ "<": 7,
96
+ ">": 7,
97
+ "<=": 7,
98
+ ">=": 7,
99
+ instanceof: 7,
100
+ in: 7,
101
+ "<<": 8,
102
+ ">>": 8,
103
+ ">>>": 8,
104
+ "+": 9,
105
+ "-": 9,
106
+ "*": 10,
107
+ "/": 10,
108
+ "%": 10,
109
+ "**": 11,
110
+ };
111
+ const ASSIGNMENT_OPERATORS = new Set([
112
+ "=",
113
+ "+=",
114
+ "-=",
115
+ "*=",
116
+ "/=",
117
+ "%=",
118
+ "**=",
119
+ "<<=",
120
+ ">>=",
121
+ ">>>=",
122
+ "&=",
123
+ "|=",
124
+ "^=",
125
+ "&&=",
126
+ "||=",
127
+ "??=",
128
+ ]);
129
+ const PREFIX_OPERATORS = new Set(["!", "-", "+", "~", "++", "--"]);
130
+ const PREFIX_KEYWORDS = new Set(["typeof", "void", "delete", "await"]);
131
+ /** Words that cannot start an expression: a statement keyword means this is not code the parser understands. */
132
+ const NOT_AN_EXPRESSION = new Set([
133
+ "break",
134
+ "case",
135
+ "catch",
136
+ "const",
137
+ "continue",
138
+ "debugger",
139
+ "default",
140
+ "do",
141
+ "else",
142
+ "enum",
143
+ "export",
144
+ "extends",
145
+ "finally",
146
+ "for",
147
+ "if",
148
+ "in",
149
+ "instanceof",
150
+ "let",
151
+ "return",
152
+ "switch",
153
+ "throw",
154
+ "try",
155
+ "var",
156
+ "while",
157
+ "with",
158
+ ]);
159
+ /** How deep the expression parser recurses before it gives up (and reports nothing). */
160
+ const MAX_DEPTH = 64;
161
+ /** How many tokens a look for TypeScript type arguments (`f<T>(x)`) reads. */
162
+ const TYPE_ARGUMENT_LOOKAHEAD = 64;
163
+ const isLineBreak = (code) => code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
164
+ /**
165
+ * The script's tokens with every value a token of its own, and
166
+ * multi-character operators joined. A template with holes is one token,
167
+ * followed by the tokens of the code in its holes, which `skipTo` steps over
168
+ * (for every other token it is the next index); `gapStart` is where the text
169
+ * before each token starts, so a template's closing text is not read as a
170
+ * gap between two tokens.
171
+ */
172
+ function tokensOf(source) {
173
+ const { tokens, values } = scanJavaScript(source);
174
+ const merged = [];
175
+ const addValue = (value) => merged.push({
176
+ kind: value.type,
177
+ value: source.slice(value.start, value.end),
178
+ start: value.start,
179
+ end: value.end,
180
+ ...(value.type === "template" &&
181
+ (value.end - value.start < 2 || source[value.end - 1] !== "`")
182
+ ? { unclosed: true }
183
+ : {}),
184
+ });
185
+ let v = 0;
186
+ for (const token of tokens) {
187
+ while (v < values.length && values[v].start < token.start)
188
+ addValue(values[v++]);
189
+ if (token.type === "string" || token.type === "template")
190
+ merged.push({
191
+ kind: token.type,
192
+ value: token.value,
193
+ start: token.start - 1,
194
+ end: Math.min(token.end + 1, source.length),
195
+ // The quote that opened it, where the closing one should be.
196
+ ...(source[token.end] !== source[token.start - 1]
197
+ ? { unclosed: true }
198
+ : {}),
199
+ });
200
+ else
201
+ merged.push({
202
+ kind: token.type,
203
+ value: token.value,
204
+ start: token.start,
205
+ end: token.end,
206
+ });
207
+ }
208
+ while (v < values.length)
209
+ addValue(values[v++]);
210
+ const out = [];
211
+ for (let i = 0; i < merged.length; i++) {
212
+ const tok = merged[i];
213
+ if (tok.kind !== "punctuation") {
214
+ out.push(tok);
215
+ continue;
216
+ }
217
+ let length = 1;
218
+ // A multi-character operator is punctuation right after punctuation.
219
+ const following = merged[i + 1];
220
+ const candidates = following?.kind === "punctuation" && following.start === tok.start + 1
221
+ ? (OPERATORS_BY_FIRST.get(source[tok.start]) ?? [])
222
+ : [];
223
+ for (const operator of candidates) {
224
+ if (!source.startsWith(operator, tok.start))
225
+ continue;
226
+ let adjacent = true;
227
+ for (let k = 1; k < operator.length; k++) {
228
+ const next = merged[i + k];
229
+ if (next?.kind !== "punctuation" || next.start !== tok.start + k) {
230
+ adjacent = false;
231
+ break;
232
+ }
233
+ }
234
+ // `a?.5:b` is a conditional, not an optional chain.
235
+ if (operator === "?." && /[0-9]/.test(source[tok.start + 2] ?? ""))
236
+ adjacent = false;
237
+ if (adjacent) {
238
+ length = operator.length;
239
+ break;
240
+ }
241
+ }
242
+ // `.5` is a number.
243
+ const next = merged[i + 1];
244
+ if (length === 1 &&
245
+ tok.value === "." &&
246
+ next?.kind === "number" &&
247
+ next.start === tok.end) {
248
+ out.push({
249
+ kind: "number",
250
+ value: source.slice(tok.start, next.end),
251
+ start: tok.start,
252
+ end: next.end,
253
+ });
254
+ i++;
255
+ continue;
256
+ }
257
+ out.push({
258
+ kind: "punctuation",
259
+ value: source.slice(tok.start, tok.start + length),
260
+ start: tok.start,
261
+ end: tok.start + length,
262
+ });
263
+ i += length - 1;
264
+ }
265
+ const n = out.length;
266
+ const skipTo = new Int32Array(n);
267
+ // One more entry: gapStart[n] is where the last token (or template) ends.
268
+ const gapStart = new Int32Array(n + 1);
269
+ for (let i = 0; i <= n; i++) {
270
+ if (i < n)
271
+ skipTo[i] = i + 1;
272
+ gapStart[i] = i > 0 ? out[i - 1].end : 0;
273
+ }
274
+ for (let i = 0; i < n; i++) {
275
+ const tok = out[i];
276
+ if (tok.kind !== "template" || tok.end - tok.start < 2)
277
+ continue;
278
+ // The first token after the template: a binary search, so templates
279
+ // nested in holes cost no rescan.
280
+ let low = i + 1;
281
+ let high = n;
282
+ while (low < high) {
283
+ const mid = (low + high) >> 1;
284
+ if (out[mid].start < tok.end)
285
+ low = mid + 1;
286
+ else
287
+ high = mid;
288
+ }
289
+ skipTo[i] = low;
290
+ gapStart[low] = Math.max(gapStart[low], tok.end);
291
+ }
292
+ return { toks: out, skipTo, gapStart };
293
+ }
294
+ /** Every throw and rejection in `source` whose value can never be an Error. */
295
+ export function findNonErrorThrows(source) {
296
+ // Most scripts throw nothing: skip the token pass for them.
297
+ if (!source.includes("throw") && !source.includes("Promise"))
298
+ return [];
299
+ const { toks, skipTo, gapStart } = tokensOf(source);
300
+ const n = toks.length;
301
+ const found = [];
302
+ // The token that closes each bracket (and opens each closing one), and the
303
+ // innermost bracket around each token, from one pass with a stack.
304
+ const match = new Int32Array(n).fill(-1);
305
+ const parent = new Int32Array(n).fill(-1);
306
+ const open = [];
307
+ const CLOSES = { ")": "(", "]": "[", "}": "{" };
308
+ for (let i = 0; i < n; i++) {
309
+ const tok = toks[i];
310
+ parent[i] = open.length > 0 ? open[open.length - 1] : -1;
311
+ if (tok.kind !== "punctuation")
312
+ continue;
313
+ if (tok.value === "(" || tok.value === "[" || tok.value === "{")
314
+ open.push(i);
315
+ else if (tok.value in CLOSES) {
316
+ const top = open[open.length - 1];
317
+ if (top !== undefined && toks[top].value === CLOSES[tok.value]) {
318
+ match[top] = i;
319
+ match[i] = top;
320
+ open.pop();
321
+ }
322
+ }
323
+ }
324
+ // 0: not read yet, 1: no line break before the token, 2: a line break.
325
+ const breaks = new Int8Array(n);
326
+ const lineBreakBefore = (i) => {
327
+ if (i <= 0 || i >= n)
328
+ return false;
329
+ if (breaks[i] === 0) {
330
+ let found = false;
331
+ for (let c = gapStart[i]; c < toks[i].start; c++)
332
+ if (isLineBreak(source.charCodeAt(c))) {
333
+ found = true;
334
+ break;
335
+ }
336
+ breaks[i] = found ? 2 : 1;
337
+ }
338
+ return breaks[i] === 2;
339
+ };
340
+ const isPunct = (i, value) => i >= 0 &&
341
+ i < n &&
342
+ toks[i].kind === "punctuation" &&
343
+ toks[i].value === value;
344
+ const isWord = (i, value) => i >= 0 && i < n && toks[i].kind === "identifier" && toks[i].value === value;
345
+ const isMemberName = (i) => isPunct(i - 1, ".") || isPunct(i - 1, "?.") || isPunct(i - 1, "#");
346
+ /** The index after a group that opens at `i`, or -1 when it never closes. */
347
+ const after = (i) => (match[i] < 0 ? -1 : match[i] + 1);
348
+ /**
349
+ * The index after TypeScript type arguments that open with `<` at `i`
350
+ * (`f<T>(x)`, `new Map<string, number>()`), or -1 when what follows is no
351
+ * type argument list. Reads at most TYPE_ARGUMENT_LOOKAHEAD tokens, so a
352
+ * chain of comparisons costs no rescan.
353
+ */
354
+ const typeArgumentsEnd = (i) => {
355
+ let depth = 0;
356
+ let read = 0;
357
+ for (let k = i; k < n && read < TYPE_ARGUMENT_LOOKAHEAD; read++) {
358
+ const tok = toks[k];
359
+ if (tok.kind === "punctuation") {
360
+ if (tok.value === "<")
361
+ depth++;
362
+ else if (tok.value === ">" || tok.value === ">>" || tok.value === ">>>")
363
+ depth -= tok.value.length;
364
+ else if (tok.value === "(" || tok.value === "[" || tok.value === "{") {
365
+ const end = after(k);
366
+ if (end < 0)
367
+ return -1;
368
+ k = end;
369
+ continue;
370
+ }
371
+ else if (![",", ".", "|", "&", "=>", "?", ":"].includes(tok.value))
372
+ return -1;
373
+ if (depth < 0)
374
+ return -1;
375
+ if (depth === 0)
376
+ return k + 1;
377
+ }
378
+ else if (tok.kind === "regex" || tok.kind === "template")
379
+ return -1;
380
+ k++;
381
+ }
382
+ return -1;
383
+ };
384
+ const TYPE_OPERATORS = new Set([
385
+ "keyof",
386
+ "typeof",
387
+ "readonly",
388
+ "unique",
389
+ "infer",
390
+ ]);
391
+ /** A token a type can end with, so a word after it starts something else. */
392
+ const completesType = (tok) => tok.kind === "identifier"
393
+ ? !TYPE_OPERATORS.has(tok.value)
394
+ : tok.kind === "punctuation"
395
+ ? [")", "]", "}", ">", ">>", ">>>"].includes(tok.value)
396
+ : true;
397
+ /**
398
+ * The index after a TypeScript type that starts at `i` (after `as`,
399
+ * `satisfies`, or `:` in a parameter list), or -1. It stops at the first
400
+ * token at depth 0 that a type cannot hold.
401
+ */
402
+ const typeEnd = (i) => {
403
+ let k = i;
404
+ let angle = 0;
405
+ let read = 0;
406
+ while (k < n) {
407
+ if (++read > 4 * TYPE_ARGUMENT_LOOKAHEAD)
408
+ return -1;
409
+ const tok = toks[k];
410
+ if (tok.kind === "punctuation") {
411
+ const v = tok.value;
412
+ if (v === "(" || v === "[" || v === "{") {
413
+ // `{` after a complete type ends it (a body); inside angles it is an object type.
414
+ if (v === "{" && angle === 0 && k > i)
415
+ return k;
416
+ const end = after(k);
417
+ if (end < 0)
418
+ return -1;
419
+ k = end;
420
+ continue;
421
+ }
422
+ if (v === "<")
423
+ angle++;
424
+ else if (v === ">" || v === ">>" || v === ">>>") {
425
+ if (angle === 0)
426
+ return k;
427
+ angle = Math.max(0, angle - v.length);
428
+ }
429
+ else if (v === "|" || v === "&" || v === "." || v === "=>") {
430
+ // part of the type
431
+ }
432
+ else if (angle > 0 && (v === "," || v === "?" || v === ":")) {
433
+ // inside type arguments
434
+ }
435
+ else
436
+ return k;
437
+ }
438
+ else if (tok.kind === "identifier") {
439
+ // A word after a complete type ends it (`x as T as U`, `x as T[]
440
+ // satisfies U`); after a type operator (`keyof T`, `typeof x`,
441
+ // `readonly string[]`) or `|`, `&`, `.`, `=>` it is part of it.
442
+ if (k > i && angle === 0 && completesType(toks[k - 1]))
443
+ return k;
444
+ }
445
+ else if (tok.kind === "regex" || tok.kind === "template")
446
+ return k;
447
+ k++;
448
+ }
449
+ return k;
450
+ };
451
+ // The expression parser. `p` is the token it reads next; each function
452
+ // reads one construct and returns what it is, or null when the code is
453
+ // not something it can read for certain (nothing is then reported).
454
+ let p = 0;
455
+ let depth = 0;
456
+ const kindOf = (a, b) => {
457
+ if (a.couldBeError || b.couldBeError)
458
+ return COULD_BE_ERROR;
459
+ if (a.kind === b.kind)
460
+ return plain(a.kind);
461
+ const kinds = new Set([...a.kind.split(" or "), ...b.kind.split(" or ")].filter(Boolean));
462
+ return plain(kinds.size <= 3 ? [...kinds].join(" or ") : "a plain value");
463
+ };
464
+ /** An arrow function's body after `=>` at `p`. */
465
+ const arrowBody = () => {
466
+ if (isPunct(p, "{")) {
467
+ const end = after(p);
468
+ if (end < 0)
469
+ return false;
470
+ p = end;
471
+ return true;
472
+ }
473
+ if (++depth > MAX_DEPTH)
474
+ return false;
475
+ const body = parseAssignment();
476
+ depth--;
477
+ return body !== null;
478
+ };
479
+ const parsePrimary = () => {
480
+ if (p >= n)
481
+ return null;
482
+ const tok = toks[p];
483
+ switch (tok.kind) {
484
+ case "string":
485
+ case "template":
486
+ if (tok.unclosed)
487
+ return null;
488
+ p = skipTo[p];
489
+ return { couldBeError: false, kind: "a string", wrappable: true };
490
+ case "number":
491
+ p++;
492
+ return plain(BIGINT.test(tok.value) ? "a bigint" : "a number");
493
+ case "regex":
494
+ p++;
495
+ return plain("a regular expression");
496
+ case "punctuation": {
497
+ if (tok.value === "(") {
498
+ const end = after(p);
499
+ if (end < 0)
500
+ return null;
501
+ if (isPunct(end, "=>") && !lineBreakBefore(end)) {
502
+ p = end + 1;
503
+ return arrowBody() ? plain("a function") : null;
504
+ }
505
+ if (end === p + 2)
506
+ return null; // `()` that is no arrow
507
+ const close = end - 1;
508
+ p++;
509
+ if (++depth > MAX_DEPTH)
510
+ return null;
511
+ const inner = parseExpression();
512
+ depth--;
513
+ if (!inner || p !== close)
514
+ return null;
515
+ p = end;
516
+ return { ...inner, wrappable: false };
517
+ }
518
+ if (tok.value === "[" || tok.value === "{") {
519
+ const end = after(p);
520
+ if (end < 0)
521
+ return null;
522
+ p = end;
523
+ return plain(tok.value === "[" ? "an array" : "an object");
524
+ }
525
+ return null;
526
+ }
527
+ case "identifier": {
528
+ const word = tok.value;
529
+ if (NOT_AN_EXPRESSION.has(word))
530
+ return null;
531
+ if (word === "undefined") {
532
+ p++;
533
+ return plain("undefined");
534
+ }
535
+ if (word === "null") {
536
+ p++;
537
+ return plain("null");
538
+ }
539
+ if (word === "true" || word === "false") {
540
+ p++;
541
+ return plain("a boolean");
542
+ }
543
+ if (word === "class")
544
+ return null;
545
+ if (word === "function") {
546
+ p++;
547
+ if (isPunct(p, "*"))
548
+ p++;
549
+ if (toks[p]?.kind === "identifier")
550
+ p++;
551
+ if (!isPunct(p, "("))
552
+ return null;
553
+ const end = after(p);
554
+ if (end < 0 || !isPunct(end, "{"))
555
+ return null;
556
+ const bodyEnd = after(end);
557
+ if (bodyEnd < 0)
558
+ return null;
559
+ p = bodyEnd;
560
+ return plain("a function");
561
+ }
562
+ if (word === "async" && !lineBreakBefore(p + 1)) {
563
+ if (isWord(p + 1, "function")) {
564
+ p++;
565
+ return parsePrimary();
566
+ }
567
+ if (toks[p + 1]?.kind === "identifier" &&
568
+ isPunct(p + 2, "=>") &&
569
+ !lineBreakBefore(p + 2)) {
570
+ p += 3;
571
+ return arrowBody() ? plain("a function") : null;
572
+ }
573
+ if (isPunct(p + 1, "(")) {
574
+ const end = after(p + 1);
575
+ if (end > 0 && isPunct(end, "=>") && !lineBreakBefore(end)) {
576
+ p = end + 1;
577
+ return arrowBody() ? plain("a function") : null;
578
+ }
579
+ }
580
+ }
581
+ if (isPunct(p + 1, "=>") && !lineBreakBefore(p + 1)) {
582
+ p += 2;
583
+ return arrowBody() ? plain("a function") : null;
584
+ }
585
+ if (word === "new")
586
+ return parseNew();
587
+ p++;
588
+ // An identifier, `this`, `super`, `import`: could hold an Error.
589
+ return COULD_BE_ERROR;
590
+ }
591
+ }
592
+ return null;
593
+ };
594
+ /** `new X(...)`, `new X`, `new.target`: could be an Error. */
595
+ const parseNew = () => {
596
+ p++; // new
597
+ if (isPunct(p, ".")) {
598
+ p += 2;
599
+ return COULD_BE_ERROR;
600
+ }
601
+ if (++depth > MAX_DEPTH)
602
+ return null;
603
+ const callee = isWord(p, "new") ? parseNew() : parsePrimary();
604
+ depth--;
605
+ if (!callee)
606
+ return null;
607
+ // The callee's member accesses; the first call is the constructor's arguments.
608
+ for (;;) {
609
+ if (isPunct(p, ".") || isPunct(p, "?.")) {
610
+ p++;
611
+ if (isPunct(p, "#"))
612
+ p++;
613
+ if (toks[p]?.kind !== "identifier")
614
+ return null;
615
+ p++;
616
+ }
617
+ else if (isPunct(p, "[")) {
618
+ const end = after(p);
619
+ if (end < 0)
620
+ return null;
621
+ p = end;
622
+ }
623
+ else if (isPunct(p, "<")) {
624
+ const end = typeArgumentsEnd(p);
625
+ if (end < 0)
626
+ break;
627
+ p = end;
628
+ }
629
+ else
630
+ break;
631
+ }
632
+ if (isPunct(p, "(")) {
633
+ const end = after(p);
634
+ if (end < 0)
635
+ return null;
636
+ p = end;
637
+ }
638
+ return COULD_BE_ERROR;
639
+ };
640
+ /** A primary followed by member accesses, calls, tagged templates, casts and `++`. */
641
+ const parsePostfix = () => {
642
+ let value = parsePrimary();
643
+ if (!value)
644
+ return null;
645
+ for (;;) {
646
+ if (p >= n)
647
+ break;
648
+ const tok = toks[p];
649
+ if (tok.kind === "template") {
650
+ // A tagged template.
651
+ p = skipTo[p];
652
+ value = COULD_BE_ERROR;
653
+ continue;
654
+ }
655
+ if (tok.kind === "identifier") {
656
+ if ((tok.value === "as" || tok.value === "satisfies") &&
657
+ !lineBreakBefore(p)) {
658
+ const end = typeEnd(p + 1);
659
+ if (end < 0 || end === p + 1)
660
+ return null;
661
+ p = end;
662
+ value = { ...value, wrappable: false };
663
+ continue;
664
+ }
665
+ break;
666
+ }
667
+ if (tok.kind !== "punctuation")
668
+ break;
669
+ const v = tok.value;
670
+ if (v === "." || v === "?.") {
671
+ p++;
672
+ if (isPunct(p, "#"))
673
+ p++;
674
+ if (toks[p]?.kind === "identifier")
675
+ p++;
676
+ else if (v === "?." && (isPunct(p, "(") || isPunct(p, "["))) {
677
+ const end = after(p);
678
+ if (end < 0)
679
+ return null;
680
+ p = end;
681
+ }
682
+ else
683
+ return null;
684
+ value = COULD_BE_ERROR;
685
+ }
686
+ else if (v === "(" || v === "[") {
687
+ const end = after(p);
688
+ if (end < 0)
689
+ return null;
690
+ p = end;
691
+ value = COULD_BE_ERROR;
692
+ }
693
+ else if (v === "!" && !lineBreakBefore(p)) {
694
+ // TypeScript's non-null assertion: the same value.
695
+ p++;
696
+ value = { ...value, wrappable: false };
697
+ }
698
+ else if (v === "<") {
699
+ const end = typeArgumentsEnd(p);
700
+ if (end < 0 || !(isPunct(end, "(") || toks[end]?.kind === "template"))
701
+ break;
702
+ p = end;
703
+ }
704
+ else if ((v === "++" || v === "--") && !lineBreakBefore(p)) {
705
+ p++;
706
+ return plain("a number");
707
+ }
708
+ else
709
+ break;
710
+ }
711
+ return value;
712
+ };
713
+ const parseUnary = () => {
714
+ const tok = toks[p];
715
+ if (!tok)
716
+ return null;
717
+ const isPrefix = (tok.kind === "punctuation" && PREFIX_OPERATORS.has(tok.value)) ||
718
+ (tok.kind === "identifier" &&
719
+ PREFIX_KEYWORDS.has(tok.value) &&
720
+ // `await` that is a name (`throw await;`) is an identifier.
721
+ !(tok.value === "await" &&
722
+ (p + 1 >= n ||
723
+ lineBreakBefore(p + 1) ||
724
+ isPunct(p + 1, ";") ||
725
+ isPunct(p + 1, ")"))));
726
+ if (!isPrefix)
727
+ return parsePostfix();
728
+ p++;
729
+ if (++depth > MAX_DEPTH)
730
+ return null;
731
+ const operand = parseUnary();
732
+ depth--;
733
+ if (!operand)
734
+ return null;
735
+ switch (tok.value) {
736
+ case "await":
737
+ return COULD_BE_ERROR;
738
+ case "typeof":
739
+ return plain("a string");
740
+ case "void":
741
+ return plain("undefined");
742
+ case "delete":
743
+ case "!":
744
+ return plain("a boolean");
745
+ default:
746
+ return plain("a number");
747
+ }
748
+ };
749
+ const combineBinary = (operator, left, right) => {
750
+ if (operator === "&&")
751
+ return right.couldBeError ? COULD_BE_ERROR : plain(right.kind);
752
+ if (operator === "||" || operator === "??")
753
+ return kindOf(left, right);
754
+ const precedence = BINARY_PRECEDENCE[operator];
755
+ if (precedence === 6 || precedence === 7)
756
+ return plain("a boolean");
757
+ if (operator === "+") {
758
+ if (left.kind === "a string" || right.kind === "a string")
759
+ return plain("a string");
760
+ if (left.kind === "a number" && right.kind === "a number")
761
+ return plain("a number");
762
+ return plain("a string or a number");
763
+ }
764
+ return plain("a number");
765
+ };
766
+ const operatorAt = (i) => {
767
+ const tok = toks[i];
768
+ if (!tok)
769
+ return undefined;
770
+ if (tok.kind === "punctuation" && tok.value in BINARY_PRECEDENCE)
771
+ return tok.value;
772
+ if (tok.kind === "identifier" &&
773
+ (tok.value === "in" || tok.value === "instanceof"))
774
+ return tok.value;
775
+ return undefined;
776
+ };
777
+ const parseBinary = (minPrecedence) => {
778
+ let left = parseUnary();
779
+ if (!left)
780
+ return null;
781
+ for (;;) {
782
+ const operator = operatorAt(p);
783
+ if (operator === undefined)
784
+ break;
785
+ const precedence = BINARY_PRECEDENCE[operator];
786
+ if (precedence < minPrecedence)
787
+ break;
788
+ p++;
789
+ if (++depth > MAX_DEPTH)
790
+ return null;
791
+ const right = parseBinary(operator === "**" ? precedence : precedence + 1);
792
+ depth--;
793
+ if (!right)
794
+ return null;
795
+ left = combineBinary(operator, left, right);
796
+ }
797
+ return left;
798
+ };
799
+ const parseConditional = () => {
800
+ const test = parseBinary(1);
801
+ if (!test)
802
+ return null;
803
+ if (!isPunct(p, "?"))
804
+ return test;
805
+ p++;
806
+ if (++depth > MAX_DEPTH)
807
+ return null;
808
+ const consequent = parseAssignment();
809
+ if (!consequent || !isPunct(p, ":"))
810
+ return null;
811
+ p++;
812
+ const alternate = parseAssignment();
813
+ depth--;
814
+ if (!alternate)
815
+ return null;
816
+ return kindOf(consequent, alternate);
817
+ };
818
+ function parseAssignment() {
819
+ if (isWord(p, "yield")) {
820
+ p++;
821
+ if (p < n &&
822
+ !lineBreakBefore(p) &&
823
+ ![")", "]", "}", ",", ";", ":"].includes(toks[p].value)) {
824
+ if (isPunct(p, "*"))
825
+ p++;
826
+ if (++depth > MAX_DEPTH)
827
+ return null;
828
+ const operand = parseAssignment();
829
+ depth--;
830
+ if (!operand)
831
+ return null;
832
+ }
833
+ return COULD_BE_ERROR;
834
+ }
835
+ const left = parseConditional();
836
+ if (!left)
837
+ return null;
838
+ const tok = toks[p];
839
+ if (tok?.kind !== "punctuation" || !ASSIGNMENT_OPERATORS.has(tok.value))
840
+ return left;
841
+ p++;
842
+ if (++depth > MAX_DEPTH)
843
+ return null;
844
+ const right = parseAssignment();
845
+ depth--;
846
+ if (!right)
847
+ return null;
848
+ if (tok.value === "=" || tok.value === "&&=")
849
+ return right.couldBeError ? COULD_BE_ERROR : plain(right.kind);
850
+ if (tok.value === "||=" || tok.value === "??=")
851
+ return kindOf(left, right);
852
+ return plain(tok.value === "+=" ? "a string or a number" : "a number");
853
+ }
854
+ function parseExpression() {
855
+ let value = parseAssignment();
856
+ while (value && isPunct(p, ",")) {
857
+ p++;
858
+ value = parseAssignment();
859
+ }
860
+ return value;
861
+ }
862
+ /** What the expression at `start` is, and where it ends, or null. */
863
+ const expressionAt = (start, full) => {
864
+ p = start;
865
+ depth = 0;
866
+ const value = full ? parseExpression() : parseAssignment();
867
+ return value ? { value, end: p } : null;
868
+ };
869
+ const report = (site, from, to, value, callee) => {
870
+ found.push({
871
+ site,
872
+ value: value?.kind ?? "",
873
+ start: toks[from].start,
874
+ end: gapStart[to],
875
+ wrappable: value !== undefined && value.wrappable && to === skipTo[from],
876
+ ...(callee !== undefined ? { callee } : {}),
877
+ });
878
+ };
879
+ /**
880
+ * A call's arguments in the group that opens at `open`: reports the call
881
+ * when it passes nothing, or its first argument when that can never be an
882
+ * Error. `from` is where the call starts.
883
+ */
884
+ const checkRejectCall = (site, from, open, callee) => {
885
+ const close = match[open];
886
+ if (close < 0)
887
+ return;
888
+ if (close === open + 1) {
889
+ report(site, from, close + 1, undefined, callee);
890
+ return;
891
+ }
892
+ if (isPunct(open + 1, "..."))
893
+ return;
894
+ const argument = expressionAt(open + 1, false);
895
+ if (!argument || argument.value.couldBeError)
896
+ return;
897
+ if (argument.end !== close && !isPunct(argument.end, ","))
898
+ return;
899
+ report(site, open + 1, argument.end, argument.value, callee);
900
+ };
901
+ /** The reject parameter's name of the executor that starts at `i`, with the token range of its body. */
902
+ const executorAt = (i, limit) => {
903
+ let k = i;
904
+ if (isWord(k, "async"))
905
+ k++;
906
+ let params;
907
+ if (isWord(k, "function")) {
908
+ k++;
909
+ if (isPunct(k, "*"))
910
+ k++;
911
+ if (toks[k]?.kind === "identifier")
912
+ k++;
913
+ if (!isPunct(k, "("))
914
+ return undefined;
915
+ params = k;
916
+ }
917
+ else if (isPunct(k, "("))
918
+ params = k;
919
+ else
920
+ return undefined;
921
+ const paramsEnd = match[params];
922
+ if (paramsEnd < 0)
923
+ return undefined;
924
+ // The second parameter, when it is a plain name (typed or not). A
925
+ // TypeScript `this` parameter (`function (this: T, resolve, reject)`) is
926
+ // no parameter at run time, so reject is the third.
927
+ const wanted = isWord(params + 1, "this") && isPunct(params + 2, ":") ? 2 : 1;
928
+ let second = -1;
929
+ let commas = 0;
930
+ for (let j = params + 1; j < paramsEnd; j++) {
931
+ if (match[j] > j) {
932
+ j = match[j];
933
+ continue;
934
+ }
935
+ if (isPunct(j, "<")) {
936
+ const end = typeArgumentsEnd(j);
937
+ if (end < 0)
938
+ return undefined;
939
+ j = end - 1;
940
+ continue;
941
+ }
942
+ if (isPunct(j, ",")) {
943
+ commas++;
944
+ if (commas === wanted)
945
+ second = j + 1;
946
+ }
947
+ }
948
+ if (second < 0 || toks[second]?.kind !== "identifier")
949
+ return undefined;
950
+ if (!(second + 1 === paramsEnd ||
951
+ isPunct(second + 1, ",") ||
952
+ isPunct(second + 1, ":")))
953
+ return undefined;
954
+ const name = toks[second].value;
955
+ let body = paramsEnd + 1;
956
+ if (isPunct(body, ":")) {
957
+ const end = typeEnd(body + 1);
958
+ if (end < 0)
959
+ return undefined;
960
+ body = end;
961
+ }
962
+ if (isPunct(body, "=>"))
963
+ body++;
964
+ else if (!isPunct(body, "{"))
965
+ return undefined;
966
+ if (isPunct(body, "{")) {
967
+ const end = match[body];
968
+ if (end < 0)
969
+ return undefined;
970
+ return { name, bodyStart: body + 1, bodyEnd: end };
971
+ }
972
+ return { name, bodyStart: body, bodyEnd: limit };
973
+ };
974
+ /** Identifier token indexes by name, built when the first executor is found. */
975
+ let byName;
976
+ const occurrences = (name) => {
977
+ if (!byName) {
978
+ byName = new Map();
979
+ for (let i = 0; i < n; i++)
980
+ if (toks[i].kind === "identifier") {
981
+ const list = byName.get(toks[i].value);
982
+ if (list)
983
+ list.push(i);
984
+ else
985
+ byName.set(toks[i].value, [i]);
986
+ }
987
+ }
988
+ return byName.get(name) ?? [];
989
+ };
990
+ const firstAtOrAfter = (list, at) => {
991
+ let low = 0;
992
+ let high = list.length;
993
+ while (low < high) {
994
+ const mid = (low + high) >> 1;
995
+ if (list[mid] < at)
996
+ low = mid + 1;
997
+ else
998
+ high = mid;
999
+ }
1000
+ return low;
1001
+ };
1002
+ /**
1003
+ * For each bracket that opens a group, the innermost group at or around it
1004
+ * that can declare a name read inside it: a `(` (a parameter list, a catch
1005
+ * clause, a `for` header, or plain parentheses), or a `{` or `[` followed
1006
+ * by `=` (a destructuring pattern). A `{` or `[` that is neither (an object
1007
+ * or array literal, or a pattern nested in one) passes the question to the
1008
+ * group around it, so `({ a, reject }) =>` and `([id, reject]) =>` are
1009
+ * parameter lists. -2: not computed; -1: no such group. Memoized, so the
1010
+ * walk costs each group once however many names are read in it.
1011
+ */
1012
+ let deciders;
1013
+ const deciderOf = (group) => {
1014
+ deciders ??= new Int32Array(n).fill(-2);
1015
+ const path = [];
1016
+ let at = group;
1017
+ while (at >= 0 && deciders[at] === -2) {
1018
+ const end = after(at);
1019
+ if (toks[at].value === "(" || (end > 0 && isPunct(end, "="))) {
1020
+ deciders[at] = at;
1021
+ break;
1022
+ }
1023
+ path.push(at);
1024
+ at = parent[at];
1025
+ }
1026
+ const result = at < 0 ? -1 : deciders[at];
1027
+ for (const k of path)
1028
+ deciders[k] = result;
1029
+ return result;
1030
+ };
1031
+ /**
1032
+ * 1 for each token at a bracket level whose statement starts with `let`,
1033
+ * `const` or `var` and has not ended, so a name after a comma there
1034
+ * (`let a, reject`) is declared. One pass, built with the first executor.
1035
+ */
1036
+ let inDeclaration;
1037
+ const isInDeclaration = (i) => {
1038
+ if (!inDeclaration) {
1039
+ inDeclaration = new Uint8Array(n);
1040
+ const outer = [];
1041
+ let declaring = false;
1042
+ for (let k = 0; k < n; k++) {
1043
+ const tok = toks[k];
1044
+ if (tok.kind === "punctuation") {
1045
+ const v = tok.value;
1046
+ if ((v === "(" || v === "[" || v === "{") && match[k] > k) {
1047
+ outer.push(declaring);
1048
+ declaring = false;
1049
+ continue;
1050
+ }
1051
+ if ((v === ")" || v === "]" || v === "}") && match[k] >= 0) {
1052
+ if (match[k] < k)
1053
+ declaring = outer.pop() ?? false;
1054
+ continue;
1055
+ }
1056
+ if (v === ";")
1057
+ declaring = false;
1058
+ }
1059
+ else if (tok.kind === "identifier" &&
1060
+ (tok.value === "let" ||
1061
+ tok.value === "const" ||
1062
+ tok.value === "var") &&
1063
+ !isMemberName(k))
1064
+ declaring = true;
1065
+ if (declaring)
1066
+ inDeclaration[k] = 1;
1067
+ }
1068
+ }
1069
+ return inDeclaration[i] === 1;
1070
+ };
1071
+ /**
1072
+ * The executor's calls to its reject parameter, or none when the body
1073
+ * might declare the name again (a nested parameter, also inside a
1074
+ * destructuring pattern, a `const` or a `let a, reject` list, a catch
1075
+ * binding, a reassignment, a `for (reject of ...)` loop): only a name that
1076
+ * is clearly the parameter counts.
1077
+ */
1078
+ const checkExecutor = (executor) => {
1079
+ const list = occurrences(executor.name);
1080
+ const calls = [];
1081
+ for (let at = firstAtOrAfter(list, executor.bodyStart); at < list.length && list[at] < executor.bodyEnd; at++) {
1082
+ const i = list[at];
1083
+ if (isMemberName(i))
1084
+ continue;
1085
+ const previous = toks[i - 1];
1086
+ if (previous !== undefined &&
1087
+ previous.kind !== "string" &&
1088
+ previous.kind !== "template" &&
1089
+ ["const", "let", "var", "function", "class", "...", "catch"].includes(previous.value))
1090
+ return;
1091
+ if (isPunct(i - 1, "(") && isWord(i - 2, "catch"))
1092
+ return;
1093
+ // `let a, reject`: a second declarator.
1094
+ if (isPunct(i - 1, ",") && isInDeclaration(i))
1095
+ return;
1096
+ const next = toks[i + 1];
1097
+ if (next?.kind === "punctuation") {
1098
+ if (next.value === "=>" || next.value === ":" || next.value === "?")
1099
+ return;
1100
+ if (ASSIGNMENT_OPERATORS.has(next.value))
1101
+ return;
1102
+ if (next.value === "(") {
1103
+ const end = after(i + 1);
1104
+ // A method `reject() {}` declares the name.
1105
+ if (end < 0 || isPunct(end, "{"))
1106
+ return;
1107
+ calls.push(i);
1108
+ continue;
1109
+ }
1110
+ }
1111
+ // A plain read (`setTimeout(reject, 10)`, `.catch(reject)`), unless the
1112
+ // group around it, through any object or array pattern, is a parameter
1113
+ // list, a catch clause, a `for` header or a destructuring pattern
1114
+ // inside the body.
1115
+ const group = parent[i] >= 0 ? deciderOf(parent[i]) : -1;
1116
+ if (group >= executor.bodyStart && group < executor.bodyEnd) {
1117
+ if (toks[group].value !== "(")
1118
+ return; // `{ a, reject } = o`
1119
+ const end = after(group);
1120
+ if (end > 0 &&
1121
+ (isPunct(end, "=>") ||
1122
+ isPunct(end, "=") ||
1123
+ isPunct(end, "{") ||
1124
+ isPunct(end, ":")))
1125
+ return;
1126
+ if (isWord(group - 1, "catch") ||
1127
+ isWord(group - 1, "for") ||
1128
+ (isWord(group - 1, "await") && isWord(group - 2, "for")))
1129
+ return;
1130
+ }
1131
+ }
1132
+ for (const call of calls)
1133
+ checkRejectCall("reject", call, call + 1, executor.name);
1134
+ };
1135
+ for (let i = 0; i < n; i++) {
1136
+ const tok = toks[i];
1137
+ if (tok.kind !== "identifier")
1138
+ continue;
1139
+ if (tok.value === "throw") {
1140
+ if (isMemberName(i))
1141
+ continue;
1142
+ const next = i + 1;
1143
+ if (next >= n || lineBreakBefore(next))
1144
+ continue;
1145
+ const nextTok = toks[next];
1146
+ if (nextTok.kind === "punctuation" &&
1147
+ [":", "?", ",", ";", "}", ")", "]", "=", ".", "?.", "=>", "<"].includes(nextTok.value))
1148
+ continue;
1149
+ if (isPunct(next, "!") && isPunct(next + 1, ":"))
1150
+ continue;
1151
+ // `throw(x) {}` is a method named throw; `throw (x)` throws x.
1152
+ if (isPunct(next, "(")) {
1153
+ const end = after(next);
1154
+ if (end < 0 || isPunct(end, "{") || isPunct(end, ":"))
1155
+ continue;
1156
+ }
1157
+ const expression = expressionAt(next, true);
1158
+ if (!expression || expression.value.couldBeError)
1159
+ continue;
1160
+ // The statement must end here, or this was not read right.
1161
+ const end = expression.end;
1162
+ if (end < n &&
1163
+ !isPunct(end, ";") &&
1164
+ !isPunct(end, "}") &&
1165
+ !lineBreakBefore(end))
1166
+ continue;
1167
+ report("throw", next, end, expression.value);
1168
+ }
1169
+ else if (tok.value === "Promise" && !isMemberName(i)) {
1170
+ if ((isPunct(i + 1, ".") || isPunct(i + 1, "?.")) &&
1171
+ isWord(i + 2, "reject") &&
1172
+ (isPunct(i + 3, "(") || (isPunct(i + 3, "?.") && isPunct(i + 4, "("))))
1173
+ checkRejectCall("Promise.reject", i, isPunct(i + 3, "(") ? i + 3 : i + 4);
1174
+ else if (isWord(i - 1, "new") && !isMemberName(i - 1)) {
1175
+ let open = i + 1;
1176
+ if (isPunct(open, "<")) {
1177
+ const end = typeArgumentsEnd(open);
1178
+ if (end < 0)
1179
+ continue;
1180
+ open = end;
1181
+ }
1182
+ if (!isPunct(open, "(") || match[open] < 0)
1183
+ continue;
1184
+ const executor = executorAt(open + 1, match[open]);
1185
+ if (executor)
1186
+ checkExecutor(executor);
1187
+ }
1188
+ }
1189
+ }
1190
+ return found;
1191
+ }
1192
+ /** The diagnostic message for a value `findNonErrorThrows` found. */
1193
+ export function nonErrorThrowMessage(found, sourceText) {
1194
+ const shown = found.wrappable &&
1195
+ sourceText.length <= 60 &&
1196
+ !Array.from(sourceText).some((c) => isLineBreak(c.charCodeAt(0)))
1197
+ ? sourceText
1198
+ : '"..."';
1199
+ const why = "Only an Error carries a stack trace, so without one Bascik's error report cannot name this line.";
1200
+ const kind = found.value;
1201
+ if (found.site === "throw")
1202
+ return `Throw an Error, not ${kind}: throw new Error(${shown}). ${why}`;
1203
+ const call = found.site === "reject" ? found.callee : "Promise.reject";
1204
+ if (kind === "")
1205
+ return `Pass ${call}() an Error: ${call}(new Error("...")). A rejection with no reason has no stack trace, so Bascik's error report cannot name this line.`;
1206
+ return `Reject with an Error, not ${kind}: ${call}(new Error(${shown})). ${why}`;
1207
+ }
1208
+ //# sourceMappingURL=throw-non-error.js.map