eslint-plugin-julia 0.0.0-stage → 0.3.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.
Files changed (115) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/LICENSE +21 -0
  3. package/README.md +213 -2
  4. package/data/base-core-exports.json +5 -0
  5. package/data/public-only.json +35 -0
  6. package/data/stdlib-exports.json +180 -0
  7. package/package.json +76 -4
  8. package/src/index.js +226 -0
  9. package/src/language.js +46 -0
  10. package/src/macro-signatures.js +277 -0
  11. package/src/module-resolution.js +1187 -0
  12. package/src/orphans.js +631 -0
  13. package/src/parser/flags.js +25 -0
  14. package/src/parser/green-tree.js +41 -0
  15. package/src/parser/positions.js +29 -0
  16. package/src/parser/syntax-tree.js +91 -0
  17. package/src/parser/wasm-host.js +92 -0
  18. package/src/resolver/index.js +232 -0
  19. package/src/resolver/pkg-child.mjs +165 -0
  20. package/src/resolver/toml.js +63 -0
  21. package/src/resolver/warm.mjs +26 -0
  22. package/src/rules/common.js +52 -0
  23. package/src/rules/correctness-common.js +90 -0
  24. package/src/rules/growth-common.js +93 -0
  25. package/src/rules/idiom-common.js +116 -0
  26. package/src/rules/no-collapsible-if.js +38 -0
  27. package/src/rules/no-collect-before-range-iteration.js +24 -0
  28. package/src/rules/no-compare-negative-zero.js +50 -0
  29. package/src/rules/no-concat-growth-in-loop.js +18 -0
  30. package/src/rules/no-cond-assign.js +126 -0
  31. package/src/rules/no-const-reassign.js +61 -0
  32. package/src/rules/no-constant-condition.js +59 -0
  33. package/src/rules/no-debugger.js +96 -0
  34. package/src/rules/no-discarded-copy-result.js +50 -0
  35. package/src/rules/no-dupe-args.js +25 -0
  36. package/src/rules/no-dupe-elseif.js +57 -0
  37. package/src/rules/no-duplicate-dict-keys.js +95 -0
  38. package/src/rules/no-duplicate-keyword-arguments.js +40 -0
  39. package/src/rules/no-duplicate-logical-operands.js +85 -0
  40. package/src/rules/no-duplicate-method-signatures.js +90 -0
  41. package/src/rules/no-duplicate-struct-fields.js +38 -0
  42. package/src/rules/no-empty-block.js +49 -0
  43. package/src/rules/no-empty-catch.js +32 -0
  44. package/src/rules/no-empty-literal-range.js +26 -0
  45. package/src/rules/no-env-mutation.js +62 -0
  46. package/src/rules/no-eval-local-symbol.js +85 -0
  47. package/src/rules/no-fill-with-mutable.js +43 -0
  48. package/src/rules/no-full-slice-in-consumer.js +41 -0
  49. package/src/rules/no-identical-branches.js +44 -0
  50. package/src/rules/no-import-assign.js +64 -0
  51. package/src/rules/no-impossible-length-comparison.js +49 -0
  52. package/src/rules/no-invalid-foreign-call-signature.js +58 -0
  53. package/src/rules/no-isdefined-local-call.js +23 -0
  54. package/src/rules/no-loss-of-float-integer-precision.js +41 -0
  55. package/src/rules/no-nothing-return-conversion.js +127 -0
  56. package/src/rules/no-obvious-type-piracy.js +112 -0
  57. package/src/rules/no-orphan-file.js +39 -0
  58. package/src/rules/no-overwritten-literal-index.js +80 -0
  59. package/src/rules/no-reassigned-capture.js +107 -0
  60. package/src/rules/no-redundant-type-assertion.js +36 -0
  61. package/src/rules/no-redundant-union-members.js +42 -0
  62. package/src/rules/no-restricted-calls.js +74 -0
  63. package/src/rules/no-restricted-imports.js +105 -0
  64. package/src/rules/no-restricted-macros.js +61 -0
  65. package/src/rules/no-self-assign.js +65 -0
  66. package/src/rules/no-self-identity-comparison.js +37 -0
  67. package/src/rules/no-shadowed-loop-var.js +83 -0
  68. package/src/rules/no-show-macro.js +90 -0
  69. package/src/rules/no-single-iteration-loop.js +50 -0
  70. package/src/rules/no-string-growth-in-loop.js +18 -0
  71. package/src/rules/no-throw-literal.js +33 -0
  72. package/src/rules/no-unbound-type-parameters.js +91 -0
  73. package/src/rules/no-undef.js +284 -0
  74. package/src/rules/no-undefined-exports.js +60 -0
  75. package/src/rules/no-uninitialized-ref-read.js +38 -0
  76. package/src/rules/no-unreachable.js +82 -0
  77. package/src/rules/no-unsafe-finally.js +35 -0
  78. package/src/rules/no-unsafe-negation.js +77 -0
  79. package/src/rules/no-unused-expressions.js +137 -0
  80. package/src/rules/no-unused-type-parameters.js +55 -0
  81. package/src/rules/no-unused-vars.js +123 -0
  82. package/src/rules/no-use-before-define.js +139 -0
  83. package/src/rules/no-useless-assignment.js +75 -0
  84. package/src/rules/no-useless-catch.js +28 -0
  85. package/src/rules/parse-errors.js +19 -0
  86. package/src/rules/performance-common.js +119 -0
  87. package/src/rules/prefer-any.js +75 -0
  88. package/src/rules/prefer-const-global.js +103 -0
  89. package/src/rules/prefer-count-over-findall-length.js +46 -0
  90. package/src/rules/prefer-eachindex.js +120 -0
  91. package/src/rules/prefer-extreme-over-sort.js +73 -0
  92. package/src/rules/prefer-generator-sum.js +34 -0
  93. package/src/rules/prefer-identity-nothing.js +43 -0
  94. package/src/rules/prefer-in.js +67 -0
  95. package/src/rules/prefer-isa.js +70 -0
  96. package/src/rules/prefer-isempty.js +57 -0
  97. package/src/rules/prefer-ismissing.js +42 -0
  98. package/src/rules/prefer-parenthesized-interpolation.js +160 -0
  99. package/src/rules/prefer-size-dimension.js +19 -0
  100. package/src/rules/prefer-sized-push-buffer.js +81 -0
  101. package/src/rules/prefer-typed-empty-array.js +90 -0
  102. package/src/rules/require-typed-global.js +60 -0
  103. package/src/rules/restricted-common.js +211 -0
  104. package/src/rules/semantic-common.js +105 -0
  105. package/src/rules/use-isnan.js +28 -0
  106. package/src/scope.js +1338 -0
  107. package/src/source-code.js +100 -0
  108. package/types/ast.d.ts +49 -0
  109. package/types/index.d.ts +65 -0
  110. package/types/scope.d.ts +71 -0
  111. package/wasm/LICENSES/Julia.md +26 -0
  112. package/wasm/LICENSES/JuliaSyntax-MIT.md +46 -0
  113. package/wasm/LICENSES/WasmCodegen-MIT.txt +21 -0
  114. package/wasm/manifest.json +44 -0
  115. package/wasm/parser.wasm +0 -0
package/src/orphans.js ADDED
@@ -0,0 +1,631 @@
1
+ // Which files of a package can run: the files its entry points reach through `include`.
2
+ // Syntactic only: never loads a package or executes Julia.
3
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
4
+ import { resolve, dirname, join, relative, sep, basename } from 'node:path';
5
+ import { parseJulia } from './parser/syntax-tree.js';
6
+ import { isInfixCall } from './parser/flags.js';
7
+ import { identifierName } from './scope.js';
8
+
9
+ // Files meant to be run on their own (relative to the package directory).
10
+ export const DEFAULT_SCRIPTS = [
11
+ '*.jl',
12
+ 'docs/**',
13
+ 'benchmark/**',
14
+ 'benchmarks/**',
15
+ 'bench/**',
16
+ 'perf/**',
17
+ 'examples/**',
18
+ 'scripts/**',
19
+ 'tools/**',
20
+ 'contrib/**',
21
+ 'gen/**',
22
+ 'bin/**',
23
+ 'deps/build.jl',
24
+ ];
25
+ // Functions that run (or load) a file given its path.
26
+ const INCLUDERS = new Set(['include', 'includet', 'evalfile', 'include_dependency']);
27
+
28
+ const mtime = (path) => {
29
+ try {
30
+ const s = statSync(path);
31
+ return `${s.mtimeMs}:${s.size}`;
32
+ } catch {
33
+ return null;
34
+ }
35
+ };
36
+ // Path joiners: `joinpath(a, b)`, `normpath(a, b)`, `abspath(a, b)`, `realpath(a)`.
37
+ const JOINERS = new Set(['joinpath', 'normpath', 'abspath', 'realpath']);
38
+ // Functions whose string arguments are directories: `push!(LOAD_PATH, "fixtures")`, `cd("x")`.
39
+ const DIRECTORY_CALLS = new Set(['push!', 'pushfirst!', 'cd', 'readdir', 'walkdir']);
40
+ const isDirectory = (path) => {
41
+ try {
42
+ return statSync(path).isDirectory();
43
+ } catch {
44
+ return false;
45
+ }
46
+ };
47
+ const posix = (path) => path.split(sep).join('/');
48
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
49
+
50
+ // `**` any depth, `*` and `?` within one path segment.
51
+ export function globRegExp(glob) {
52
+ let out = '';
53
+ for (let i = 0; i < glob.length; i++) {
54
+ const c = glob[i];
55
+ if (c === '*' && glob[i + 1] === '*') {
56
+ i++;
57
+ if (glob[i + 1] === '/') {
58
+ i++;
59
+ out += '(?:.*/)?';
60
+ } else out += '.*';
61
+ } else if (c === '*') out += '[^/]*';
62
+ else if (c === '?') out += '[^/]';
63
+ else out += escape(c);
64
+ }
65
+ return new RegExp(`^${out}$`, 'u');
66
+ }
67
+
68
+ // The nearest named Project.toml: { dir, name, extensions }.
69
+ const projects = new Map();
70
+ export function packageFor(file) {
71
+ for (let dir = dirname(file); ; dir = dirname(dir)) {
72
+ const path = join(dir, 'Project.toml'),
73
+ version = mtime(path);
74
+ let cached = projects.get(path);
75
+ if (cached?.version !== version) {
76
+ cached = { version, value: version ? readProject(path, dir) : null };
77
+ projects.set(path, cached);
78
+ }
79
+ if (cached.value?.name) return cached.value;
80
+ if (dirname(dir) === dir) return null;
81
+ }
82
+ }
83
+ function readProject(path, dir) {
84
+ let text;
85
+ try {
86
+ text = readFileSync(path, 'utf8');
87
+ } catch {
88
+ return null;
89
+ }
90
+ const result = { dir, name: null, extensions: [] };
91
+ let table = '';
92
+ for (const line of text.split(/\r?\n/u)) {
93
+ const header = line.match(/^\s*\[\s*([^\]]+?)\s*\]/u);
94
+ if (header) {
95
+ table = header[1];
96
+ continue;
97
+ }
98
+ const key = line.match(/^\s*(?:"([^"]+)"|([\w-]+))\s*=\s*(.*)$/u);
99
+ if (!key) continue;
100
+ if (!table && key[2] === 'name') result.name = key[3].match(/^"([^"]*)"/u)?.[1] ?? null;
101
+ if (table === 'extensions') result.extensions.push(key[1] ?? key[2]);
102
+ }
103
+ return result;
104
+ }
105
+
106
+ // A path expression as literal pieces (strings) and unknown pieces (null).
107
+ function pathPieces(node, file, env, depth = 0) {
108
+ if (!node || depth > 8) return [null];
109
+ const c = node.children ?? [];
110
+ switch (node.kind) {
111
+ case 'string':
112
+ return c.flatMap((p) =>
113
+ p.kind === 'String' && !p.value.includes('\\')
114
+ ? [p.value]
115
+ : pathPieces(p.kind === 'parens' ? p.children[0] : p, file, env, depth + 1),
116
+ );
117
+ case 'parens':
118
+ return c.length === 1 ? pathPieces(c[0], file, env, depth + 1) : [null];
119
+ case 'macrocall': {
120
+ const name = identifierName(c[0]);
121
+ if (c.length === 1 && name === '@__DIR__') return [dirname(file)];
122
+ if (c.length === 1 && name === '@__FILE__') return [file];
123
+ return [null];
124
+ }
125
+ case 'Identifier':
126
+ return env.get(node.value)?.(depth + 1) ?? [null];
127
+ case 'call': {
128
+ if (isInfixCall(node))
129
+ return identifierName(c[1]) === '*'
130
+ ? [c[0], ...c.slice(2)].flatMap((p) => pathPieces(p, file, env, depth + 1))
131
+ : [null];
132
+ const head = c[0],
133
+ name =
134
+ identifierName(head) ??
135
+ (head?.kind === '.' ? identifierName(head.children.at(-1)) : null),
136
+ args = c.slice(1).filter((a) => a.kind !== 'parameters');
137
+ if (JOINERS.has(name) && args.length)
138
+ return args.flatMap((a, i) => [
139
+ ...(i ? ['/'] : []),
140
+ ...pathPieces(a, file, env, depth + 1),
141
+ ]);
142
+ if (name === 'string') return args.flatMap((a) => pathPieces(a, file, env, depth + 1));
143
+ if (name === 'dirname' && args.length === 1) {
144
+ const inner = pathPieces(args[0], file, env, depth + 1);
145
+ return inner.every((p) => p !== null)
146
+ ? [dirname(resolve(dirname(file), inner.join('')))]
147
+ : [null];
148
+ }
149
+ if (name === 'pkgdir') {
150
+ const p = packageFor(file);
151
+ return p ? [p.dir] : [null];
152
+ }
153
+ return [null];
154
+ }
155
+ default:
156
+ return [null];
157
+ }
158
+ }
159
+ // What a path expression can name: one file, or the files a pattern matches.
160
+ function matcher(pieces, file) {
161
+ const merged = [];
162
+ for (const p of pieces)
163
+ if (typeof p === 'string' && typeof merged.at(-1) === 'string') merged[merged.length - 1] += p;
164
+ else merged.push(p);
165
+ if (merged.every((p) => p !== null)) return { path: resolve(dirname(file), merged.join('')) };
166
+ // The pattern starts in the including file's directory (`include`'s own rule; `@__DIR__`
167
+ // paths are absolute) joined with the pattern's literal leading directories (`../lib/`).
168
+ const head = typeof merged[0] === 'string' ? posix(merged.shift()) : '';
169
+ const cut = head.lastIndexOf('/');
170
+ const dir = posix(resolve(dirname(file), head.slice(0, cut + 1) || '.')).replace(/\/$/u, '');
171
+ // More than two unknown spans would make the regular expression backtrack badly on long
172
+ // names; such a path could name any file below its literal directory.
173
+ if (merged.filter((p) => p === null).length > 2) return { pattern: `^${escape(dir)}/.*$` };
174
+ const body = [head.slice(cut + 1), ...merged]
175
+ .map((p) => (p === null ? '.*' : escape(posix(p))))
176
+ .join('')
177
+ .replace(/\/+/gu, '/')
178
+ .replace(/^\//u, '');
179
+ return { pattern: `^${escape(dir)}/${body}$` };
180
+ }
181
+
182
+ // Per file: the files it names to `include` (exact paths and patterns), and whether it
183
+ // couldn't be read.
184
+ const reachCache = new Map();
185
+ export function includesOf(file) {
186
+ const version = mtime(file);
187
+ const cached = reachCache.get(file);
188
+ if (cached?.version === version) return cached.value;
189
+ const value = {
190
+ paths: new Set(),
191
+ patterns: new Set(),
192
+ // Bare `.jl` file names mentioned, and every literal word (directory names spelled
193
+ // separately: `joinpath(root(), "src", "runner")`).
194
+ names: new Set(),
195
+ words: new Set(),
196
+ // The patterns of computed `include` calls alone (not of paths merely named).
197
+ computed: new Set(),
198
+ unknown: false,
199
+ listed: [],
200
+ unknownInclude: false,
201
+ valueInclude: false,
202
+ live: false,
203
+ };
204
+ let parsed;
205
+ try {
206
+ parsed = parseJulia(readFileSync(file, 'utf8'));
207
+ } catch {
208
+ parsed = null;
209
+ }
210
+ if (!parsed || parsed.diagnostics.some((d) => d.level === 1)) value.unknown = true;
211
+ else collect(parsed.ast ?? parsed.tree, file, value);
212
+ settle(value, file);
213
+ reachCache.set(file, { version, value });
214
+ return value;
215
+ }
216
+ // The `$(…)` parts of a command literal.
217
+ function interpolations(text) {
218
+ const parts = [];
219
+ for (let i = text.indexOf('$('); i >= 0; i = text.indexOf('$(', i + 1)) {
220
+ let depth = 0;
221
+ for (let j = i + 1; j < text.length; j++) {
222
+ if (text[j] === '(') depth++;
223
+ else if (text[j] === ')' && --depth === 0) {
224
+ parts.push(text.slice(i + 2, j));
225
+ break;
226
+ }
227
+ }
228
+ }
229
+ return parts;
230
+ }
231
+ function collect(root, file, out, outer = null) {
232
+ // Names assigned once in the file (`const TESTDIR = joinpath(@__DIR__, "x")`), and loop
233
+ // variables over `readdir(dir; join = true)`: their path pieces.
234
+ const assigned = new Map(),
235
+ env = new Map(outer ?? []);
236
+ // `quoted`: inside a quote or a macro definition, code that may never run as written.
237
+ const visit = (node, fn, quoted = false) => {
238
+ fn(node, quoted);
239
+ const inner = quoted || node.kind === 'quote' || node.kind === 'macro';
240
+ for (const child of node.children ?? []) visit(child, fn, inner);
241
+ };
242
+ visit(root, (node) => {
243
+ let target = null,
244
+ value = null;
245
+ if (node.kind === '=' && node.children.length === 2) [target, value] = node.children;
246
+ if (node.kind === 'const' && node.children[0]?.kind === '=')
247
+ [target, value] = node.children[0].children;
248
+ if (target?.kind === 'Identifier') {
249
+ if (!assigned.has(target.value)) assigned.set(target.value, []);
250
+ assigned.get(target.value).push({ value, loop: false });
251
+ }
252
+ if (node.kind === 'iteration')
253
+ for (const spec of node.children)
254
+ if (['in', '=', '∈'].includes(spec.kind) && spec.children[0]?.kind === 'Identifier') {
255
+ const name = spec.children[0].value;
256
+ if (!assigned.has(name)) assigned.set(name, []);
257
+ assigned.get(name).push({ value: spec.children[1], loop: true });
258
+ }
259
+ });
260
+ for (const [name, values] of assigned) {
261
+ if (values.length !== 1 || outer) continue;
262
+ const [{ value, loop }] = values;
263
+ env.set(name, (depth) => {
264
+ if (!loop) return pathPieces(value, file, env, depth);
265
+ // `for f in readdir(dir; join = true)`: a file of `dir`.
266
+ const head = identifierName(value?.children?.[0]);
267
+ const join = value?.children?.some(
268
+ (p) =>
269
+ p.kind === 'parameters' &&
270
+ p.children.some((k) => identifierName(k.children?.[0]) === 'join'),
271
+ );
272
+ if (
273
+ value?.kind === 'call' &&
274
+ head === 'readdir' &&
275
+ join &&
276
+ value.children[1]?.kind !== 'parameters'
277
+ )
278
+ return [...pathPieces(value.children[1], file, env, depth), '/', null];
279
+ return [null];
280
+ });
281
+ }
282
+ const directory = (text) => {
283
+ const path = resolve(dirname(file), text);
284
+ if (isDirectory(path) && !posix(dirname(file) + sep).startsWith(posix(path + sep)))
285
+ out.patterns.add(`^${escape(posix(path))}/.*$`);
286
+ };
287
+ const add = (pieces) => {
288
+ const m = matcher(pieces, file);
289
+ if (m.path) out.paths.add(m.path);
290
+ else out.patterns.add(m.pattern);
291
+ };
292
+ visit(root, (node, quoted) => {
293
+ const c = node.children ?? [];
294
+ if (node.kind === 'call' || node.kind === 'dotcall') {
295
+ const head = c[0],
296
+ name =
297
+ identifierName(head) ??
298
+ (head?.kind === '.' ? identifierName(head.children.at(-1)) : null);
299
+ if (INCLUDERS.has(name) && !isInfixCall(node)) {
300
+ const args = c.slice(1).filter((a) => a.kind !== 'parameters');
301
+ // `include(M, path)`: the path is the last argument. `include.(paths)` maps over paths.
302
+ const path = args.at(-1);
303
+ const pieces = path && node.kind === 'call' ? pathPieces(path, file, env) : null;
304
+ if (pieces?.some((p) => p !== null)) {
305
+ const m = matcher(pieces, file);
306
+ if (m.pattern && !quoted) out.computed.add(m.pattern);
307
+ add(pieces);
308
+ } else if (pieces) {
309
+ out.unknownInclude = true;
310
+ if (!quoted) out.live = true;
311
+ } else if (path) {
312
+ out.valueInclude = true;
313
+ if (!quoted) out.live = true;
314
+ }
315
+ }
316
+ // `readdir(dir)`, `walkdir(dir)`: the directories a computed include may list.
317
+ if (['readdir', 'walkdir'].includes(name) && node.kind === 'call') {
318
+ const dir = c.slice(1).find((a) => a.kind !== 'parameters');
319
+ out.listed.push(dir ? [...pathPieces(dir, file, env), '/', null] : [null]);
320
+ }
321
+ }
322
+ // A `.jl` path named anywhere (a list of test files, a script run in a subprocess), or a
323
+ // directory named as a path (a fixtures directory, a `LOAD_PATH` entry): its files can
324
+ // run. A bare word naming a directory (`@testset "integration"`) is not a path.
325
+ const callee = node.kind === 'call' ? identifierName(c[0]) : null;
326
+ if (node.kind === 'string' || JOINERS.has(callee)) {
327
+ const pieces = pathPieces(node, file, env);
328
+ if (pieces.every((p) => p !== null)) {
329
+ const text = pieces.join('');
330
+ const bare = node.kind === 'string' && !/[\\/]/u.test(text);
331
+ if (bare) out.words.add(text);
332
+ if (text.endsWith('.jl')) {
333
+ out.paths.add(resolve(dirname(file), text));
334
+ // A bare file name (`joinpath(root(), "src", "runner", "Loader.jl")`) may be a
335
+ // package file of that name elsewhere.
336
+ if (bare) out.names.add(text);
337
+ } else if (JOINERS.has(callee) || /[\\/]/u.test(text)) directory(text);
338
+ } else if (typeof pieces.at(-1) === 'string' && pieces.at(-1).endsWith('.jl')) add(pieces);
339
+ }
340
+ if (DIRECTORY_CALLS.has(callee))
341
+ for (const arg of c.slice(1)) {
342
+ const pieces = arg.kind === 'string' ? pathPieces(arg, file, env) : [null];
343
+ if (pieces.every((p) => p !== null)) directory(pieces.join(''));
344
+ }
345
+ // Command literals aren't parsed into interpolations: their `$(…)` parts and `.jl` words.
346
+ if (node.kind === 'CmdString') {
347
+ const text = String(node.value);
348
+ for (const code of interpolations(text)) {
349
+ let parsed;
350
+ try {
351
+ parsed = parseJulia(code);
352
+ } catch {
353
+ continue;
354
+ }
355
+ if (parsed.diagnostics.some((d) => d.level === 1)) continue;
356
+ collect(parsed.ast ?? parsed.tree, file, out, env);
357
+ }
358
+ for (const [word] of text.replace(/\$\([^)]*\)/gu, ' ').matchAll(/[^\s"'`$()]+\.jl\b/gu))
359
+ out.paths.add(resolve(dirname(file), word));
360
+ }
361
+ // `include` passed as a value (`map(include, files)`, `foreach(include, …)`).
362
+ if ((node.kind === 'call' || node.kind === 'dotcall') && !isInfixCall(node))
363
+ for (const arg of c.slice(1))
364
+ if (arg.kind === 'Identifier' && INCLUDERS.has(arg.value)) {
365
+ out.valueInclude = true;
366
+ if (!quoted) out.live = true;
367
+ }
368
+ });
369
+ }
370
+ // An include of a computed path (`include(f)`, `foreach(include, files)`) reaches the
371
+ // directories the file lists (`readdir`, `walkdir`); without one, `include(f)` reaches any file
372
+ // below the including file's directory. Literal paths the collection is built from are
373
+ // mentions of their own.
374
+ function settle(out, file) {
375
+ if (out.unknownInclude || out.valueInclude) {
376
+ const patterns = out.listed.length
377
+ ? out.listed.map((pieces) => matcher(pieces, file).pattern).filter(Boolean)
378
+ : out.unknownInclude
379
+ ? [matcher([null], file).pattern]
380
+ : [];
381
+ for (const p of patterns) {
382
+ out.patterns.add(p);
383
+ if (out.live) out.computed.add(p);
384
+ }
385
+ }
386
+ delete out.listed;
387
+ delete out.unknownInclude;
388
+ delete out.valueInclude;
389
+ delete out.live;
390
+ return out;
391
+ }
392
+
393
+ // A file run without being included: a shebang script, a file of test items (discovered by
394
+ // TestItemRunner or ReTestItems), a Pluto notebook, a script that reads its command line or
395
+ // exits the process, one whose comments say how to run it (`julia --project test/x.jl`).
396
+ const RUN_ON_ITS_OWN =
397
+ /^#!|^\s*@test(?:item|module|snippet|setup)\b|^### A Pluto\.jl notebook ###|\bARGS\b|^\s*exit\(/mu;
398
+ const ownCache = new Map();
399
+ function runsOnItsOwn(file, text) {
400
+ if (text !== undefined) return ownScript(file, text);
401
+ const version = mtime(file);
402
+ const cached = ownCache.get(file);
403
+ if (cached?.version === version) return cached.value;
404
+ let value = false;
405
+ try {
406
+ value = ownScript(file, readFileSync(file, 'utf8'));
407
+ } catch {
408
+ /* unreadable */
409
+ }
410
+ ownCache.set(file, { version, value });
411
+ return value;
412
+ }
413
+ function ownScript(file, text) {
414
+ if (RUN_ON_ITS_OWN.test(text)) return true;
415
+ const name = escape(basename(file));
416
+ return new RegExp(`^\\s*#.*\\bjulia\\b.*(?:^|[\\s/])${name}\\b`, 'mu').test(text);
417
+ }
418
+ // Shell scripts and build files that may run a Julia file by its path.
419
+ const RUNNER = /^(?:.*\.(?:sh|bash|ps1|cmd|bat|mk|ya?ml)|Makefile|justfile|Justfile)$/u;
420
+ // The CI configuration of the repository around `dir`.
421
+ function ciFiles(dir) {
422
+ let root = null;
423
+ for (let at = dir; ; at = dirname(at)) {
424
+ if (mtime(join(at, '.git'))) {
425
+ root = at;
426
+ break;
427
+ }
428
+ if (dirname(at) === at) break;
429
+ }
430
+ if (!root) return { root: dir, files: [] };
431
+ const files = [];
432
+ for (const sub of ['.github/workflows', '.buildkite', '.ci', '.gitlab'])
433
+ try {
434
+ for (const e of readdirSync(join(root, sub), { withFileTypes: true }))
435
+ if (e.isFile()) files.push(join(root, sub, e.name));
436
+ } catch {
437
+ /* no such directory */
438
+ }
439
+ for (const name of ['.gitlab-ci.yml', '.travis.yml', 'appveyor.yml', 'Makefile'])
440
+ if (mtime(join(root, name))) files.push(join(root, name));
441
+ return { root, files };
442
+ }
443
+ // The `.jl` files of a package directory, without nested packages or hidden directories.
444
+ function packageFiles(
445
+ dir,
446
+ root = dir,
447
+ out = { files: [], runners: [], nested: [], dirs: new Map() },
448
+ ) {
449
+ out.dirs.set(dir, mtime(dir));
450
+ let entries;
451
+ try {
452
+ entries = readdirSync(dir, { withFileTypes: true });
453
+ } catch {
454
+ return out;
455
+ }
456
+ for (const e of entries) {
457
+ if (e.name.startsWith('.') || e.name === 'node_modules') continue;
458
+ const path = join(dir, e.name);
459
+ if (e.isDirectory()) {
460
+ if (packageFor(join(path, 'x.jl'))?.dir === path) {
461
+ out.nested.push(packageFor(join(path, 'x.jl')));
462
+ continue;
463
+ }
464
+ packageFiles(path, root, out);
465
+ } else if (e.name.endsWith('.jl')) out.files.push(path);
466
+ else if (RUNNER.test(e.name)) out.runners.push(path);
467
+ }
468
+ return out;
469
+ }
470
+
471
+ // `text` names the relative path `path` as a whole word.
472
+ const mentions = (text, path) => {
473
+ let at = text.indexOf(path);
474
+ while (at >= 0) {
475
+ const before = text[at - 1],
476
+ after = text[at + path.length];
477
+ if ((!before || !/[\w.-]/u.test(before)) && (!after || !/[\w-]/u.test(after))) return true;
478
+ at = text.indexOf(path, at + 1);
479
+ }
480
+ return false;
481
+ };
482
+ // The files of `pkg` its entry points reach, cached until a visited file or directory changes.
483
+ const packageCache = new Map();
484
+ export function reachable(pkg, options) {
485
+ const key = JSON.stringify([pkg.dir, options.entryPoints, options.scripts]);
486
+ const cached = packageCache.get(key);
487
+ if (
488
+ cached &&
489
+ [...cached.versions].every(([p, v]) => mtime(p) === v) &&
490
+ [...cached.listing.dirs].every(([p, v]) => mtime(p) === v)
491
+ )
492
+ return cached.value;
493
+ const listing = packageFiles(pkg.dir);
494
+ const rel = (f) => posix(relative(pkg.dir, f));
495
+ const entriesOf = (p) =>
496
+ [
497
+ join(p.dir, 'src', `${p.name}.jl`),
498
+ join(p.dir, 'test', 'runtests.jl'),
499
+ ...p.extensions.flatMap((ext) => [
500
+ join(p.dir, 'ext', `${ext}.jl`),
501
+ join(p.dir, 'ext', ext, `${ext}.jl`),
502
+ ]),
503
+ ].filter((f) => mtime(f));
504
+ const entryRegs = options.entryPoints.map(globRegExp),
505
+ scriptRegs = options.scripts.map(globRegExp);
506
+ const entries = entriesOf(pkg);
507
+ const configured = listing.files.filter((f) => entryRegs.some((r) => r.test(rel(f))));
508
+ // Every `runtests.jl` is a test harness (a sub-suite run on its own: `test/trim/runtests.jl`).
509
+ const harnesses = listing.files.filter((f) => basename(f) === 'runtests.jl');
510
+ const scripts = listing.files.filter(
511
+ (f) => scriptRegs.some((r) => r.test(rel(f))) || runsOnItsOwn(f),
512
+ );
513
+ const versions = new Map(),
514
+ reached = new Set(),
515
+ // A package below this one (a monorepo's `lib/Sub`) may include this one's files
516
+ // (`include("../../../test/shared/common.jl")`).
517
+ queue = [
518
+ ...entries,
519
+ ...configured,
520
+ ...harnesses,
521
+ ...scripts,
522
+ ...listing.nested.flatMap(entriesOf),
523
+ ],
524
+ patterns = [];
525
+ // Its `[extensions]` decide the entry points.
526
+ const project = join(pkg.dir, 'Project.toml');
527
+ versions.set(project, mtime(project));
528
+ // Files that CI or a shell script runs by path (`julia --project test/quality.jl`).
529
+ const ci = ciFiles(pkg.dir),
530
+ run = [];
531
+ for (const runner of [...new Set([...ci.files, ...listing.runners])]) {
532
+ versions.set(runner, mtime(runner));
533
+ try {
534
+ const text = readFileSync(runner, 'utf8');
535
+ for (const f of listing.files) {
536
+ // The path from the repository root, any tail of it with a directory
537
+ // (`test/quality.jl`, run from the package directory), or the bare name in a script
538
+ // beside the file.
539
+ const parts = posix(relative(ci.root, f)).split('/');
540
+ const names = parts.slice(0, -1).map((_, i) => parts.slice(i).join('/'));
541
+ if (dirname(runner) === dirname(f)) names.push(parts.at(-1));
542
+ if (names.some((n) => mentions(text, n))) run.push(f);
543
+ }
544
+ } catch {
545
+ /* unreadable */
546
+ }
547
+ }
548
+ queue.push(...run);
549
+ const named = [];
550
+ // A bare file name reaches a package file of that name when the mentioning file also spells
551
+ // each directory of its path (`"src", "runner", "Loader.jl"`).
552
+ const spelled = (f) => {
553
+ const parts = rel(f).split('/');
554
+ const dirs = parts.slice(0, -1);
555
+ return named.some((n) => n.names.has(parts.at(-1)) && dirs.every((d) => n.words.has(d)));
556
+ };
557
+ const visit = (file) => {
558
+ if (reached.has(file)) return;
559
+ reached.add(file);
560
+ versions.set(file, mtime(file));
561
+ if (!versions.get(file)) return;
562
+ const facts = includesOf(file);
563
+ if (facts.unknown) patterns.push(new RegExp(`^${escape(posix(dirname(file)))}/.*$`, 'u'));
564
+ for (const p of facts.paths) queue.push(p);
565
+ if (facts.names.size) named.push(facts);
566
+ for (const p of facts.patterns) patterns.push(new RegExp(p, 'u'));
567
+ };
568
+ for (;;) {
569
+ while (queue.length) visit(queue.pop());
570
+ const more = listing.files.filter(
571
+ (f) => !reached.has(f) && (spelled(f) || patterns.some((r) => r.test(posix(f)))),
572
+ );
573
+ if (!more.length) break;
574
+ queue.push(...more);
575
+ }
576
+ const value = { entries, configured: configured.length > 0, reached };
577
+ packageCache.set(key, { versions, listing, value });
578
+ if (packageCache.size > 64) packageCache.delete(packageCache.keys().next().value);
579
+ return value;
580
+ }
581
+
582
+ // Why `file` never runs, or null: the package and entry points that don't reach it.
583
+ export function orphan(file, options = {}, text = '') {
584
+ const o = {
585
+ entryPoints: options.entryPoints ?? [],
586
+ scripts: options.scripts ?? DEFAULT_SCRIPTS,
587
+ };
588
+ const pkg = packageFor(file);
589
+ if (!pkg) return null;
590
+ const rel = posix(relative(pkg.dir, file));
591
+ // Hidden directories hold tool configuration (`.ci/`, `.pkg/` hooks Pkg runs).
592
+ if (rel.split('/').some((part) => part.startsWith('.'))) return null;
593
+ if (runsOnItsOwn(file, text)) return null;
594
+ // A file with an environment of its own (a nested Project.toml other than the package's test
595
+ // environment) is run in that environment, not by the package: `julia --project=tools x.jl`.
596
+ for (let dir = dirname(file); dir !== pkg.dir && dir.startsWith(pkg.dir); dir = dirname(dir)) {
597
+ const env = posix(relative(pkg.dir, dir));
598
+ if (env !== 'test' && env !== 'tests' && mtime(join(dir, 'Project.toml'))) return null;
599
+ }
600
+ // A package inside another package's tests is a fixture its tests copy or load.
601
+ const outer = packageFor(pkg.dir);
602
+ if (
603
+ outer &&
604
+ posix(relative(outer.dir, pkg.dir))
605
+ .split('/')
606
+ .some((p) => p === 'test' || p === 'tests')
607
+ )
608
+ return null;
609
+ if ([...o.entryPoints, ...o.scripts].some((g) => globRegExp(g).test(rel))) return null;
610
+ // A test harness that names no file (`runtests(Pkg, ARGS)` of a test runner that discovers
611
+ // the files itself): reachability under `test/` can't be measured.
612
+ const harness = join(pkg.dir, 'test', 'runtests.jl');
613
+ if (rel.startsWith('test/') && mtime(harness)) {
614
+ const named = includesOf(harness);
615
+ if (!named.unknown && !named.paths.size && !named.patterns.size) return null;
616
+ }
617
+ const result = reachable(pkg, o);
618
+ // No entry point found: nothing to measure reachability against.
619
+ if (!result.entries.length && !result.configured) return null;
620
+ if (result.reached.has(file)) return null;
621
+ // The entry points named in the message: the package module, extensions, tests, and any
622
+ // configured ones.
623
+ const names = result.entries.map((e) => posix(relative(pkg.dir, e)));
624
+ const entries = [
625
+ ...names.filter((n) => n.startsWith('src/')),
626
+ ...(names.some((n) => n.startsWith('ext/')) ? ['ext/'] : []),
627
+ ...names.filter((n) => n.startsWith('test/')),
628
+ ...(result.configured ? ['entryPoints'] : []),
629
+ ];
630
+ return { pkg, entries };
631
+ }
@@ -0,0 +1,25 @@
1
+ // These meanings are pinned to the manifest's JuliaSyntax grammar. Never interpret
2
+ // overloaded bits 8/9 without checking the kind.
3
+ export const isInfixCall = (n) =>
4
+ ['call', 'dotcall'].includes(n.kind) && n.interior && (n.flags & 24) === 8;
5
+ export const isPrefixCall = (n) => n.kind === 'call' && n.interior && (n.flags & 24) === 0;
6
+ export const isPrefixOperatorCall = (n) => n.kind === 'call' && n.interior && (n.flags & 24) === 16;
7
+ export const isMutableStruct = (n) => n.kind === 'struct' && n.interior && Boolean(n.flags & 256);
8
+ export const isTripleString = (n) =>
9
+ ['string', 'cmdstring'].includes(n.kind) && n.interior && Boolean(n.flags & 256);
10
+ export const isShortFunction = (n) => n.kind === 'function' && n.interior && Boolean(n.flags & 256);
11
+ export const hasTrailingComma = (n) =>
12
+ ['tuple', 'call', 'dotcall', 'curly', 'ref', 'vect', 'braces', 'parameters'].includes(n.kind) &&
13
+ n.interior &&
14
+ Boolean(n.flags & 512);
15
+ export const semanticChildren = (n) => n.children;
16
+ export const getOperatorToken = (n) =>
17
+ isInfixCall(n) ? n.children[1] : isPrefixOperatorCall(n) ? n.children[0] : undefined;
18
+ export function isInsideMacro(n, source) {
19
+ for (let p = n; p; p = source.getParent(p)) if (p.kind === 'macrocall') return true;
20
+ return false;
21
+ }
22
+ export function isQuoted(n, source) {
23
+ for (let p = n; p; p = source.getParent(p)) if (['quote', 'inert'].includes(p.kind)) return true;
24
+ return false;
25
+ }