@inthedark/dxlint 0.1.15 → 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.
Binary file
Binary file
Binary file
package/esbuild.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // An esbuild plugin mapping files through a project's `.dx` transforms, the
2
- // same way `tsc` sees them: one long-lived `dxlint map` for the whole build,
3
- // spoken to in its own protocol (`map { path, text, sourceMap }`).
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
4
  import { spawn } from "node:child_process";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { dirname, join } from "node:path";
@@ -13,6 +13,15 @@ function server() {
13
13
  const waiting = new Map();
14
14
  let next = 1;
15
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})`)));
16
25
  child.stdout.on("data", chunk => {
17
26
  buffer = Buffer.concat([buffer, chunk]);
18
27
  for (;;) {
@@ -22,19 +31,20 @@ function server() {
22
31
  if (buffer.length < header + 4 + length) return;
23
32
  const message = JSON.parse(buffer.toString("utf8", header + 4, header + 4 + length));
24
33
  buffer = buffer.subarray(header + 4 + length);
25
- const { resolve, reject } = waiting.get(message.id);
34
+ const pending = waiting.get(message.id);
35
+ if (!pending) continue;
26
36
  waiting.delete(message.id);
27
- if (message.error) reject(new Error(message.error.message));
28
- else resolve(message.result);
37
+ if (message.error) pending.reject(new Error(message.error.message));
38
+ else pending.resolve(message.result);
29
39
  }
30
40
  });
31
- child.on("exit", () => {
32
- for (const { reject } of waiting.values()) reject(new Error("dxlint map exited"));
33
- waiting.clear();
34
- });
35
41
  return {
42
+ get alive() {
43
+ return failure === undefined;
44
+ },
36
45
  request(method, params) {
37
46
  return new Promise((resolve, reject) => {
47
+ if (failure) return reject(failure);
38
48
  const id = next++;
39
49
  waiting.set(id, { resolve, reject });
40
50
  const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
@@ -58,27 +68,45 @@ function location(file, content, start, end) {
58
68
  return { file, line, column, length, lineText: content.split("\n")[line - 1] ?? "" };
59
69
  }
60
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
+
61
81
  /**
62
82
  * The project's `.dx` transforms as a function, for builds whose own `onLoad`
63
- * does more with a file: one long-lived `dxlint map`, started on first use.
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.
64
86
  * `transform` gives TypeScript `contents` with an inline source map, or esbuild
65
87
  * `errors` (and no `contents`) when the transform reports problems.
66
88
  * @returns {{ transform(fileName: string, content: string): Promise<{ contents?: string, errors: { text: string, location: object }[] }>, close(): void }}
67
89
  */
68
90
  export function dxlintMapper() {
69
- let mapper;
91
+ let opened = false;
70
92
  return {
71
93
  async transform(fileName, content) {
72
- mapper ??= server();
73
- const result = await mapper.request("map", { path: fileName, text: content, sourceMap: true });
94
+ if (!opened) {
95
+ opened = true;
96
+ open++;
97
+ }
98
+ const result = await sharedServer().request("map", { path: fileName, text: content, sourceMap: true });
74
99
  const errors = result.problems.map(problem => ({ text: problem.message, location: location(fileName, content, problem.offset, problem.end_offset) }));
75
100
  if (errors.length > 0) return { errors };
76
101
  const map = Buffer.from(result.sourceMap).toString("base64");
77
102
  return { contents: `${result.text}\n//# sourceMappingURL=data:application/json;base64,${map}`, errors };
78
103
  },
79
104
  close() {
80
- mapper?.close();
81
- mapper = undefined;
105
+ if (!opened) return;
106
+ opened = false;
107
+ if (--open > 0) return;
108
+ shared?.close();
109
+ shared = undefined;
82
110
  },
83
111
  };
84
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inthedark/dxlint",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "let you and your agents own your linter",
5
5
  "license": "MIT",
6
6
  "repository": {
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
@@ -134,12 +134,29 @@ define {
134
134
  variance parameters bivariant
135
135
  }
136
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
+ })
137
143
  in ts_interface, ts_type_literal {
138
144
  let calls_headers filter(member.nodes, h => h is ts_call_signature)
139
- signatures calls_headers
145
+ when count(calls_headers) > 0 { signatures calls_headers }
140
146
  fits callable when any(calls_headers, h => h.kind != "new")
141
147
  fits constructible when any(calls_headers, h => h.kind == "new")
142
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
+ }
143
160
  in ts_class {
144
161
  let calls_constructor_headers filter(member.nodes, h => h is ts_method && h.calls_constructor)
145
162
  when count(calls_constructor_headers) > 0 { signatures calls_constructor_headers }
@@ -158,15 +175,20 @@ define {
158
175
  in ts_type_parameter { optional when default != null }
159
176
  in ts_rest, ts_spread { fits rest }
160
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
+ }
161
183
  in ts_call {
162
- when in_optional_chain == true { calls (callee \ nullable, undefined) with argument }
184
+ when in_optional_chain == true { calls (callee \ nullable, undefined) with calls_arguments }
163
185
  # A bare call's `this` is void: a signature declaring `this: object` does not apply.
164
186
  when in_optional_chain != true && callee is ts_identifier {
165
- calls callee with argument this (trait void, undefined, nullable, falsy, nonthenable)
187
+ calls callee with calls_arguments this (trait void, undefined, nullable, falsy, nonthenable)
166
188
  }
167
- 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 }
168
190
  }
169
- in ts_new { constructs callee with argument }
191
+ in ts_new { constructs callee with calls_arguments }
170
192
  # Overload resolution tries the subtype relation (where `any` fits only
171
193
  # `any`/`unknown`) before assignability.
172
194
  in ts_call, ts_new { overloads exact first }
@@ -175,7 +197,7 @@ define {
175
197
  calls tag with calls_arguments
176
198
  }
177
199
 
178
- in ts_declarator {
200
+ in ts_declarator, ts_parameter {
179
201
  when type != null { in init expects type }
180
202
  }
181
203
  in ts_class_property { in init expects type ?? it.expected }
@@ -185,8 +207,9 @@ define {
185
207
  in ts_array { in element expects each (parent.expected \ nullable).[position] }
186
208
  in ts_method, ts_class_property, ts_property {
187
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).
188
211
  when parent is ts_object || parent is ts_class && contains([] modifier, "static") {
189
- in it expects parent.expected.[calls_member_key]
212
+ in it expects parent.expected.?[calls_member_key]
190
213
  }
191
214
  when parent is ts_class && parent.extends != null {
192
215
  when !contains([] modifier, "static") {
@@ -201,9 +224,14 @@ define {
201
224
  }
202
225
  }
203
226
  in ts_property { in value expects it.expected }
227
+ # An intrinsic element (`<div>`, `<x-widget>`) takes `JSX.IntrinsicElements[tag]`.
204
228
  in ts_jsx_attribute {
205
229
  let calls_jsx_key ts_value_key(name.node)
206
- 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
+ }
207
235
  }
208
236
  in ts_jsx_expression { in expression expects it.expected }
209
237
  in ts_arrow {
@@ -52,25 +52,30 @@ fn import_deprecation_doc(n, site) = {
52
52
  doc => doc != null))
53
53
  }
54
54
  fn import_remote_sites(n, sites) = filter(sites ?? [], site => import_remote_site(n, site))
55
- # `export { /** @deprecated */ X }`: the specifier carries the documentation,
56
- # not `X`'s declaration. Found among the statements of the declaring file.
55
+ fn export_specifier_named(n, specifier, name) = {
56
+ value exported: first(site_field(n, specifier, "exported") ?? []) ?? first(site_field(n, specifier, "local") ?? [])
57
+ value exported != null && site_text(n, exported).text == name
58
+ }
59
+ # `export { /** @deprecated */ X }` or `/** @deprecated */ export { X }`: the
60
+ # specifier or its statement carries the documentation, not `X`'s declaration.
61
+ # Found among the statements of the declaring file.
57
62
  fn import_specifier_docs(n, site, name) = if !site_mentions(n, site, "@deprecated") then [] else {
58
63
  value root: last(walk([site], current => site_parent(n, current)))
59
64
  value exports: filter(site_field(n, root, "body") ?? [], statement => statement.kind == "ts_export")
60
- value specifiers: flat_map(exports, statement => site_field(n, statement, "specifier") ?? [])
61
- value named: filter(specifiers, specifier => {
62
- value exported: first(site_field(n, specifier, "exported") ?? []) ?? first(site_field(n, specifier, "local") ?? [])
63
- value exported != null && site_text(n, exported).text == name
64
- })
65
- value map(named, specifier => deprecation_leading_doc(site_text(n, specifier).leading))
65
+ value flat_map(exports, statement => flat_map(
66
+ filter(site_field(n, statement, "specifier") ?? [], specifier => export_specifier_named(n, specifier, name)),
67
+ specifier => [deprecation_leading_doc(site_text(n, specifier).leading), deprecation_leading_doc(site_text(n, statement).leading)]))
66
68
  }
67
- fn import_deprecation_tag(n) = {
69
+ # `declarations`: whether the declarations' own docs count, beside the export
70
+ # specifiers'; a call with one selected signature reads only that signature's.
71
+ fn import_deprecation_tag(n, declarations) = {
68
72
  value values: import_remote_sites(n, name_definitions(n, "value"))
69
73
  value types: if count(values) > 0 then [] else import_remote_sites(n, name_definitions(n, "type"))
70
74
  value sites: filter(if count(values) > 0 then values else types, site => site_mentions(n, site, "@deprecated"))
71
75
  value if count(sites) == 0 then null else {
72
76
  value imported: name_binding(n).node.imported_name ?? n.text
73
- value deprecation_first(flat_map(reverse(sites), site => [import_deprecation_doc(n, site)] import_specifier_docs(n, site, imported)))
77
+ value deprecation_first(flat_map(reverse(sites), site =>
78
+ (if declarations then [import_deprecation_doc(n, site)] else []) import_specifier_docs(n, site, imported)))
74
79
  }
75
80
  }
76
81
  fn deprecation_local_doc(n) = {
@@ -147,7 +152,11 @@ fn deprecation_reason(n) = {
147
152
  else site_sources(subject, site).sites ?? [])
148
153
  value members: if subject is (ts_member, ts_index) || subject.deprecation_pattern_key then deprecation_symbols(subject).sites else []
149
154
  value origin: declaration_identity(subject)
150
- value declarations: unique([] members (if origin != null then [origin] else []) sites)
155
+ # A name read from a destructured member (`const { old: local } = o; local`)
156
+ # is not that member: only a member access reports it.
157
+ value own_sites: if subject not ts_identifier then sites else filter(sites, site =>
158
+ !contains(["ts_property_signature", "ts_property", "ts_pattern_property", "ts_method_signature", "ts_class_property"], site.kind))
159
+ value declarations: unique([] members (if origin != null then [origin] else []) own_sites)
151
160
  value owners: if call == null then declarations else filter(roots.sites ?? [], site =>
152
161
  !contains(["ts_function", "ts_arrow", "ts_method", "ts_function_type", "ts_method_signature", "ts_call_signature"], site.kind))
153
162
  value signatures: if call != null && selection != null && !selection.uncertain && count(selection.selected) == 1
@@ -159,9 +168,11 @@ fn deprecation_reason(n) = {
159
168
  && name_binding(subject.object.node).node is ts_import.namespace
160
169
  value published: if namespace then flat_map(members, site => import_specifier_docs(subject, site, deprecation_symbols(subject).name)) else []
161
170
  value own: deprecation_first([deprecation_local_doc(subject)] docs published)
162
- # A name bound by an import is deprecated where its module publishes it.
163
- value imported: if own == null && subject is ts_identifier && name_binding(subject).node.deprecation_import == true
164
- then import_deprecation_tag(subject) else null
171
+ # A name bound by an import is deprecated where its module publishes it;
172
+ # with one selected signature, only the export specifiers' docs join its own.
173
+ value imported: if own == null && subject is ts_identifier
174
+ && (name_binding(subject).node.deprecation_import == true || subject.deprecation_reexport)
175
+ then import_deprecation_tag(subject, count(signatures) == 0) else null
165
176
  value own ?? imported
166
177
  }
167
178
 
@@ -169,6 +180,8 @@ in ts_node let deprecation_import
169
180
  if is (ts_import, ts_import_equals) then true
170
181
  else if is (ts_program, ts_block, ts_function, ts_arrow, ts_class, ts_interface) then false
171
182
  else parent.deprecation_import == true
183
+ # `export { x } from "m"`: `x` names the module's export, bound by nothing local.
184
+ in ts_node let deprecation_reexport is ts_export_specifier.local && parent.parent.from != null
172
185
  in ts_node let deprecation_pattern_key is ts_pattern_property.key || is ts_property.key && parent.flow_destructuring_target
173
186
  in ts_node let deprecation_shorthand is ts_property.key && parent.value.node == null && !deprecation_pattern_key
174
187
  in ts_node let deprecation_excluded
package/std/ts/enums.dx CHANGED
@@ -14,8 +14,9 @@ fn enum_root_bad(sender, receiver) = sender != null && receiver != null && len(r
14
14
  && any(receiver, target => any(domains, domain => any(target, part => contains(part.traits, domain))))
15
15
  && !any(receiver, target => any(enum_origins(target), b => any(origins, a =>
16
16
  a.carrier.file == b.carrier.file && a.carrier.node == b.carrier.node)))
17
- && all(source, part => !contains(part.traits, "any") && !contains(part.traits, "unknown")
18
- && !contains(part.uncertain_traits, "enum"))
17
+ # A type parameter stands for its constraint, the arm's other parts.
18
+ && all(source, part => contains(part.traits, "parameter") || !contains(part.traits, "any")
19
+ && !contains(part.traits, "unknown") && !contains(part.uncertain_traits, "enum"))
19
20
  })
20
21
  fn enum_relation_children(pair, source) = {
21
22
  value identity: {sender: pair.sender, receiver: pair.receiver}
@@ -109,6 +110,22 @@ fn enum_annotation_target(context) = {
109
110
  value if frame == null then null else
110
111
  fold(frame.path, frame.target, (target, key) => value_lookup(target, key).member)
111
112
  }
113
+ # The key a computed access must match: the key constraint of the mapped
114
+ # type (`[P in E]`) or the computed member key (`[E.A]: ...`) it reads. An
115
+ # unknown key (`value[key]`, `key: K`) reads the one site all members share.
116
+ fn enum_index_target(n) = {
117
+ value key: value_key(n.index.node)
118
+ value sites: if key != null then flat_map(value_lookup(n.object.node, key).alternatives ?? [], arm =>
119
+ if arm.matched then map(arm.sources ?? [], origin => origin.site) else [])
120
+ else unique(flat_map(value_children(n.object.node, true, []) ?? [], edge =>
121
+ map(edge.member.sources ?? [], origin => origin.site)))
122
+ value member: if key == null && count(sites) != 1 then null else first(sites)
123
+ value parameter: if member == null then null else first(site_field(n, member, "type_parameter") ?? [])
124
+ value computed: if member == null || parameter != null then null else first(site_field(n, member, "key") ?? [])
125
+ value key_site: if parameter != null then first(site_field(n, parameter, "constraint") ?? [])
126
+ else if computed != null then first(site_field(n, computed, "expression") ?? []) else null
127
+ value if key_site != null then declaration_value(n, key_site) else null
128
+ }
112
129
  fn enum_policy(site, source) = {
113
130
  value context: if site is ts_property then site
114
131
  else if source is ts_spread && source.parent is ts_object
@@ -118,12 +135,16 @@ fn enum_policy(site, source) = {
118
135
  value target: if site is ts_update || site is ts_assignment && site.enum_mutation then source
119
136
  else if site is (ts_as, ts_type_assertion) then site.type.node
120
137
  else if site.type != null then site.type.node
138
+ else if site is ts_index then enum_index_target(site)
121
139
  else if context != null && expected.present == true then value_expected_handle(context)
122
140
  else if context != null then enum_annotation_target(context) else null
123
141
  value owner: if source is ts_return.argument || source is ts_arrow.body then return_value_owner(source) else null
124
142
  value asynchronous: owner != null && contains([] owner.modifier, "async")
125
143
  value receiver_handle: if asynchronous && target != null then ts_awaited_value(target, target) else target
126
- value sender_handle: if asynchronous && source != null then ts_awaited_value(source, source) else source
144
+ # `[...numbers]` sends each element of the spread array.
145
+ value spread_element: if source is ts_spread && source.parent is ts_array
146
+ then value_lookup(source.argument.node, {domain: "ordinal"}).member else null
147
+ value sender_handle: if asynchronous && source != null then ts_awaited_value(source, source) else spread_element ?? source
127
148
  value receiver: if receiver_handle != null then value_constituents(receiver_handle) else null
128
149
  value sender: if sender_handle != null then value_constituents(sender_handle) else null
129
150
  value pairs: enum_relation_pairs(sender_handle, receiver_handle, source)
@@ -194,6 +215,8 @@ in enum_transfer rule es-no-unsafe-enum-assignment {
194
215
  else "The value assigned here does not have a shared enum type with the expected enum {enum_names_text(contexts)}."
195
216
  }
196
217
  in ts_array.element rule es-no-unsafe-enum-assignment:element {
218
+ # A spread argument's elements are arguments (`:arguments` reports them).
219
+ when !(parent.parent is ts_spread && parent.parent.parent is (ts_call, ts_new))
197
220
  when !parent.enum_checked && unparenthesised_node(node) not (ts_object, ts_array)
198
221
  let contexts enum_policy(node, node)
199
222
  when any(contexts, context => enum_context_bad(context))
@@ -214,7 +237,12 @@ in ts_jsx_expression.expression rule es-no-unsafe-enum-assignment:jsx {
214
237
  in ts_call.argument, ts_new.argument, ts_template.expression rule es-no-unsafe-enum-assignment:arguments {
215
238
  when !(is ts_template.expression) || parent is ts_tagged_template.quasi
216
239
  when unparenthesised_node(node) not (ts_object, ts_array)
217
- let contexts enum_policy(node, node)
240
+ # `f(...[1])` passes the elements: reported at the spread. One with a spread
241
+ # of its own (`...[1, ...numbers]`) passes as the whole array.
242
+ let passed if node is ts_spread && node.argument is ts_array
243
+ && !any(node.argument.element.nodes, element => element is ts_spread) then filter(node.argument.element.nodes,
244
+ item => unparenthesised_node(item) not (ts_object, ts_array)) else [node]
245
+ let contexts flat_map(passed, item => enum_policy(item, item))
218
246
  when any(contexts, context => enum_context_bad(context))
219
247
  warn "The argument passed here does not have a shared enum type with the expected enum {enum_names_text(contexts)}."
220
248
  }
package/std/ts/grammar.dx CHANGED
@@ -254,7 +254,7 @@ parser ts in js {
254
254
  production ts_case = ("case" test:expression | "default") ":" body:(not(/case|default|\}/) statement)*
255
255
  production ts_try = "try" cut block:ts_block (kind:"catch" ("(" parameter:binding (":" type:goal(types, type_expression))? ")")? handler:ts_block)? ("finally" finalizer:ts_block)?
256
256
  production ts_labeled = label:ts_identifier ":" cut body:statement
257
- production ts_variable_declaration = modifier:"declare"* @ts_parser_variable terminator(";", before("}"), newline, eof)
257
+ production ts_variable_declaration = modifier:variable_modifier* @ts_parser_variable terminator(";", before("}"), newline, eof)
258
258
  production ts_declarator = name:binding "!"? (":" type:goal(types, type_expression))? ("=" init:assignment)?
259
259
  production ts_expression_statement = expression:expression terminator(";", before("}"), newline, eof)
260
260
  production binding = ts_identifier | ts_object_pattern | ts_array_pattern
@@ -288,7 +288,7 @@ parser ts in js {
288
288
  production ts_decorator = "@" expression:lhs_expression
289
289
  production ts_parameter = decorator:ts_decorator* (modifier:/public|private|protected|readonly|override/ same_line peek(property_key))* name:(ts_rest | ts_this | binding) (optional:"?")? (":" type:goal(types, type_expression))? ("=" init:goal(code, clear(no_in, assignment)))?
290
290
  production parameters = "(" (parameter:ts_parameter ("," parameter:ts_parameter)* ","?)? ")"
291
- production ts_function = modifier:"declare"* (modifier:"async" same_line)? "function" (modifier:"*" @ts_parser_function_header (body:clear(no_in, set(generator, ts_block)) | @ts_parser_semi) | @ts_parser_function_header (body:clear(no_in, clear(generator, ts_block)) | @ts_parser_semi))
291
+ production ts_function = modifier:function_modifier* (modifier:"async" same_line)? "function" (modifier:"*" @ts_parser_function_header (body:clear(no_in, set(generator, ts_block)) | @ts_parser_semi) | @ts_parser_function_header (body:clear(no_in, clear(generator, ts_block)) | @ts_parser_semi))
292
292
  production ts_arrow = try(
293
293
  peek(ts_identifier same_line "=>" | "(" | "<" | "async" same_line (ts_identifier same_line "=>" | "(" | "<"))
294
294
  (
@@ -461,7 +461,11 @@ parser ts in js {
461
461
  @ts_parser_method_header (body:clear(no_in, clear(generator, ts_block)) | @ts_parser_semi)
462
462
  ))
463
463
  # Extension points: `extend parser ts { production class_modifier |= ... }`
464
- # adds member modifiers, `class_initializer` tokens standing for `=`.
464
+ # adds member modifiers, `class_initializer` tokens standing for `=`,
465
+ # `function_modifier` and `variable_modifier` words before `function` and
466
+ # `const`/`let`/`var`.
467
+ production function_modifier = text("declare")
468
+ production variable_modifier = text("declare")
465
469
  production class_modifier = text("static") peek(accessor_next) | /public|private|protected|readonly|abstract|override|declare|accessor|async/ same_line peek(accessor_next)
466
470
  production class_initializer = "="
467
471
  production ts_class_property = decorator:ts_decorator* @ts_parser_class_modifiers modifier:"*"? (kind:/get|set/ peek(accessor_next))? key:property_key optional:"?"? "!"? (":" type:goal(types, type_expression))? (discard(class_initializer) init:clear(no_in, assignment))? @ts_parser_semi
@@ -17,8 +17,8 @@ fn import_namespace(n) = {
17
17
  }
18
18
 
19
19
  # Found once per import, not once per use of the name it binds.
20
- in ts_import_specifier let import_tag import_deprecation_tag(local.node ?? imported.node)
21
- in ts_import let import_default_tag if default_import == null then null else import_deprecation_tag(default_import.node)
20
+ in ts_import_specifier let import_tag import_deprecation_tag(local.node ?? imported.node, true)
21
+ in ts_import let import_default_tag if default_import == null then null else import_deprecation_tag(default_import.node, true)
22
22
 
23
23
  in ts_import_specifier rule es-import-no-deprecated:specifier {
24
24
  when import_tag != null
@@ -70,6 +70,11 @@ in ts_array, ts_array_pattern, ts_object, ts_object_pattern, ts_function, ts_arr
70
70
  option tuples trailing_comma_mode | null = null "tuple policy"
71
71
  let dangle_policies {arrays:arrays, objects:objects, functions:functions, imports:imports, exports:exports, importAttributes:importAttributes, dynamicImports:dynamicImports, enums:enums, generics:generics, tuples:tuples, "type-arguments":"never"}
72
72
  let dangle_tsx ends_with(file, ".tsx")
73
+ # One-line lists without a trailing comma are right under every mode but `always`.
74
+ let dangle_may_be_wrong contains([style, arrays, objects, functions, imports, exports, importAttributes, dynamicImports, enums, generics, tuples], "always")
75
+ || position(offset).js_line != position(end_offset).js_line
76
+ || re_test(byte_slice(source, offset, end_offset), /,\s*[)\]}>]|\/\*/)
77
+ when dangle_may_be_wrong
73
78
  each dangle_site in if is ts_import_attributes then layout_attribute_sites(layout_attribute_comma_sites, style, dangle_policies) else layout_dangle_lists(node, style, dangle_policies, ecma_version, dangle_tsx, source) {
74
79
  when layout_dangle_wrong(dangle_site, dangle_site.mode)
75
80
  report at { start: dangle_site.offset, end: dangle_site.offset + (if byte_slice(source, dangle_site.offset, dangle_site.offset + 2) == "\r\n" then 2 else 1) }