@inthedark/dxlint 0.1.14 → 0.1.17

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.
Files changed (71) hide show
  1. package/README.md +16 -9
  2. package/bin/dxlint-darwin-arm64 +0 -0
  3. package/bin/dxlint-linux-x64 +0 -0
  4. package/bin/dxlint-win32-x64.exe +0 -0
  5. package/esbuild.mjs +134 -0
  6. package/package.json +20 -2
  7. package/rules/bugs.dx +1 -0
  8. package/std/ts/arithmetic.dx +10 -0
  9. package/std/ts/assertions.dx +56 -4
  10. package/std/ts/calls.dx +45 -15
  11. package/std/ts/conditions.dx +2 -0
  12. package/std/ts/constants.dx +2 -1
  13. package/std/ts/content-mapper.dx +48 -0
  14. package/std/ts/deprecation.dx +38 -18
  15. package/std/ts/effects.dx +8 -1
  16. package/std/ts/enums.dx +32 -4
  17. package/std/ts/format.dx +1 -1
  18. package/std/ts/grammar.dx +29 -15
  19. package/std/ts/import-no-deprecated.dx +4 -2
  20. package/std/ts/javascript.dx +496 -0
  21. package/std/ts/layout/literals.dx +14 -7
  22. package/std/ts/layout/separators.dx +6 -1
  23. package/std/ts/layout/shared.dx +36 -37
  24. package/std/ts/layout/types.dx +4 -0
  25. package/std/ts/literals.dx +1 -0
  26. package/std/ts/methods.dx +3 -0
  27. package/std/ts/modules.dx +60 -2
  28. package/std/ts/names.dx +30 -13
  29. package/std/ts/narrowing.dx +20 -14
  30. package/std/ts/parentheses.dx +27 -0
  31. package/std/ts/problems/control-flow.dx +1 -0
  32. package/std/ts/problems/numeric-precision.dx +1 -0
  33. package/std/ts/problems/regexp.dx +1 -0
  34. package/std/ts/regex/checks.dx +1 -0
  35. package/std/ts/regex/findings.dx +10 -6
  36. package/std/ts/regex/values.dx +4 -15
  37. package/std/ts/restrictions.dx +76 -0
  38. package/std/ts/scoping/member-uses.dx +5 -3
  39. package/std/ts/scoping/shadowing.dx +1 -0
  40. package/std/ts/scoping/usage.dx +3 -3
  41. package/std/ts/spreads.dx +1 -1
  42. package/std/ts/structure/padding.dx +10 -8
  43. package/std/ts/style/expressions.dx +8 -4
  44. package/std/ts/style/returns.dx +3 -1
  45. package/std/ts/style/signatures.dx +5 -0
  46. package/std/ts/style/type-exports.dx +1 -0
  47. package/std/ts/suggestions/builtins.dx +1 -1
  48. package/std/ts/suggestions/comparisons.dx +1 -0
  49. package/std/ts/suggestions/expressions.dx +1 -0
  50. package/std/ts/suggestions/object-spread.dx +1 -1
  51. package/std/ts/tokens.dx +14 -5
  52. package/std/ts/type-specifiers.dx +19 -3
  53. package/std/ts/typed/awaitability.dx +1 -0
  54. package/std/ts/typed/collection-iteration.dx +24 -0
  55. package/std/ts/typed/floating-promises.dx +45 -14
  56. package/std/ts/typed/includes.dx +3 -4
  57. package/std/ts/typed/promises.dx +16 -13
  58. package/std/ts/typed/readonly-parameters.dx +11 -2
  59. package/std/ts/typed/string-boundaries.dx +1 -0
  60. package/std/ts/typed/switches.dx +1 -0
  61. package/std/ts/typed/transfers.dx +54 -7
  62. package/std/ts/typed/type-arguments.dx +19 -20
  63. package/std/ts/typed/type-conversions.dx +1 -0
  64. package/std/ts/typed/type-parameters.dx +1 -1
  65. package/std/ts/typed/using-disposable.dx +98 -0
  66. package/std/ts/typed.dx +22 -9
  67. package/std/ts/values/arguments.dx +1 -1
  68. package/std/ts/values/enums.dx +5 -1
  69. package/std/ts/values/inspection.dx +26 -7
  70. package/std/ts/values.dx +98 -39
  71. package/std/ts.dx +10 -4
package/README.md CHANGED
@@ -23,7 +23,7 @@ warn: Promises must be awaited, end with a call to .catch, end with a call to .t
23
23
 
24
24
  - **it's over 200× faster than eslint+typescript-eslint.** because apples to apples requires eslint *without* its caching enabled, and dxlint's cache is intrinsic. (even without that, it's also twice as fast and significantly less memory hungry)
25
25
  - **and it has almost perfect eslint parity.** 99.4% of eslint's and typescript-eslint's test cases give the same result. type-aware rules read your `tsconfig.json` *without running typescript*
26
- - **everything is overrideable, you own it all.** built-in rules are `.dx` files: override them, tweak them, write your own, or describe a whole new language
26
+ - **everything is overrideable, you own it all.** built-in rules, and even the typescript parser, are `.dx` files: override them, tweak them, extend the grammar with [syntax of your own](docs/advanced.md#transforms-syntax-of-your-own) that typescript and esbuild see through, or describe a whole new language
27
27
  - **plus a high quality vscode extension too!** extremely fast, with diagnostics, with a proper `.dx` lsp
28
28
 
29
29
  ## getting started
@@ -47,8 +47,9 @@ ignore "dist" "src/generated/**"
47
47
  | `dxlint --fix` | apply fixes |
48
48
  | `dxlint rules` | list every rule with its options |
49
49
  | `dxlint describe <name>` | explain a rule, option or anything else in the config |
50
+ | `dxlint map <files>` | show what files using your own syntax become ([transforms](docs/advanced.md#transforms-syntax-of-your-own)) |
50
51
 
51
- exit code 1 means errors were found, 2 means the config is broken.&nbsp;
52
+ `dx` works as a shorter name for `dxlint`. exit code 1 means errors were found, 2 means the config is broken.&nbsp;
52
53
 
53
54
  don't forget to add `.dxcache` to `.gitignore`!!!
54
55
 
@@ -70,14 +71,20 @@ in ts_call.callee rule no-alert-calls error "use the notification service instea
70
71
 
71
72
  ## performance
72
73
 
73
- one core (`--jobs 1`, both pinned to the same core, wall time, measured in one session), on a project with 2,094 .ts files, its complex custom eslint config ported, type-aware rules included:
74
+ a project with 2,161 .ts files and its complex custom eslint config ported, type-aware rules included. eslint 9.39 with typescript-eslint 8.58, wall time, measured in one session on a 16-core machine:
74
75
 
75
- | | ESLint | dxlint |
76
+ | one core (`--jobs 1`) | ESLint | dxlint |
76
77
  | --- | --- | --- |
77
- | first run | 164 s | 72 s |
78
- | cached run, nothing changed | 4.4 s | 0.8 s |
79
- | peak memory (working set) | 2.0 GB | 0.7 GB |
78
+ | first run | 143 s | 58 s |
79
+ | cached run, nothing changed | 2.5 s | 2.0 s |
80
+ | peak memory (working set) | 3.6 GB | 0.60 GB |
80
81
 
81
- and remember: this isn't a fair comparison because [eslint --cache doesn't work with typescript-eslint](https://typescript-eslint.io/troubleshooting/faqs/eslint/?utm_source=chatgpt.com#can-i-use-eslints---cache-with-typescript-eslint)!&nbsp;
82
+ | every core (dxlint's default; ESLint `--concurrency auto`) | ESLint | dxlint |
83
+ | --- | --- | --- |
84
+ | first run | 119 s | 11 s |
85
+ | cached run, nothing changed | 3.0 s | 1.5 s |
86
+ | peak memory (working set) | 18 GB | 1.07 GB |
87
+
88
+ and remember: the cached rows aren't a fair comparison because [eslint --cache doesn't work with typescript-eslint](https://typescript-eslint.io/troubleshooting/faqs/eslint/?utm_source=chatgpt.com#can-i-use-eslints---cache-with-typescript-eslint)! eslint's cache skips files whose own text didn't change, even when a type they use did, while dxlint's cache tracks what each file read&nbsp;
82
89
 
83
- also note that by default dxlint uses every core, and is significantly better at that than eslint+typescript-eslint due to no reliance on typescript itself
90
+ eslint's threads each build their own typescript program, so more cores mostly buy it memory; dxlint doesn't rely on typescript, so its work splits across cores
Binary file
Binary file
Binary file
package/esbuild.mjs ADDED
@@ -0,0 +1,134 @@
1
+ // An esbuild plugin mapping files through a project's `.dx` transforms, the
2
+ // same way `tsc` sees them: one long-lived `dxlint map` shared by every build
3
+ // in the process, spoken to in its own protocol (`map { path, text, sourceMap }`).
4
+ import { spawn } from "node:child_process";
5
+ import { readFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const launcher = join(dirname(fileURLToPath(import.meta.url)), "bin", "dxlint");
10
+
11
+ function server() {
12
+ const child = spawn(process.execPath, [launcher, "map"], { stdio: ["pipe", "pipe", "inherit"] });
13
+ const waiting = new Map();
14
+ let next = 1;
15
+ let buffer = Buffer.alloc(0);
16
+ let failure;
17
+ const fail = error => {
18
+ failure ??= error;
19
+ for (const { reject } of waiting.values()) reject(failure);
20
+ waiting.clear();
21
+ };
22
+ child.on("error", error => fail(new Error(`dxlint map failed: ${error.message}`)));
23
+ child.stdin.on("error", error => fail(new Error(`dxlint map stopped reading: ${error.message}`)));
24
+ child.on("exit", code => fail(new Error(`dxlint map exited (${code})`)));
25
+ child.stdout.on("data", chunk => {
26
+ buffer = Buffer.concat([buffer, chunk]);
27
+ for (;;) {
28
+ const header = buffer.indexOf("\r\n\r\n");
29
+ if (header === -1) return;
30
+ const length = Number(/content-length:\s*(\d+)/i.exec(buffer.toString("latin1", 0, header))[1]);
31
+ if (buffer.length < header + 4 + length) return;
32
+ const message = JSON.parse(buffer.toString("utf8", header + 4, header + 4 + length));
33
+ buffer = buffer.subarray(header + 4 + length);
34
+ const pending = waiting.get(message.id);
35
+ if (!pending) continue;
36
+ waiting.delete(message.id);
37
+ if (message.error) pending.reject(new Error(message.error.message));
38
+ else pending.resolve(message.result);
39
+ }
40
+ });
41
+ return {
42
+ get alive() {
43
+ return failure === undefined;
44
+ },
45
+ request(method, params) {
46
+ return new Promise((resolve, reject) => {
47
+ if (failure) return reject(failure);
48
+ const id = next++;
49
+ waiting.set(id, { resolve, reject });
50
+ const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
51
+ child.stdin.write(`Content-Length: ${body.length}\r\n\r\n`);
52
+ child.stdin.write(body);
53
+ });
54
+ },
55
+ close() {
56
+ child.stdin.end();
57
+ },
58
+ };
59
+ }
60
+
61
+ /** Byte offset of a problem as esbuild's line and column. */
62
+ function location(file, content, start, end) {
63
+ const bytes = Buffer.from(content);
64
+ const before = bytes.subarray(0, start).toString();
65
+ const line = before.split("\n").length;
66
+ const column = before.length - (before.lastIndexOf("\n") + 1);
67
+ const length = bytes.subarray(start, end).toString().length;
68
+ return { file, line, column, length, lineText: content.split("\n")[line - 1] ?? "" };
69
+ }
70
+
71
+ /** The process every mapper shares, and how many mappers are open. */
72
+ let shared;
73
+ let open = 0;
74
+
75
+ /** The shared process, started again if it died. */
76
+ function sharedServer() {
77
+ if (!shared?.alive) shared = server();
78
+ return shared;
79
+ }
80
+
81
+ /**
82
+ * The project's `.dx` transforms as a function, for builds whose own `onLoad`
83
+ * does more with a file. Every open mapper shares one long-lived `dxlint map`,
84
+ * started on first use and ended when the last one closes; it maps each file
85
+ * on its own and picks up `.dx` edits, so any number of builds may use it.
86
+ * `transform` gives TypeScript `contents` with an inline source map, or esbuild
87
+ * `errors` (and no `contents`) when the transform reports problems.
88
+ * @returns {{ transform(fileName: string, content: string): Promise<{ contents?: string, errors: { text: string, location: object }[] }>, close(): void }}
89
+ */
90
+ export function dxlintMapper() {
91
+ let opened = false;
92
+ return {
93
+ async transform(fileName, content) {
94
+ if (!opened) {
95
+ opened = true;
96
+ open++;
97
+ }
98
+ const result = await sharedServer().request("map", { path: fileName, text: content, sourceMap: true });
99
+ const errors = result.problems.map(problem => ({ text: problem.message, location: location(fileName, content, problem.offset, problem.end_offset) }));
100
+ if (errors.length > 0) return { errors };
101
+ const map = Buffer.from(result.sourceMap).toString("base64");
102
+ return { contents: `${result.text}\n//# sourceMappingURL=data:application/json;base64,${map}`, errors };
103
+ },
104
+ close() {
105
+ if (!opened) return;
106
+ opened = false;
107
+ if (--open > 0) return;
108
+ shared?.close();
109
+ shared = undefined;
110
+ },
111
+ };
112
+ }
113
+
114
+ /**
115
+ * @param {{ filter?: RegExp, readFile?: (path: string) => string | Uint8Array | Promise<string | Uint8Array> }} [options]
116
+ * `filter`: files to map, by default `.wts`. `readFile`: a file's content as
117
+ * the build should see it (an editor buffer, another checkout's view); by
118
+ * default the disk's.
119
+ */
120
+ export function dxlintTransform({ filter = /\.wts$/, readFile: readContent = path => readFile(path, "utf8") } = {}) {
121
+ return {
122
+ name: "dxlint-transform",
123
+ setup(build) {
124
+ const mapper = dxlintMapper();
125
+ build.onDispose(() => mapper.close());
126
+ build.onLoad({ filter }, async args => {
127
+ const read = await readContent(args.path);
128
+ const content = typeof read === "string" ? read : Buffer.from(read).toString("utf8");
129
+ const { contents, errors } = await mapper.transform(args.path, content);
130
+ return contents === undefined ? { errors } : { contents, loader: "ts", resolveDir: dirname(args.path) };
131
+ });
132
+ },
133
+ };
134
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inthedark/dxlint",
3
- "version": "0.1.14",
3
+ "version": "0.1.17",
4
4
  "description": "let you and your agents own your linter",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,12 +32,30 @@
32
32
  "arm64"
33
33
  ],
34
34
  "bin": {
35
- "dxlint": "bin/dxlint"
35
+ "dxlint": "bin/dxlint",
36
+ "dx": "bin/dxlint"
37
+ },
38
+ "exports": {
39
+ "./esbuild": "./esbuild.mjs",
40
+ "./package.json": "./package.json"
41
+ },
42
+ "typescript": {
43
+ "contentMapper": {
44
+ "exec": [
45
+ "node",
46
+ "bin/dxlint",
47
+ "map",
48
+ "--protocol",
49
+ ".ts/content-mapper"
50
+ ],
51
+ "dynamicConfig": true
52
+ }
36
53
  },
37
54
  "files": [
38
55
  "bin",
39
56
  "std",
40
57
  "rules",
58
+ "esbuild.mjs",
41
59
  "README.md",
42
60
  "LICENSE"
43
61
  ]
package/rules/bugs.dx CHANGED
@@ -31,6 +31,7 @@ rule es-no-misused-promises error
31
31
  rule es-no-new-native-nonconstructor error
32
32
  rule es-no-non-null-asserted-optional-chain error
33
33
  rule es-no-obj-calls error
34
+ rule es-no-object-iteration-of-collections error
34
35
  rule es-no-redeclare error
35
36
  rule es-no-self-assign error
36
37
  rule es-no-setter-return error
@@ -5,12 +5,22 @@ fn ts_value_print_literal_parts(parts) = parts != null && len(parts) > 0
5
5
  && any(parts, arm => any(arm, part => !contains(part.traits, "parameter")))
6
6
  && all(parts, arm => all(filter(arm, part => !contains(part.traits, "parameter")),
7
7
  part => contains(part.traits, "literal") || part.identity_known && part.identity.kind == "value"))
8
+ # A type parameter names its constraint's primitive (`T extends 'a' | 'b'`:
9
+ # `string`), as TypeScript ESLint's getTypeName does.
10
+ fn arithmetic_parameter_primitive(parts) = {
11
+ value parameter: parts != null && count(parts) > 0 && all(parts, arm => any(arm, part => contains(part.traits, "parameter")))
12
+ value primitives: unique(flat_map(parts ?? [], arm => flat_map(arm, part =>
13
+ filter(["string", "number", "bigint", "boolean"], trait => contains(part.traits, trait)))))
14
+ value if parameter && count(primitives) == 1 then first(primitives) else null
15
+ }
8
16
  # Widening only changes literals: structure would collapse to `object`, so keep
9
17
  # the handle's shape unless every printed constituent is a literal.
10
18
  fn arithmetic_type_name(n) = {
11
19
  value written: ts_value_print_written(n)
12
20
  value parts: value_constituents(n)
21
+ value primitive: arithmetic_parameter_primitive(parts)
13
22
  value if written != null then written
23
+ else if primitive != null then primitive
14
24
  else if ts_value_print_literal_parts(parts) then ts_value_print(value_widened(n) ?? parts)
15
25
  else ts_value_print_handle(n)
16
26
  }
@@ -233,6 +233,33 @@ fn assertion_named_unchanged(n, subject) = {
233
233
  else if written != null then written == n.type.text
234
234
  else !contains(["object", "unknown"], printed) && printed == ts_value_print_handle(n.type.node)
235
235
  }
236
+ # TypeScript ESLint's hasSameProperties + mutual assignability, for differently
237
+ # named shapes (`record as Props`): one shape each side, the same keys, each
238
+ # readonly on both sides or neither, each pair of member values assignable both
239
+ # ways. Compared member by member: an object literal's own runtime facts
240
+ # (`object`, `truthy`) are no requirement an interface type could promise.
241
+ # Plain shapes only: upstream also needs equal type arguments, which arrays,
242
+ # tuples and instantiated generics would have to compare (`PropsB[]` vs
243
+ # `PropsA[]` are mutually assignable yet kept).
244
+ fn assertion_property_edges(n) = {
245
+ value arms: value_parts(n)
246
+ value plain: arms != null && count(arms) == 1 && all(first(arms).parts, part => part.product_known && part.product == null
247
+ && part.carrier_known && (part.carrier == null || count(part.carrier.arguments ?? []) == 0))
248
+ value if !plain then null else value_children(first(arms).handle, true, [])
249
+ }
250
+ fn assertion_property_readonly(edge) = any(edge.member.sources, source => contains(source.flags, "readonly"))
251
+ fn assertion_same_properties(source, target) = {
252
+ value left: assertion_property_edges(source)
253
+ value right: assertion_property_edges(target)
254
+ value left != null && right != null && count(left) > 0 && count(left) == count(right)
255
+ && all(left, edge => edge.member != null) && all(right, edge => edge.member != null)
256
+ && all(left, edge => any(right, other => other.member.key == edge.member.key
257
+ && other.member.optional == edge.member.optional
258
+ && assertion_property_readonly(other) == assertion_property_readonly(edge)
259
+ && value_accepts(other.handle, edge.handle, "value", "value") == true
260
+ && value_accepts(edge.handle, other.handle, "value", "value") == true))
261
+ && value_accepts(target, source, "value", "value") == true
262
+ }
236
263
  # The receiver's own typing (union, satisfies, another assertion) gives no contextual type.
237
264
  fn assertion_property_receiver(n) = {
238
265
  value property: n.parent.node
@@ -337,6 +364,14 @@ fn assertion_context_skipped(n) = {
337
364
  else if parent is ts_assignment && parent.right.offset == n.offset && parent.parent not ts_expression_statement then true
338
365
  else false
339
366
  }
367
+ # An asserted type with generic methods (`method<T>(v: T): T`) the operand's
368
+ # don't match keeps the assertion (TypeScript ESLint's genericsMismatch).
369
+ fn assertion_generic_mismatch(n) = {
370
+ value target: value_parts(n.type.node)
371
+ value edges: if target != null && count(target) == 1 then value_children(first(target).handle, true, []) ?? [] else []
372
+ value any(edges, edge => any(flat_map(value_signatures(edge.handle) ?? [], arm => arm),
373
+ header => count(site_field(n, header.site, "type_parameter") ?? []) > 0))
374
+ }
340
375
  fn assertion_check(n, ignored, check_const) = {
341
376
  value literal_const: n.type.text == "const"
342
377
  value raw_subject: if literal_const then n.expression.node else assertion_subject(n, ignored)
@@ -349,13 +384,24 @@ fn assertion_check(n, ignored, check_const) = {
349
384
  || value_accepts(n, n.expression.node, "expected", "widened") == true
350
385
  || n.parent.node is ts_property && value_accepts(n.expression.node, n.expression.node, "expected", "value") == true)
351
386
  && !assertion_context_skipped(n)
387
+ && !assertion_generic_mismatch(n)
352
388
  value chain_contextual: !literal_const && n.expression.node is (ts_as, ts_type_assertion)
353
389
  && (assertion_parts_contain_any(value_trait_parts(n.expression.node, ["any"]))
354
390
  || ts_value_trait(value_constituent_traits(n.expression.node, ["unknown"]), "unknown") == true)
355
391
  && value_accepts(n, subject, "expected", "value") == true
356
392
  value receiver: contextual || chain_contextual
357
393
  value identity: !literal_const && assertion_context_identity(n)
394
+ # `[]` is `never[]` already (strict): asserting that changes nothing.
395
+ value empty_never: subject is ts_array && count(subject.element.nodes) == 0
396
+ && n.type.node is ts_array_type && n.type.node.type is ts_type_keyword && n.type.node.type.text == "never"
397
+ && ts_compiler_option(n, "strictNullChecks") == true
398
+ # A generic call's literal result (`echo(3)`) is inferred from the assertion's
399
+ # wider primitive (`as number`: `echo<number>`), as TypeScript infers it.
400
+ value generic_widened: !literal_const && subject is ts_call && assertion_parts_known(annotation)
401
+ && all(annotation, arm => all(arm.parts, part => part.identity_known && part.identity == null && part.carrier == null))
402
+ && assertion_generic_call(subject) == true && ts_value_print(value_widened(subject)) == ts_value_print(value_constituents(n.type.node))
358
403
  value same: if literal_const then assertion_same_handles(operand, annotation) == true
404
+ else if empty_never || generic_widened then true
359
405
  else if assertion_context_identity(n) == true then true
360
406
  else if assertion_error_identity(n) == true then true
361
407
  else if assertion_non_nullable_identity(n, subject) == true then true
@@ -366,19 +412,24 @@ fn assertion_check(n, ignored, check_const) = {
366
412
  && !assertion_parts_deep_contain_any(operand, 4) && !assertion_parts_deep_contain_any(annotation, 4)
367
413
  && (assertion_same_value(subject, n.type.node)
368
414
  || (subject not (ts_object, ts_array) || assertion_context_identity(n) == true)
369
- && assertion_named_unchanged(n, subject)
370
- && assertion_same_shape(subject, n.type.node))
415
+ && (assertion_named_unchanged(n, subject) && assertion_same_shape(subject, n.type.node)
416
+ || assertion_same_properties(subject, n.type.node)))
371
417
  value generic: assertion_generic_call(subject)
372
418
  value literal_preserved: !any(annotation ?? [], arm => any(arm.parts, part =>
373
419
  part.identity_known && part.identity.kind == "value")) || assertion_literal_preserved(n)
374
420
  || subject is ts_call && generic == false
375
421
  value enum_preserved: ts_value_has_enum(n) != null && ts_value_has_enum(n) == ts_value_has_enum(subject)
376
422
  value if contains(ignored, n.type.text) || literal_const && (!check_const || !assertion_const_scalar(n))
377
- || !receiver && (!same || !identity && subject is (ts_object, ts_array)
423
+ || !receiver && (!same || !identity && !empty_never && subject is (ts_object, ts_array)
378
424
  || !literal_const && subject is ts_template && count(subject.expression.nodes) == 0
379
425
  || !literal_preserved || !enum_preserved) || generic == null then null
380
426
  else {subject: subject, raw_subject: raw_subject, contextual: receiver && !same, generic: generic}
381
427
  }
428
+ # One arm each side, equal up to instantiation (`Box<string>` handles differ
429
+ # between the union and the assertion): assignable both ways.
430
+ fn assertion_mutual_arm(retained, target) = count(retained) == 1 && count(target) == 1
431
+ && value_accepts(first(retained).handle, first(target).handle, "value", "value") == true
432
+ && value_accepts(first(target).handle, first(retained).handle, "value", "value") == true
382
433
  fn assertion_non_null_style(n) = {
383
434
  value source: value_parts(n.expression.node)
384
435
  value target: value_parts(n.type.node)
@@ -387,7 +438,8 @@ fn assertion_non_null_style(n) = {
387
438
  value non_null: value_union(first(retained).handle, map(slice(retained, 1), arm => arm.handle))
388
439
  value if !assertion_parts_known(source) || !assertion_parts_non_null(target) then null
389
440
  else count(retained) < count(source)
390
- && (assertion_same_handles(retained, target) == true || assertion_same_value(non_null, n.type.node)
441
+ && (assertion_same_handles(retained, target) == true || assertion_mutual_arm(retained, target)
442
+ || assertion_same_value(non_null, n.type.node)
391
443
  || assertion_same_scalar_type(non_null, n.type.node))
392
444
  }
393
445
  fn assertion_unassigned(n) = n is ts_identifier && (n.declaration == null && n.resolved != "global" || n.declaration.parent is ts_declarator && n.declaration.ambient != true && (n.declaration.parent.init == null && { value n.declaration.parent.token_texts; slice 1 2; first } != "!"
package/std/ts/calls.dx CHANGED
@@ -1,3 +1,4 @@
1
+ import .ts/javascript
1
2
  # .ts/calls: signatures and invocation syntax.
2
3
  import .ts/effects
3
4
 
@@ -44,15 +45,16 @@ define {
44
45
  }
45
46
  }
46
47
 
48
+ in ts_class let calls_bodiless_methods filter(member.nodes, declaration => declaration is ts_method && declaration.body == null)
49
+ in ts_arrow, ts_function_type, ts_method_signature, ts_call_signature let calls_overload_implementation false
50
+ in ts_function let calls_overload_implementation node.body != null && any(name_binding(node.name.node).declarations, declaration =>
51
+ declaration.parent.node is ts_function && declaration.parent.node.body == null)
52
+ in ts_method let calls_overload_implementation node.body != null && parent is ts_class && count(parent.calls_bodiless_methods) > 0
53
+ && ts_value_key(key.node) != null
54
+ && any(parent.calls_bodiless_methods, declaration => ts_value_key(declaration.key.node) == ts_value_key(key.node)
55
+ && ts_value_static(declaration.modifier.nodes) == ts_value_static(modifier.nodes))
47
56
  in ts_function, ts_arrow, ts_method, ts_function_type, ts_method_signature, ts_call_signature {
48
57
  overloads infer last
49
- let calls_overload_implementation node.body != null && (
50
- node is ts_function && any(name_binding(node.name.node).declarations, declaration =>
51
- declaration.parent.node is ts_function && declaration.parent.node.body == null)
52
- || node is ts_method && parent is ts_class && ts_value_key(key.node) != null
53
- && any(parent.member.nodes, declaration => declaration is ts_method && declaration.body == null
54
- && ts_value_key(declaration.key.node) == ts_value_key(key.node)
55
- && ts_value_static(declaration.modifier.nodes) == ts_value_static(modifier.nodes)))
56
58
  let calls_receivers filter(parameter.nodes, p => p.name is ts_this || p.name is ts_identifier && p.name == "this")
57
59
  let calls_parameters filter(parameter.nodes, p => !(p.name is ts_this || p.name is ts_identifier && p.name == "this"))
58
60
  let calls_concise_result if node is ts_arrow && node.body not ts_block then node.body.node else null
@@ -132,12 +134,29 @@ define {
132
134
  variance parameters bivariant
133
135
  }
134
136
 
137
+ fn calls_base_declares(base, construct) = base is ts_type_reference && base.name is ts_identifier
138
+ && any(name_binding(base.name.node).declarations ?? [], declaration => {
139
+ value owner: declaration.parent.node
140
+ value owner is ts_interface && (any(owner.calls_headers, header => (header.kind == "new") == construct)
141
+ || count(if construct then owner.calls_constructible_bases else owner.calls_callable_bases) > 0)
142
+ })
135
143
  in ts_interface, ts_type_literal {
136
144
  let calls_headers filter(member.nodes, h => h is ts_call_signature)
137
- signatures calls_headers
145
+ when count(calls_headers) > 0 { signatures calls_headers }
138
146
  fits callable when any(calls_headers, h => h.kind != "new")
139
147
  fits constructible when any(calls_headers, h => h.kind == "new")
140
148
  }
149
+ # Call signatures are inherited (`interface A extends B {}`); a base with
150
+ # none (`Function`) makes nothing callable. Read off the bases' interface
151
+ # declarations (syntax and names only: callability is asked constantly).
152
+ in ts_interface {
153
+ let calls_callable_bases filter(extends.nodes, base => calls_base_declares(base, false))
154
+ let calls_constructible_bases filter(extends.nodes, base => calls_base_declares(base, true))
155
+ when count(calls_callable_bases) > 0 { signatures ...calls_callable_bases }
156
+ when count(calls_constructible_bases) > 0 { signatures ...calls_constructible_bases }
157
+ fits callable when count(calls_callable_bases) > 0
158
+ fits constructible when count(calls_constructible_bases) > 0
159
+ }
141
160
  in ts_class {
142
161
  let calls_constructor_headers filter(member.nodes, h => h is ts_method && h.calls_constructor)
143
162
  when count(calls_constructor_headers) > 0 { signatures calls_constructor_headers }
@@ -156,15 +175,20 @@ define {
156
175
  in ts_type_parameter { optional when default != null }
157
176
  in ts_rest, ts_spread { fits rest }
158
177
 
178
+ # A spread array literal passes its elements (`f(...[1, cb])` is `f(1, cb)`).
179
+ in ts_call, ts_new {
180
+ let calls_arguments flat_map(argument.nodes, item => if item is ts_spread && item.argument is ts_array
181
+ && !any(item.argument.element.nodes, element => element is ts_spread) then item.argument.element.nodes else [item])
182
+ }
159
183
  in ts_call {
160
- when in_optional_chain == true { calls (callee \ nullable, undefined) with argument }
184
+ when in_optional_chain == true { calls (callee \ nullable, undefined) with calls_arguments }
161
185
  # A bare call's `this` is void: a signature declaring `this: object` does not apply.
162
186
  when in_optional_chain != true && callee is ts_identifier {
163
- calls callee with argument this (trait void, undefined, nullable, falsy, nonthenable)
187
+ calls callee with calls_arguments this (trait void, undefined, nullable, falsy, nonthenable)
164
188
  }
165
- when in_optional_chain != true && !(callee is ts_identifier) { calls callee with argument }
189
+ when in_optional_chain != true && !(callee is ts_identifier) { calls callee with calls_arguments }
166
190
  }
167
- in ts_new { constructs callee with argument }
191
+ in ts_new { constructs callee with calls_arguments }
168
192
  # Overload resolution tries the subtype relation (where `any` fits only
169
193
  # `any`/`unknown`) before assignability.
170
194
  in ts_call, ts_new { overloads exact first }
@@ -173,7 +197,7 @@ define {
173
197
  calls tag with calls_arguments
174
198
  }
175
199
 
176
- in ts_declarator {
200
+ in ts_declarator, ts_parameter {
177
201
  when type != null { in init expects type }
178
202
  }
179
203
  in ts_class_property { in init expects type ?? it.expected }
@@ -183,8 +207,9 @@ define {
183
207
  in ts_array { in element expects each (parent.expected \ nullable).[position] }
184
208
  in ts_method, ts_class_property, ts_property {
185
209
  let calls_member_key if key is ts_computed_key then key.expression.node else ts_value_key(key.node)
210
+ # A union context types a property by the alternatives that have it (TypeScript).
186
211
  when parent is ts_object || parent is ts_class && contains([] modifier, "static") {
187
- in it expects parent.expected.[calls_member_key]
212
+ in it expects parent.expected.?[calls_member_key]
188
213
  }
189
214
  when parent is ts_class && parent.extends != null {
190
215
  when !contains([] modifier, "static") {
@@ -199,9 +224,14 @@ define {
199
224
  }
200
225
  }
201
226
  in ts_property { in value expects it.expected }
227
+ # An intrinsic element (`<div>`, `<x-widget>`) takes `JSX.IntrinsicElements[tag]`.
202
228
  in ts_jsx_attribute {
203
229
  let calls_jsx_key ts_value_key(name.node)
204
- in value expects parent.name.first_parameter.[calls_jsx_key]
230
+ let calls_jsx_intrinsic if re_test(parent.name.text, /^[a-z]|-/) then parent.name.text else null
231
+ when calls_jsx_intrinsic == null { in value expects parent.name.first_parameter.[calls_jsx_key] }
232
+ when calls_jsx_intrinsic != null {
233
+ in value expects (scope namespace from instance "JSX" in type).["IntrinsicElements"].[calls_jsx_intrinsic].[calls_jsx_key]
234
+ }
205
235
  }
206
236
  in ts_jsx_expression { in expression expects it.expected }
207
237
  in ts_arrow {
@@ -1,3 +1,4 @@
1
+ import .ts/javascript
1
2
  # .ts/conditions: type-aware conditional policy.
2
3
 
3
4
  import .ts/values/inspection
@@ -207,6 +208,7 @@ fn condition_callback(n) = if n is (ts_arrow, ts_function) then when {
207
208
  else then null
208
209
  } else null
209
210
  fn condition_array_method(n) = n.callee is (ts_member, ts_index) && contains(["every", "filter", "find", "findIndex", "findLast", "findLastIndex", "some"], n.callee.static_name)
211
+ in ts_call let condition_array_call condition_array_method(node)
210
212
  fn condition_array_callback(n) = condition_array_method(n) && strict_boolean_array(n.callee.object.node)
211
213
  fn condition_literal_arm(arm) = {
212
214
  value parts: filter(arm, part => part.identity.kind == "value")
@@ -1,3 +1,4 @@
1
+ import .ts/javascript
1
2
  import .ts/globals
2
3
  import .ts/expression-fixes
3
4
 
@@ -9,7 +10,7 @@ fn ts_runtime_binding_init(n) = {
9
10
  value owner: declaration.parent.node
10
11
  value if binding == null || count(binding.declarations) != 1 || owner not ts_declarator
11
12
  || owner.name.node != declaration || !contains(["const", "let", "var"], declaration.declaration_kind)
12
- || !all(binding.references, reference => reference.access != null
13
+ || !all(name_references(n), reference => reference.access != null
13
14
  && !contains(["write", "read_write"], reference.access))
14
15
  then null else owner.init.node
15
16
  }
@@ -0,0 +1,48 @@
1
+ # TypeScript's content-mapper protocol (TypeScript 7: `contentMappers` in
2
+ # tsconfig, `tsc --runExternalCode`), as an adapter over dxlint's neutral
3
+ # mapping. Served by `dxlint map --protocol .ts/content-mapper`, which the
4
+ # npm package's manifest names. Kept text and copies are verbatim segments
5
+ # (mirrors take part in no language feature, so tools land on the copy),
6
+ # renamed text is an alias; segments split where another piece's span
7
+ # starts or ends, as TypeScript wants original spans equal or disjoint.
8
+
9
+ protocol typescript {
10
+ method initialize (params) = { protocolVersion: 1, positionEncoding: "utf-8", diagnosticSource: "dxlint" }
11
+ method openProject (params) = { configIdentity: config_identity(params.configFileName), watchedFiles: config_files(params.configFileName) }
12
+ method closeProject (params) = null
13
+ method transform (params) = ts_content_mapping(map_file(params.fileName, params.content))
14
+ }
15
+
16
+ define {
17
+
18
+ fn ts_mapper_cuts(pieces) = { value pieces; flat_map (p) [p.source.offset, p.source.end_offset]; unique; sort }
19
+
20
+ # A same-text piece as segments split at every cut inside its span:
21
+ # `[virtual start, length, original start, length]`.
22
+ fn ts_mapper_segments(p, cuts) = {
23
+ value inside: { value cuts; filter (c) c > p.source.offset && c < p.source.end_offset }
24
+ value starts: [p.source.offset] inside
25
+ value { value starts; zip (inside [p.source.end_offset]) (start, end) [p.output.offset + start - p.source.offset, end - start, start, end - start] }
26
+ }
27
+
28
+ # Renamed text maps as a whole; across a cut it maps nowhere.
29
+ fn ts_mapper_alias(p, cuts) = if any(cuts, c => c > p.source.offset && c < p.source.end_offset) then []
30
+ else [[p.output.offset, p.output.end_offset - p.output.offset, p.source.offset, p.source.end_offset - p.source.offset, 2]]
31
+
32
+ # Kind 0 is verbatim; a sixth element 0 turns every language feature off.
33
+ fn ts_mapper_tuple(p, segment) = if p.kind == "mirror" then segment [0, 0] else segment [0]
34
+
35
+ fn ts_mapper_mappings(pieces) = {
36
+ value cuts: ts_mapper_cuts(pieces)
37
+ value pieces
38
+ flat_map (p) if p.kind == "renamed" then ts_mapper_alias(p, cuts) else map(ts_mapper_segments(p, cuts), s => ts_mapper_tuple(p, s))
39
+ }
40
+
41
+ fn ts_content_mapping(mapped) = {
42
+ text: mapped.text,
43
+ extension: ".ts",
44
+ mappings: ts_mapper_mappings(mapped.pieces),
45
+ diagnostics: map(mapped.problems, p => { messageText: p.message, start: p.offset, length: p.end_offset - p.offset }),
46
+ }
47
+
48
+ }