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.
- package/CHANGELOG.md +159 -0
- package/LICENSE +21 -0
- package/README.md +213 -2
- package/data/base-core-exports.json +5 -0
- package/data/public-only.json +35 -0
- package/data/stdlib-exports.json +180 -0
- package/package.json +76 -4
- package/src/index.js +226 -0
- package/src/language.js +46 -0
- package/src/macro-signatures.js +277 -0
- package/src/module-resolution.js +1187 -0
- package/src/orphans.js +631 -0
- package/src/parser/flags.js +25 -0
- package/src/parser/green-tree.js +41 -0
- package/src/parser/positions.js +29 -0
- package/src/parser/syntax-tree.js +91 -0
- package/src/parser/wasm-host.js +92 -0
- package/src/resolver/index.js +232 -0
- package/src/resolver/pkg-child.mjs +165 -0
- package/src/resolver/toml.js +63 -0
- package/src/resolver/warm.mjs +26 -0
- package/src/rules/common.js +52 -0
- package/src/rules/correctness-common.js +90 -0
- package/src/rules/growth-common.js +93 -0
- package/src/rules/idiom-common.js +116 -0
- package/src/rules/no-collapsible-if.js +38 -0
- package/src/rules/no-collect-before-range-iteration.js +24 -0
- package/src/rules/no-compare-negative-zero.js +50 -0
- package/src/rules/no-concat-growth-in-loop.js +18 -0
- package/src/rules/no-cond-assign.js +126 -0
- package/src/rules/no-const-reassign.js +61 -0
- package/src/rules/no-constant-condition.js +59 -0
- package/src/rules/no-debugger.js +96 -0
- package/src/rules/no-discarded-copy-result.js +50 -0
- package/src/rules/no-dupe-args.js +25 -0
- package/src/rules/no-dupe-elseif.js +57 -0
- package/src/rules/no-duplicate-dict-keys.js +95 -0
- package/src/rules/no-duplicate-keyword-arguments.js +40 -0
- package/src/rules/no-duplicate-logical-operands.js +85 -0
- package/src/rules/no-duplicate-method-signatures.js +90 -0
- package/src/rules/no-duplicate-struct-fields.js +38 -0
- package/src/rules/no-empty-block.js +49 -0
- package/src/rules/no-empty-catch.js +32 -0
- package/src/rules/no-empty-literal-range.js +26 -0
- package/src/rules/no-env-mutation.js +62 -0
- package/src/rules/no-eval-local-symbol.js +85 -0
- package/src/rules/no-fill-with-mutable.js +43 -0
- package/src/rules/no-full-slice-in-consumer.js +41 -0
- package/src/rules/no-identical-branches.js +44 -0
- package/src/rules/no-import-assign.js +64 -0
- package/src/rules/no-impossible-length-comparison.js +49 -0
- package/src/rules/no-invalid-foreign-call-signature.js +58 -0
- package/src/rules/no-isdefined-local-call.js +23 -0
- package/src/rules/no-loss-of-float-integer-precision.js +41 -0
- package/src/rules/no-nothing-return-conversion.js +127 -0
- package/src/rules/no-obvious-type-piracy.js +112 -0
- package/src/rules/no-orphan-file.js +39 -0
- package/src/rules/no-overwritten-literal-index.js +80 -0
- package/src/rules/no-reassigned-capture.js +107 -0
- package/src/rules/no-redundant-type-assertion.js +36 -0
- package/src/rules/no-redundant-union-members.js +42 -0
- package/src/rules/no-restricted-calls.js +74 -0
- package/src/rules/no-restricted-imports.js +105 -0
- package/src/rules/no-restricted-macros.js +61 -0
- package/src/rules/no-self-assign.js +65 -0
- package/src/rules/no-self-identity-comparison.js +37 -0
- package/src/rules/no-shadowed-loop-var.js +83 -0
- package/src/rules/no-show-macro.js +90 -0
- package/src/rules/no-single-iteration-loop.js +50 -0
- package/src/rules/no-string-growth-in-loop.js +18 -0
- package/src/rules/no-throw-literal.js +33 -0
- package/src/rules/no-unbound-type-parameters.js +91 -0
- package/src/rules/no-undef.js +284 -0
- package/src/rules/no-undefined-exports.js +60 -0
- package/src/rules/no-uninitialized-ref-read.js +38 -0
- package/src/rules/no-unreachable.js +82 -0
- package/src/rules/no-unsafe-finally.js +35 -0
- package/src/rules/no-unsafe-negation.js +77 -0
- package/src/rules/no-unused-expressions.js +137 -0
- package/src/rules/no-unused-type-parameters.js +55 -0
- package/src/rules/no-unused-vars.js +123 -0
- package/src/rules/no-use-before-define.js +139 -0
- package/src/rules/no-useless-assignment.js +75 -0
- package/src/rules/no-useless-catch.js +28 -0
- package/src/rules/parse-errors.js +19 -0
- package/src/rules/performance-common.js +119 -0
- package/src/rules/prefer-any.js +75 -0
- package/src/rules/prefer-const-global.js +103 -0
- package/src/rules/prefer-count-over-findall-length.js +46 -0
- package/src/rules/prefer-eachindex.js +120 -0
- package/src/rules/prefer-extreme-over-sort.js +73 -0
- package/src/rules/prefer-generator-sum.js +34 -0
- package/src/rules/prefer-identity-nothing.js +43 -0
- package/src/rules/prefer-in.js +67 -0
- package/src/rules/prefer-isa.js +70 -0
- package/src/rules/prefer-isempty.js +57 -0
- package/src/rules/prefer-ismissing.js +42 -0
- package/src/rules/prefer-parenthesized-interpolation.js +160 -0
- package/src/rules/prefer-size-dimension.js +19 -0
- package/src/rules/prefer-sized-push-buffer.js +81 -0
- package/src/rules/prefer-typed-empty-array.js +90 -0
- package/src/rules/require-typed-global.js +60 -0
- package/src/rules/restricted-common.js +211 -0
- package/src/rules/semantic-common.js +105 -0
- package/src/rules/use-isnan.js +28 -0
- package/src/scope.js +1338 -0
- package/src/source-code.js +100 -0
- package/types/ast.d.ts +49 -0
- package/types/index.d.ts +65 -0
- package/types/scope.d.ts +71 -0
- package/wasm/LICENSES/Julia.md +26 -0
- package/wasm/LICENSES/JuliaSyntax-MIT.md +46 -0
- package/wasm/LICENSES/WasmCodegen-MIT.txt +21 -0
- package/wasm/manifest.json +44 -0
- package/wasm/parser.wasm +0 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Postorder placement ported from proto/parser.mjs and topiary-julia/src/jlparse.rs.
|
|
2
|
+
// Place ALL leaves, including nonzero TOMBSTONEs, before removing any trivia.
|
|
3
|
+
export function placeGreen(raw, byteLength) {
|
|
4
|
+
const nodes = [],
|
|
5
|
+
stack = [];
|
|
6
|
+
let cursor = 0;
|
|
7
|
+
for (let i = 0; i < raw.length; i++) {
|
|
8
|
+
const o = raw[i],
|
|
9
|
+
interior = Boolean(o.class & 1),
|
|
10
|
+
children = [];
|
|
11
|
+
if (
|
|
12
|
+
!Number.isInteger(o.span) ||
|
|
13
|
+
o.span < 0 ||
|
|
14
|
+
!Number.isInteger(o.nodespan) ||
|
|
15
|
+
o.nodespan < 0
|
|
16
|
+
) {
|
|
17
|
+
throw new Error(`Invalid green node dimensions at ${i}`);
|
|
18
|
+
}
|
|
19
|
+
let start = cursor;
|
|
20
|
+
if (interior) {
|
|
21
|
+
const first = i - o.nodespan;
|
|
22
|
+
if (first < 0) throw new Error(`Invalid green subtree at ${i}`);
|
|
23
|
+
while (stack.length && stack.at(-1) >= first) children.push(stack.pop());
|
|
24
|
+
children.reverse();
|
|
25
|
+
if (children.length) {
|
|
26
|
+
const firstChild = nodes[children[0]];
|
|
27
|
+
const subtreeStart = children[0] - (firstChild.interior ? firstChild.nodespan : 0);
|
|
28
|
+
if (subtreeStart !== first) throw new Error(`Misaligned green subtree at ${i}`);
|
|
29
|
+
start = firstChild.start;
|
|
30
|
+
} else cursor += o.span;
|
|
31
|
+
} else cursor += o.span;
|
|
32
|
+
if (cursor > byteLength || cursor - start !== o.span)
|
|
33
|
+
throw new Error(`Invalid green span at ${i}`);
|
|
34
|
+
nodes.push({ ...o, interior, start, end: cursor, children });
|
|
35
|
+
stack.push(i);
|
|
36
|
+
}
|
|
37
|
+
if (cursor !== byteLength)
|
|
38
|
+
throw new Error(`Tree covers ${cursor} bytes; input has ${byteLength}`);
|
|
39
|
+
const roots = stack.filter((i) => nodes[i].interior || nodes[i].start !== nodes[i].end);
|
|
40
|
+
return { nodes, roots };
|
|
41
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Ported from the investigation prototype. All public offsets use UTF-16.
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
export function positions(text, byteLength = encoder.encode(text).length) {
|
|
4
|
+
const byteToIndex = new Uint32Array(byteLength + 1);
|
|
5
|
+
let byte = 0,
|
|
6
|
+
index = 0;
|
|
7
|
+
for (const char of text) {
|
|
8
|
+
const cp = char.codePointAt(0);
|
|
9
|
+
const width = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
|
|
10
|
+
byteToIndex.fill(index, byte, byte + width);
|
|
11
|
+
byte += width;
|
|
12
|
+
index += char.length;
|
|
13
|
+
byteToIndex[byte] = index;
|
|
14
|
+
}
|
|
15
|
+
const starts = [0];
|
|
16
|
+
for (const match of text.matchAll(/\r\n|[\r\n]/gu)) starts.push(match.index + match[0].length);
|
|
17
|
+
function loc(index) {
|
|
18
|
+
let lo = 0,
|
|
19
|
+
hi = starts.length;
|
|
20
|
+
while (lo + 1 < hi) {
|
|
21
|
+
const mid = (lo + hi) >>> 1;
|
|
22
|
+
if (starts[mid] <= index) lo = mid;
|
|
23
|
+
else hi = mid;
|
|
24
|
+
}
|
|
25
|
+
return { line: lo + 1, column: index - starts[lo] };
|
|
26
|
+
}
|
|
27
|
+
const at = (b) => byteToIndex[Math.max(0, Math.min(byteLength, b))];
|
|
28
|
+
return { byteToIndex, at, loc };
|
|
29
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { readWasm, manifest } from './wasm-host.js';
|
|
2
|
+
import { positions } from './positions.js';
|
|
3
|
+
import { placeGreen } from './green-tree.js';
|
|
4
|
+
|
|
5
|
+
export function buildSyntax(text, parsed, { debug = false } = {}) {
|
|
6
|
+
const { nodes: raw, roots } = placeGreen(parsed.raw, parsed.bytes);
|
|
7
|
+
const offsets = positions(text, parsed.bytes),
|
|
8
|
+
parents = new WeakMap();
|
|
9
|
+
const tokens = [],
|
|
10
|
+
comments = [],
|
|
11
|
+
nodes = [],
|
|
12
|
+
keep = [],
|
|
13
|
+
visitorKeys = Object.create(null);
|
|
14
|
+
const location = (range) => ({ start: offsets.loc(range[0]), end: offsets.loc(range[1]) });
|
|
15
|
+
for (const o of raw) {
|
|
16
|
+
const range = [offsets.at(o.start), offsets.at(o.end)];
|
|
17
|
+
const n = {
|
|
18
|
+
type: o.kind,
|
|
19
|
+
kind: o.kind,
|
|
20
|
+
kindId: o.kindId,
|
|
21
|
+
flags: o.flags,
|
|
22
|
+
class: o.class,
|
|
23
|
+
interior: o.interior,
|
|
24
|
+
byteRange: [o.start, o.end],
|
|
25
|
+
range,
|
|
26
|
+
loc: location(range),
|
|
27
|
+
children: o.children.map((i) => nodes[i]).filter((_, j) => keep[o.children[j]]),
|
|
28
|
+
};
|
|
29
|
+
if (!o.interior)
|
|
30
|
+
Object.assign(n, {
|
|
31
|
+
value: text.slice(...range),
|
|
32
|
+
originalKindId: o.nodespan,
|
|
33
|
+
originalKind: o.originalKind,
|
|
34
|
+
});
|
|
35
|
+
nodes.push(n);
|
|
36
|
+
keep.push(
|
|
37
|
+
o.interior || (o.kind !== 'TOMBSTONE' && (Boolean(o.class & 4) || !(o.class & (2 | 128)))),
|
|
38
|
+
);
|
|
39
|
+
// Trivia tokens and comments own the same immediate interior parent as syntax.
|
|
40
|
+
for (const i of o.children) parents.set(nodes[i], n);
|
|
41
|
+
visitorKeys[n.kind] = ['children'];
|
|
42
|
+
if (!o.interior && o.kind === 'Comment') comments.push(n);
|
|
43
|
+
else if (!o.interior && o.kind !== 'TOMBSTONE' && !(o.class & 128) && range[1] > range[0])
|
|
44
|
+
tokens.push(n);
|
|
45
|
+
}
|
|
46
|
+
const ast = {
|
|
47
|
+
type: 'JuliaFile',
|
|
48
|
+
kind: 'JuliaFile',
|
|
49
|
+
children: roots.filter((i) => keep[i]).map((i) => nodes[i]),
|
|
50
|
+
range: [0, text.length],
|
|
51
|
+
byteRange: [0, parsed.bytes],
|
|
52
|
+
loc: location([0, text.length]),
|
|
53
|
+
};
|
|
54
|
+
for (const i of roots) parents.set(nodes[i], ast);
|
|
55
|
+
visitorKeys.JuliaFile = ['children'];
|
|
56
|
+
const diagnostics = parsed.diagnostics.map((d) => {
|
|
57
|
+
const start = offsets.at(d.first - 1),
|
|
58
|
+
end = Math.max(start, offsets.at(d.last));
|
|
59
|
+
const range = [start, end];
|
|
60
|
+
return {
|
|
61
|
+
message: d.message,
|
|
62
|
+
level: d.level,
|
|
63
|
+
byteRange: [d.first - 1, d.last],
|
|
64
|
+
range,
|
|
65
|
+
loc: location(range),
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
const result = {
|
|
69
|
+
ast,
|
|
70
|
+
tokens,
|
|
71
|
+
comments,
|
|
72
|
+
diagnostics,
|
|
73
|
+
visitorKeys,
|
|
74
|
+
parents,
|
|
75
|
+
provenance: manifest,
|
|
76
|
+
rawCount: raw.length,
|
|
77
|
+
bytes: parsed.bytes,
|
|
78
|
+
};
|
|
79
|
+
// Only debug parses retain a second view with unfiltered raw children.
|
|
80
|
+
if (debug)
|
|
81
|
+
result.greenNodes = raw.map((o, i) => ({
|
|
82
|
+
...nodes[i],
|
|
83
|
+
span: o.span,
|
|
84
|
+
nodespan: o.nodespan,
|
|
85
|
+
children: o.children,
|
|
86
|
+
}));
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
export function parseJulia(text, options) {
|
|
90
|
+
return buildSyntax(text, readWasm(text), options);
|
|
91
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
export const manifest = JSON.parse(
|
|
5
|
+
readFileSync(new URL('../../wasm/manifest.json', import.meta.url), 'utf8'),
|
|
6
|
+
);
|
|
7
|
+
const bytes = readFileSync(new URL('../../wasm/parser.wasm', import.meta.url));
|
|
8
|
+
if (createHash('sha256').update(bytes).digest('hex') !== manifest.sha256) {
|
|
9
|
+
throw new Error('Julia parser artifact hash differs from wasm/manifest.json');
|
|
10
|
+
}
|
|
11
|
+
const module = new WebAssembly.Module(bytes);
|
|
12
|
+
const encoder = new TextEncoder(),
|
|
13
|
+
decoder = new TextDecoder();
|
|
14
|
+
|
|
15
|
+
export class ParserTrapError extends Error {
|
|
16
|
+
constructor(cause) {
|
|
17
|
+
super(
|
|
18
|
+
`JuliaSyntax Wasm trap (Julia ${manifest.versions.julia}, sha256 ${manifest.sha256}): ${cause.message}`,
|
|
19
|
+
{ cause },
|
|
20
|
+
);
|
|
21
|
+
this.name = 'ParserTrapError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// One synchronous instance per isolate. The factory is injectable for trap tests.
|
|
26
|
+
export function createWasmHost(instantiate = () => new WebAssembly.Instance(module, {})) {
|
|
27
|
+
let instance,
|
|
28
|
+
busy = false;
|
|
29
|
+
const names = new Map();
|
|
30
|
+
return function readWasm(text) {
|
|
31
|
+
if (busy) throw new Error('Julia parser adapter is not reentrant');
|
|
32
|
+
busy = true;
|
|
33
|
+
try {
|
|
34
|
+
instance ??= instantiate();
|
|
35
|
+
const e = instance.exports;
|
|
36
|
+
const string = (len, byte) =>
|
|
37
|
+
decoder.decode(Uint8Array.from({ length: len }, (_, i) => byte(i + 1)));
|
|
38
|
+
const name = (kind) => {
|
|
39
|
+
if (!names.has(kind))
|
|
40
|
+
names.set(
|
|
41
|
+
kind,
|
|
42
|
+
string(e.kind_name_len(kind), (j) => e.kind_name_byte(kind, j)),
|
|
43
|
+
);
|
|
44
|
+
return names.get(kind);
|
|
45
|
+
};
|
|
46
|
+
const source = encoder.encode(text);
|
|
47
|
+
e.src_resize(source.length);
|
|
48
|
+
for (let i = 0; i < source.length; i += 4) {
|
|
49
|
+
e.src_set4(
|
|
50
|
+
i + 1,
|
|
51
|
+
source[i] | (source[i + 1] << 8) | (source[i + 2] << 16) | (source[i + 3] << 24),
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const count = e.parse_src(1);
|
|
55
|
+
if (!Number.isInteger(count) || count < 0)
|
|
56
|
+
throw new Error('Invalid Julia parser output count');
|
|
57
|
+
// Copy every result and diagnostic before another file can reuse the instance.
|
|
58
|
+
const raw = Array.from({ length: count }, (_, i) => {
|
|
59
|
+
const k = i + 1,
|
|
60
|
+
kindId = e.out_kind(k),
|
|
61
|
+
nodespan = e.out_nodespan(k),
|
|
62
|
+
cls = e.out_class(k);
|
|
63
|
+
return {
|
|
64
|
+
kindId,
|
|
65
|
+
kind: name(kindId),
|
|
66
|
+
span: e.out_span(k),
|
|
67
|
+
nodespan,
|
|
68
|
+
class: cls,
|
|
69
|
+
flags: e.out_flags(k),
|
|
70
|
+
...(!(cls & 1) && { originalKind: name(nodespan) }),
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
const diagnostics = Array.from({ length: e.ndiag() }, (_, i) => {
|
|
74
|
+
const k = i + 1;
|
|
75
|
+
return {
|
|
76
|
+
first: e.diag_first(k),
|
|
77
|
+
last: e.diag_last(k),
|
|
78
|
+
level: e.diag_level(k),
|
|
79
|
+
message: string(e.diag_msg_len(k), (j) => e.diag_msg_byte(k, j)),
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
return { raw, diagnostics, bytes: source.length };
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (!(error instanceof WebAssembly.RuntimeError)) throw error;
|
|
85
|
+
instance = undefined; // A trapped instance's mutable stream is never reused.
|
|
86
|
+
throw new ParserTrapError(error);
|
|
87
|
+
} finally {
|
|
88
|
+
busy = false;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export const readWasm = createWasmHost();
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import {
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
statSync,
|
|
9
|
+
unlinkSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from 'node:fs';
|
|
12
|
+
import { homedir, hostname } from 'node:os';
|
|
13
|
+
import { join, resolve } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { threadId } from 'node:worker_threads';
|
|
16
|
+
import { rewritePaths } from './toml.js';
|
|
17
|
+
|
|
18
|
+
const memo = new Map(),
|
|
19
|
+
failures = new Set();
|
|
20
|
+
const sleep = new Int32Array(new SharedArrayBuffer(4));
|
|
21
|
+
const child = fileURLToPath(new URL('./pkg-child.mjs', import.meta.url));
|
|
22
|
+
function cached(envDir, key) {
|
|
23
|
+
try {
|
|
24
|
+
const version = statSync(join(envDir, 'env.json')).mtimeMs;
|
|
25
|
+
const hit = memo.get(envDir);
|
|
26
|
+
const data =
|
|
27
|
+
hit?.version === version
|
|
28
|
+
? hit.data
|
|
29
|
+
: JSON.parse(readFileSync(join(envDir, 'env.json'), 'utf8'));
|
|
30
|
+
if (
|
|
31
|
+
data.key !== key ||
|
|
32
|
+
data.julia !== '1.13' ||
|
|
33
|
+
!data.packages ||
|
|
34
|
+
!data.stats ||
|
|
35
|
+
!Object.values(data.packages).every(
|
|
36
|
+
(p) => typeof p.uuid === 'string' && typeof p.entry === 'string' && existsSync(p.entry),
|
|
37
|
+
)
|
|
38
|
+
)
|
|
39
|
+
return null;
|
|
40
|
+
memo.set(envDir, { version, data });
|
|
41
|
+
return { ...data, envDir, cached: true, seconds: data.stats.seconds };
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function failed(envDir) {
|
|
47
|
+
if (failures.has(envDir)) return true;
|
|
48
|
+
try {
|
|
49
|
+
if (Date.now() - JSON.parse(readFileSync(join(envDir, 'failed.json'), 'utf8')).at < 3600000) {
|
|
50
|
+
failures.add(envDir);
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
} catch {
|
|
54
|
+
/* No recent failure. */
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
// A unique temporary name: worker threads share a pid.
|
|
59
|
+
export const temporaryName = (base) => `${base}.${process.pid}.${threadId}.${randomUUID()}.tmp`;
|
|
60
|
+
const wait = (ms) => Atomics.wait(sleep, 0, 0, Math.max(1, ms));
|
|
61
|
+
const alive = (pid) => {
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 0);
|
|
64
|
+
return true;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
return error.code === 'EPERM';
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
// Runs `fn` while holding `<path>.guard`, created exclusively; undefined if another process
|
|
70
|
+
// holds it. Locks are only created, taken over and released under the guard, so a stale
|
|
71
|
+
// lock is never removed after its replacement was created. A guard is held for a few file
|
|
72
|
+
// operations; one older than 30 s was left by a killed process.
|
|
73
|
+
function guarded(path, fn) {
|
|
74
|
+
const guard = `${path}.guard`;
|
|
75
|
+
try {
|
|
76
|
+
writeFileSync(guard, `${process.pid}`, { flag: 'wx' });
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.code !== 'EEXIST') throw error;
|
|
79
|
+
try {
|
|
80
|
+
if (Date.now() - statSync(guard).mtimeMs > 30000) unlinkSync(guard);
|
|
81
|
+
} catch {
|
|
82
|
+
/* Released meanwhile. */
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return fn();
|
|
88
|
+
} finally {
|
|
89
|
+
try {
|
|
90
|
+
unlinkSync(guard);
|
|
91
|
+
} catch {
|
|
92
|
+
/* Already removed as stale. */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// A lock records its holder's token, deadline, host and pid: it is stale once the deadline
|
|
97
|
+
// has passed, or at once when its holder on this host has exited.
|
|
98
|
+
function stale(held, path, timeout) {
|
|
99
|
+
const [, until, host, pid] = held.split(' ');
|
|
100
|
+
if (host === hostname() && Number(pid) && !alive(Number(pid))) return true;
|
|
101
|
+
const deadline = Number(until) || statSync(path).mtimeMs + timeout;
|
|
102
|
+
return Date.now() > deadline + 5000;
|
|
103
|
+
}
|
|
104
|
+
function exclude(result, name) {
|
|
105
|
+
if (!result || !name) return result;
|
|
106
|
+
const packages = { ...result.packages };
|
|
107
|
+
delete packages[name];
|
|
108
|
+
return { ...result, packages };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function resolveEnvironment(request, settings = {}) {
|
|
112
|
+
let envDir;
|
|
113
|
+
const locks = [];
|
|
114
|
+
try {
|
|
115
|
+
const options = settings.julia ?? {};
|
|
116
|
+
const resolver = options.resolver ?? (options.pkgResolver ? 'pkg' : 'none');
|
|
117
|
+
if (typeof resolver === 'function') {
|
|
118
|
+
const result = resolver(request);
|
|
119
|
+
if (!result?.packages || result.then) return null;
|
|
120
|
+
const packages = Object.fromEntries(
|
|
121
|
+
Object.entries(result.packages).map(([name, value]) => [
|
|
122
|
+
name,
|
|
123
|
+
typeof value === 'string' ? { entry: value } : value,
|
|
124
|
+
]),
|
|
125
|
+
);
|
|
126
|
+
return exclude({ ...result, packages }, request.packageName);
|
|
127
|
+
}
|
|
128
|
+
if (resolver !== 'pkg') return null;
|
|
129
|
+
const project = rewritePaths(readFileSync(request.projectFile, 'utf8'), request.projectFile);
|
|
130
|
+
// The key hashes what the child receives: relative `path` entries are made absolute, so
|
|
131
|
+
// two checkouts with the same Manifest don't share an environment.
|
|
132
|
+
const manifest = request.manifestFile
|
|
133
|
+
? rewritePaths(readFileSync(request.manifestFile, 'utf8'), request.manifestFile, true)
|
|
134
|
+
: '';
|
|
135
|
+
const key = createHash('sha256')
|
|
136
|
+
.update('1.13' + project + manifest)
|
|
137
|
+
.digest('hex');
|
|
138
|
+
const home = (path) => path.replace(/^~(?=$|[\\/])/u, homedir());
|
|
139
|
+
const cache = resolve(
|
|
140
|
+
options.cacheDir
|
|
141
|
+
? home(options.cacheDir)
|
|
142
|
+
: join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'eslint-plugin-julia'),
|
|
143
|
+
);
|
|
144
|
+
envDir = join(cache, 'envs', key.slice(0, 16));
|
|
145
|
+
const warm = cached(envDir, key);
|
|
146
|
+
if (warm) return exclude(warm, request.packageName);
|
|
147
|
+
if (options.offline || failed(envDir)) return null;
|
|
148
|
+
const timeout = Number(options.resolverTimeout ?? 600) * 1000;
|
|
149
|
+
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error('Invalid resolverTimeout');
|
|
150
|
+
const deadline = Date.now() + timeout;
|
|
151
|
+
mkdirSync(envDir, { recursive: true });
|
|
152
|
+
// The depot lock also protects pruning from concurrent installs of other environments.
|
|
153
|
+
for (const path of [join(envDir, 'lock'), join(cache, 'depot.lock')]) {
|
|
154
|
+
const token = randomUUID();
|
|
155
|
+
for (;;) {
|
|
156
|
+
const ready = cached(envDir, key);
|
|
157
|
+
if (ready) return exclude(ready, request.packageName);
|
|
158
|
+
if (failed(envDir)) return null;
|
|
159
|
+
if (Date.now() >= deadline)
|
|
160
|
+
throw Object.assign(new Error('Resolver lock timeout'), { transient: true });
|
|
161
|
+
const taken = guarded(path, () => {
|
|
162
|
+
let held = null;
|
|
163
|
+
try {
|
|
164
|
+
held = readFileSync(path, 'utf8');
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code !== 'ENOENT') throw error;
|
|
167
|
+
}
|
|
168
|
+
if (held !== null && !stale(held, path, timeout)) return false;
|
|
169
|
+
writeFileSync(path, `${token} ${deadline} ${hostname()} ${process.pid}`);
|
|
170
|
+
return true;
|
|
171
|
+
});
|
|
172
|
+
if (taken) {
|
|
173
|
+
locks.push({ path, token });
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
wait(Math.min(50, deadline - Date.now()));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// The request goes through stdin: a Manifest can exceed the command-line limit.
|
|
180
|
+
const run = spawnSync(options.node ?? process.execPath, [child], {
|
|
181
|
+
input: JSON.stringify({
|
|
182
|
+
key,
|
|
183
|
+
cache,
|
|
184
|
+
envDir,
|
|
185
|
+
project,
|
|
186
|
+
manifest,
|
|
187
|
+
pkgResolver: options.pkgResolver && home(options.pkgResolver),
|
|
188
|
+
pkgWasm: options.pkgWasm && home(options.pkgWasm),
|
|
189
|
+
}),
|
|
190
|
+
stdio: ['pipe', 'ignore', 'pipe'],
|
|
191
|
+
timeout: Math.max(1, deadline - Date.now()),
|
|
192
|
+
encoding: 'utf8',
|
|
193
|
+
maxBuffer: 1024 * 1024,
|
|
194
|
+
});
|
|
195
|
+
if (run.error || run.status !== 0)
|
|
196
|
+
throw run.error ?? new Error(run.stderr?.trim() || `Resolver exited ${run.status}`);
|
|
197
|
+
const result = cached(envDir, key);
|
|
198
|
+
if (!result) throw new Error('Resolver did not produce a complete environment');
|
|
199
|
+
return exclude({ ...result, cached: false }, request.packageName);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
// Waiting out another worker's lock isn't a failure of this environment.
|
|
202
|
+
if (envDir && !error.transient) {
|
|
203
|
+
failures.add(envDir);
|
|
204
|
+
try {
|
|
205
|
+
mkdirSync(envDir, { recursive: true });
|
|
206
|
+
const file = temporaryName(join(envDir, 'failed.json'));
|
|
207
|
+
writeFileSync(
|
|
208
|
+
file,
|
|
209
|
+
JSON.stringify({ error: String(error.message ?? error), at: Date.now() }),
|
|
210
|
+
);
|
|
211
|
+
renameSync(file, join(envDir, 'failed.json'));
|
|
212
|
+
} catch {
|
|
213
|
+
/* An unwritable cache must not interrupt linting. */
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return null;
|
|
217
|
+
} finally {
|
|
218
|
+
for (const { path, token } of locks.reverse())
|
|
219
|
+
for (let attempt = 0; attempt < 200; attempt++) {
|
|
220
|
+
const done = guarded(path, () => {
|
|
221
|
+
try {
|
|
222
|
+
if (readFileSync(path, 'utf8').split(' ')[0] === token) unlinkSync(path);
|
|
223
|
+
} catch {
|
|
224
|
+
/* Already released or taken over. */
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
});
|
|
228
|
+
if (done) break;
|
|
229
|
+
wait(10);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import {
|
|
2
|
+
existsSync,
|
|
3
|
+
lstatSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readFileSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
} from 'node:fs';
|
|
11
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
12
|
+
import { pathToFileURL } from 'node:url';
|
|
13
|
+
import { manifestNames } from './toml.js';
|
|
14
|
+
|
|
15
|
+
async function main(args) {
|
|
16
|
+
const start = performance.now();
|
|
17
|
+
const { cache, envDir, key } = args;
|
|
18
|
+
const depot = join(cache, 'depot'),
|
|
19
|
+
project = join(envDir, 'project');
|
|
20
|
+
// Pruning deletes everything but sources: only a depot this plugin created is pruned, never
|
|
21
|
+
// a real depot that a misconfigured cacheDir happens to point at.
|
|
22
|
+
const marker = join(depot, '.eslint-plugin-julia');
|
|
23
|
+
if (!existsSync(marker)) {
|
|
24
|
+
if (existsSync(depot) && readdirSync(depot).length)
|
|
25
|
+
throw new Error(`${depot} is not a depot created by eslint-plugin-julia; refusing to use it`);
|
|
26
|
+
mkdirSync(depot, { recursive: true });
|
|
27
|
+
writeFileSync(marker, 'A cache depot of eslint-plugin-julia: non-source files are deleted.\n');
|
|
28
|
+
}
|
|
29
|
+
for (const dir of [project, join(cache, 'home'), join(cache, 'tmp')])
|
|
30
|
+
mkdirSync(dir, { recursive: true });
|
|
31
|
+
writeFileSync(join(project, 'Project.toml'), args.project);
|
|
32
|
+
const manifest = join(project, 'Manifest.toml');
|
|
33
|
+
rmSync(manifest, { force: true });
|
|
34
|
+
if (args.manifest) writeFileSync(manifest, args.manifest);
|
|
35
|
+
if (!args.pkgResolver)
|
|
36
|
+
throw new Error('Configure a Pkg-in-Wasm resolver via settings.julia.pkgResolver');
|
|
37
|
+
const backend = await import(pathToFileURL(resolve(args.pkgResolver, 'dist/index.js')).href);
|
|
38
|
+
const { juliaPkg } = await import(
|
|
39
|
+
pathToFileURL(resolve(args.pkgResolver, 'dist/withjuliapkg.js')).href
|
|
40
|
+
);
|
|
41
|
+
if (args.pkgWasm) backend.configurePkgWasm({ dir: args.pkgWasm });
|
|
42
|
+
if (!backend.pkgWasmAvailable())
|
|
43
|
+
throw new Error('Pkg-in-Wasm resolver unavailable (requires JSPI and a supported platform)');
|
|
44
|
+
const target = {
|
|
45
|
+
cwd: project,
|
|
46
|
+
env: {
|
|
47
|
+
HOME: join(cache, 'home'),
|
|
48
|
+
JULIA_DEPOT_PATH: depot,
|
|
49
|
+
TMPDIR: join(cache, 'tmp'),
|
|
50
|
+
JULIA_PKG_PRECOMPILE_AUTO: '0',
|
|
51
|
+
WASMHOST_PLATFORM: 'arch=wasm32;os=wasi',
|
|
52
|
+
...(process.env.JULIA_PKG_SERVER !== undefined
|
|
53
|
+
? { JULIA_PKG_SERVER: process.env.JULIA_PKG_SERVER }
|
|
54
|
+
: {}),
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
const instantiate = async () => {
|
|
58
|
+
const result = await juliaPkg(
|
|
59
|
+
target,
|
|
60
|
+
{ kind: 'instantiate' },
|
|
61
|
+
{
|
|
62
|
+
project,
|
|
63
|
+
reportFile: join(envDir, 'report.toml'),
|
|
64
|
+
requestId: 'eslint',
|
|
65
|
+
onOutput: () => {},
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
if (result.status !== 'ok' || result.report?.status !== true)
|
|
69
|
+
throw new Error(result.report?.error || result.process?.stderr || 'Pkg instantiate failed');
|
|
70
|
+
};
|
|
71
|
+
const packages = Object.create(null),
|
|
72
|
+
roots = new Set();
|
|
73
|
+
const packageRoot = join(depot, 'packages');
|
|
74
|
+
mkdirSync(packageRoot, { recursive: true });
|
|
75
|
+
const stats = {
|
|
76
|
+
seconds: 0,
|
|
77
|
+
packages: 0,
|
|
78
|
+
sourceBytes: 0,
|
|
79
|
+
removedBytes: 0,
|
|
80
|
+
artifactsRemoved: 0,
|
|
81
|
+
};
|
|
82
|
+
function prune(path, root, discard = false) {
|
|
83
|
+
const info = lstatSync(path);
|
|
84
|
+
if (info.isDirectory()) {
|
|
85
|
+
for (const file of readdirSync(path)) prune(join(path, file), root, discard);
|
|
86
|
+
if (!readdirSync(path).length) rmSync(path, { recursive: true });
|
|
87
|
+
} else {
|
|
88
|
+
const local = relative(root, path);
|
|
89
|
+
const keep =
|
|
90
|
+
!discard &&
|
|
91
|
+
!info.isSymbolicLink() &&
|
|
92
|
+
(['Project.toml', 'JuliaProject.toml'].includes(local) ||
|
|
93
|
+
(local.startsWith(`src${sep}`) && local.endsWith('.jl')));
|
|
94
|
+
if (keep) stats.sourceBytes += info.size;
|
|
95
|
+
else {
|
|
96
|
+
stats.removedBytes += info.size;
|
|
97
|
+
rmSync(path, { force: true });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Every package version in the shared depot, not only this environment's: a failed or
|
|
102
|
+
// interrupted instantiate leaves downloads behind that must not survive as non-source.
|
|
103
|
+
const pruneDepot = () => {
|
|
104
|
+
for (const name of readdirSync(packageRoot, { withFileTypes: true }))
|
|
105
|
+
if (name.isDirectory())
|
|
106
|
+
for (const slug of readdirSync(join(packageRoot, name.name), { withFileTypes: true }))
|
|
107
|
+
if (slug.isDirectory()) roots.add(join(packageRoot, name.name, slug.name));
|
|
108
|
+
for (const root of roots) prune(root, root);
|
|
109
|
+
// Pkg also writes cache marker files outside individual package directories.
|
|
110
|
+
for (const item of readdirSync(packageRoot, { withFileTypes: true }))
|
|
111
|
+
if (!item.isDirectory()) prune(join(packageRoot, item.name), packageRoot, true);
|
|
112
|
+
for (const name of ['artifacts', 'clones', 'compiled', 'logs', 'scratchspaces']) {
|
|
113
|
+
const path = join(depot, name);
|
|
114
|
+
try {
|
|
115
|
+
if (name === 'artifacts') stats.artifactsRemoved = readdirSync(path).length;
|
|
116
|
+
prune(path, path, true);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error.code !== 'ENOENT') throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
// Set when the Manifest couldn't be instantiated and versions were resolved afresh.
|
|
123
|
+
let manifestIgnored = false;
|
|
124
|
+
try {
|
|
125
|
+
try {
|
|
126
|
+
await instantiate();
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (!args.manifest) throw error;
|
|
129
|
+
rmSync(manifest, { force: true });
|
|
130
|
+
manifestIgnored = true;
|
|
131
|
+
await instantiate();
|
|
132
|
+
}
|
|
133
|
+
} catch (error) {
|
|
134
|
+
pruneDepot();
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
const names = manifestNames(readFileSync(manifest, 'utf8'));
|
|
138
|
+
for (const [uuid, entry] of Object.entries(backend.locate(target, project))) {
|
|
139
|
+
if (!entry) continue; // Standard libraries have no source entry in the depot.
|
|
140
|
+
const name = names.get(uuid);
|
|
141
|
+
if (!name) throw new Error(`No Manifest name for ${uuid}`);
|
|
142
|
+
packages[name] = { uuid, entry };
|
|
143
|
+
const path = relative(packageRoot, entry);
|
|
144
|
+
const parts = path.split(sep);
|
|
145
|
+
if (!isAbsolute(path) && parts[0] !== '..' && parts.length >= 3)
|
|
146
|
+
roots.add(join(packageRoot, parts[0], parts[1]));
|
|
147
|
+
}
|
|
148
|
+
stats.packages = Object.keys(packages).length;
|
|
149
|
+
pruneDepot();
|
|
150
|
+
for (const { entry } of Object.values(packages))
|
|
151
|
+
if (!lstatSync(entry).isFile()) throw new Error(`Missing source entry: ${entry}`);
|
|
152
|
+
stats.seconds = (performance.now() - start) / 1000;
|
|
153
|
+
const temporary = join(envDir, 'env.json.tmp');
|
|
154
|
+
writeFileSync(
|
|
155
|
+
temporary,
|
|
156
|
+
JSON.stringify({ key, julia: '1.13', packages, stats, manifestIgnored }),
|
|
157
|
+
);
|
|
158
|
+
renameSync(temporary, join(envDir, 'env.json'));
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
await main(JSON.parse(readFileSync(0, 'utf8')));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
process.stderr.write(`${error.message}\n`);
|
|
164
|
+
process.exitCode = 1;
|
|
165
|
+
}
|