@cplieger/deadset-ts 3.2.0 → 3.3.0

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,127 @@
1
+ /**
2
+ * The reflective-lookup class: a member is held back, at the lowest confidence, when
3
+ * a string literal equal to its name is the key of an element access or the property
4
+ * key of a `Reflect.get`, `Reflect.set` or `Reflect.has` call, because the member is
5
+ * then read by a name the program computes nowhere the reference pass can follow.
6
+ *
7
+ * The evidence is a string beside a lookup rather than a type relation, so the
8
+ * string reaches every member of that name on any type, static members included,
9
+ * and every record names the string's own position. A key that is not literal text
10
+ * holds nothing back: a computed name is the case no exact rule serves. `Reflect` is
11
+ * the global one only: a local declaration of that name is a different object.
12
+ */
13
+
14
+ import {
15
+ isCallExpression,
16
+ isElementAccessExpression,
17
+ isIdentifier,
18
+ isNoSubstitutionTemplateLiteral,
19
+ isPropertyAccessExpression,
20
+ isStringLiteral,
21
+ type Node,
22
+ type SourceFile,
23
+ } from "@typescript/native/unstable/ast";
24
+ import type { DetectorInput, Evidence } from "./exempt.ts";
25
+ import { memberNames } from "./member-names.ts";
26
+ import { renderPosition } from "./position.ts";
27
+
28
+ /** The `Reflect` methods whose second argument is a property key. */
29
+ const REFLECT_KEYED: ReadonlySet<string> = new Set(["get", "set", "has"]);
30
+
31
+ /** One literal key at one lookup, and how the lookup is spelled in a record. */
32
+ interface Lookup {
33
+ readonly key: Node;
34
+ readonly name: string;
35
+ readonly callee: string;
36
+ /** The `Reflect` the call names, where the lookup is a `Reflect` call. */
37
+ readonly reflect: Node | undefined;
38
+ }
39
+
40
+ /** The text one key denotes, where it is literal text. */
41
+ function literalText(node: Node | undefined): string | undefined {
42
+ if (node !== undefined && (isStringLiteral(node) || isNoSubstitutionTemplateLiteral(node))) {
43
+ return node.text;
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ /** Every lookup one file writes with a literal key, in source order. */
49
+ function lookupsOf(file: SourceFile): readonly Lookup[] {
50
+ const found: Lookup[] = [];
51
+ const visit = (node: Node): void => {
52
+ if (isElementAccessExpression(node)) {
53
+ const name = literalText(node.argumentExpression);
54
+ if (name !== undefined) {
55
+ found.push({
56
+ key: node.argumentExpression,
57
+ name,
58
+ callee: `[${JSON.stringify(name)}]`,
59
+ reflect: undefined,
60
+ });
61
+ }
62
+ } else if (isCallExpression(node) && isPropertyAccessExpression(node.expression)) {
63
+ const target = node.expression.expression;
64
+ const method = node.expression.name;
65
+ const key = node.arguments[1];
66
+ const name = literalText(key);
67
+ if (
68
+ isIdentifier(target) &&
69
+ target.text === "Reflect" &&
70
+ isIdentifier(method) &&
71
+ REFLECT_KEYED.has(method.text) &&
72
+ key !== undefined &&
73
+ name !== undefined
74
+ ) {
75
+ found.push({ key, name, callee: `Reflect.${method.text}`, reflect: target });
76
+ }
77
+ }
78
+ node.forEachChild(visit);
79
+ };
80
+ file.forEachChild(visit);
81
+ return found;
82
+ }
83
+
84
+ /**
85
+ * The reflective-lookup detector: every member whose name a literal key of a lookup
86
+ * spells, recorded at the key.
87
+ */
88
+ export function reflectiveLookup<Brand>(input: DetectorInput<Brand>): readonly Evidence[] {
89
+ const { project, held, targetRoot } = input;
90
+ const files = project.ownSourceFiles();
91
+ const lookups = files.flatMap(lookupsOf);
92
+ if (lookups.length === 0) {
93
+ return [];
94
+ }
95
+
96
+ // Whether each written `Reflect` is the global one, asked in one batch: a
97
+ // declaration of that name in one of the project's own files shadows it.
98
+ const ownFiles = new Set(files.map((file) => file.fileName));
99
+ const reflects = lookups.flatMap((lookup) =>
100
+ lookup.reflect === undefined ? [] : [lookup.reflect],
101
+ );
102
+ const global = new Set<Node>();
103
+ if (reflects.length > 0) {
104
+ project.symbolsAt(reflects.map((node) => project.handle(node))).forEach((symbol, index) => {
105
+ const node = reflects[index];
106
+ const declaredHere = symbol?.declarations.some((declaration) =>
107
+ ownFiles.has(declaration.path),
108
+ );
109
+ if (node !== undefined && declaredHere === false) {
110
+ global.add(node);
111
+ }
112
+ });
113
+ }
114
+
115
+ const members = memberNames(files, held);
116
+ const found: Evidence[] = [];
117
+ for (const lookup of lookups) {
118
+ if (lookup.reflect !== undefined && !global.has(lookup.reflect)) {
119
+ continue;
120
+ }
121
+ const site = renderPosition(lookup.key.getSourceFile(), targetRoot, lookup.key.getStart());
122
+ for (const member of members.get(lookup.name) ?? []) {
123
+ found.push({ id: member.id, detail: `looked up by ${lookup.callee}`, site });
124
+ }
125
+ }
126
+ return found;
127
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The template-field class: a member is held back, at the lowest confidence, when a
3
+ * template under a configured template directory writes its name inside an action,
4
+ * because a template engine reads the member by that name at run time.
5
+ *
6
+ * Every file under a configured directory is a template. An action runs from an
7
+ * opening delimiter to the first closing one after it, at the pair
8
+ * `analysis.template_delimiters` sets, `{{` and `}}` by default, and each identifier
9
+ * it writes outside a quoted string is a name it reads: `{{ user.name }}` names `user`
10
+ * and `name`. A file holding an unclosed action names nothing. A name reaches the
11
+ * instance members of classes and the members of interfaces and object types, on any
12
+ * type, because nothing ties the name to a type.
13
+ */
14
+
15
+ import { ConfigError, type Analysis, type TemplateDelimiters } from "./config.ts";
16
+ import type { DetectorInput, Evidence } from "./exempt.ts";
17
+ import type { Host } from "./host.ts";
18
+ import type { SymbolKind } from "./inventory.ts";
19
+ import { memberNames } from "./member-names.ts";
20
+ import { isAbsolutePath, joinPath, normalizePath } from "./paths.ts";
21
+ import type { Position } from "./position.ts";
22
+
23
+ /** One template, by its path below the target root. */
24
+ export interface TemplateFile {
25
+ readonly path: string;
26
+ readonly text: string;
27
+ }
28
+
29
+ /** The templates one run scans, and the pair their actions are written with. */
30
+ export interface Templates {
31
+ readonly delimiters: TemplateDelimiters;
32
+ readonly files: readonly TemplateFile[];
33
+ }
34
+
35
+ /** The kinds of declaration an action can name. */
36
+ const READ_BY_A_TEMPLATE: ReadonlySet<SymbolKind> = new Set([
37
+ "method",
38
+ "class-member",
39
+ "interface-method",
40
+ "type-member",
41
+ ]);
42
+
43
+ /** One identifier, as the grammar of the analyzed language spells one. */
44
+ const IDENTIFIER = /[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*/uy;
45
+
46
+ /** Two strings ordered bytewise. */
47
+ function compare(a: string, b: string): number {
48
+ if (a === b) {
49
+ return 0;
50
+ }
51
+ return a < b ? -1 : 1;
52
+ }
53
+
54
+ /**
55
+ * Every template under the configured directories, read once for the run, in path
56
+ * order and each file once. A directory is named relative to the target root, and
57
+ * one the target does not hold refuses the run as a usage error: the class would
58
+ * scan nothing, so a name that no longer matches the tree would silently switch the
59
+ * exemption it was configured for off. A symbolic link to a directory is not
60
+ * followed.
61
+ */
62
+ export function readTemplates(host: Host, targetRoot: string, analysis: Analysis): Templates {
63
+ const files = new Map<string, string>();
64
+ const read = (dir: string): void => {
65
+ const entries = [...host.readDirectory(joinPath(targetRoot, dir))].sort((a, b) =>
66
+ compare(a.name, b.name),
67
+ );
68
+ for (const entry of entries) {
69
+ const path = joinPath(dir, entry.name);
70
+ if (entry.directory) {
71
+ read(path);
72
+ continue;
73
+ }
74
+ const absolute = joinPath(targetRoot, path);
75
+ if (!files.has(path) && host.kindOf(absolute) === "file") {
76
+ files.set(path, host.readFile(absolute));
77
+ }
78
+ }
79
+ };
80
+ for (const configured of analysis.templateDirs) {
81
+ const dir = normalizePath(configured);
82
+ if (
83
+ isAbsolutePath(dir) ||
84
+ dir === ".." ||
85
+ dir.startsWith("../") ||
86
+ host.kindOf(joinPath(targetRoot, dir)) !== "directory"
87
+ ) {
88
+ throw new ConfigError(
89
+ "malformed",
90
+ "analysis.template_dirs",
91
+ `analysis.template_dirs: ${JSON.stringify(configured)} is not a directory below the target root`,
92
+ );
93
+ }
94
+ read(dir);
95
+ }
96
+ return {
97
+ delimiters: analysis.templateDelimiters,
98
+ files: [...files]
99
+ .map(([path, text]) => ({ path, text }))
100
+ .sort((a, b) => compare(a.path, b.path)),
101
+ };
102
+ }
103
+
104
+ /** One identifier an action writes, where it is written, and the action that writes it. */
105
+ interface Named {
106
+ readonly name: string;
107
+ readonly offset: number;
108
+ readonly action: string;
109
+ }
110
+
111
+ /** The end of the quoted string that opens at `from`, past its closing quote. */
112
+ function stringEnd(text: string, from: number): number {
113
+ const quote = text[from];
114
+ let at = from + 1;
115
+ while (at < text.length && text[at] !== quote) {
116
+ at += text[at] === "\\" ? 2 : 1;
117
+ }
118
+ return at + 1;
119
+ }
120
+
121
+ /** The identifiers one action's inner text writes outside a quoted string, with their offsets in it. */
122
+ function identifiersOf(inner: string): readonly { name: string; offset: number }[] {
123
+ const found: { name: string; offset: number }[] = [];
124
+ let at = 0;
125
+ while (at < inner.length) {
126
+ const char = inner[at] ?? "";
127
+ if (char === '"' || char === "'" || char === "`") {
128
+ at = stringEnd(inner, at);
129
+ continue;
130
+ }
131
+ if (/[0-9]/u.test(char)) {
132
+ // A number's letters are part of the number: `1e3` names nothing.
133
+ while (at < inner.length && /[0-9A-Za-z_.]/u.test(inner[at] ?? "")) {
134
+ at += 1;
135
+ }
136
+ continue;
137
+ }
138
+ IDENTIFIER.lastIndex = at;
139
+ const match = IDENTIFIER.exec(inner);
140
+ if (match !== null) {
141
+ found.push({ name: match[0], offset: at });
142
+ at += match[0].length;
143
+ continue;
144
+ }
145
+ at += 1;
146
+ }
147
+ return found;
148
+ }
149
+
150
+ /**
151
+ * Every identifier one template's actions write, in the order the file writes them,
152
+ * or none where an action is not closed.
153
+ */
154
+ function namesOf(text: string, delimiters: TemplateDelimiters): readonly Named[] {
155
+ const found: Named[] = [];
156
+ let from = 0;
157
+ for (;;) {
158
+ const open = text.indexOf(delimiters.left, from);
159
+ if (open < 0) {
160
+ return found;
161
+ }
162
+ const start = open + delimiters.left.length;
163
+ const close = text.indexOf(delimiters.right, start);
164
+ if (close < 0) {
165
+ return [];
166
+ }
167
+ const inner = text.slice(start, close);
168
+ const action = `${delimiters.left}${inner.trim().replace(/\s+/gu, " ")}${delimiters.right}`;
169
+ for (const { name, offset } of identifiersOf(inner)) {
170
+ found.push({ name, offset: start + offset, action });
171
+ }
172
+ from = close + delimiters.right.length;
173
+ }
174
+ }
175
+
176
+ /** Where one offset of a template is, its column counted in UTF-16 code units. */
177
+ function positionIn(file: TemplateFile, offset: number): Position {
178
+ const before = file.text.slice(0, offset);
179
+ const lineStart = before.lastIndexOf("\n") + 1;
180
+ return {
181
+ path: file.path,
182
+ line: before.split("\n").length,
183
+ column: offset - lineStart + 1,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * The template-field detector: every instance member of a class and every member of
189
+ * an interface or an object type whose name an action of a configured template
190
+ * writes, recorded at the identifier.
191
+ */
192
+ export function templateField<Brand>(input: DetectorInput<Brand>): readonly Evidence[] {
193
+ const { templates } = input;
194
+ if (templates.files.length === 0) {
195
+ return [];
196
+ }
197
+ const members = memberNames(input.project.ownSourceFiles(), input.held);
198
+ const found: Evidence[] = [];
199
+ for (const file of templates.files) {
200
+ for (const named of namesOf(file.text, templates.delimiters)) {
201
+ for (const member of members.get(named.name) ?? []) {
202
+ if (!READ_BY_A_TEMPLATE.has(member.kind) || member.static) {
203
+ continue;
204
+ }
205
+ found.push({
206
+ id: member.id,
207
+ detail: `named by ${named.action}`,
208
+ site: positionIn(file, named.offset),
209
+ });
210
+ }
211
+ }
212
+ }
213
+ return found;
214
+ }