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
@@ -0,0 +1,63 @@
1
+ import { dirname, isAbsolute, resolve } from 'node:path';
2
+
3
+ // Preserve TOML verbatim except path values. Tokenizing keeps comments and strings opaque.
4
+ const tokens =
5
+ /^[\t ]*\[\[?[^\r\n]*?\]\]?|#[^\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\])*"|'[^']*'|[\w-]+|[\t ]+|\r?\n|./gmu;
6
+ function string(token) {
7
+ if (token.startsWith("'")) return token.slice(1, -1);
8
+ return JSON.parse(
9
+ token.replace(/\\U([\da-f]{8})/giu, (_, n) =>
10
+ JSON.stringify(String.fromCodePoint(parseInt(n, 16))).slice(1, -1),
11
+ ),
12
+ );
13
+ }
14
+ function header(token) {
15
+ return token
16
+ .trim()
17
+ .replace(/^\[\[?|\]\]?$/gu, '')
18
+ .trim();
19
+ }
20
+ export function rewritePaths(text, file, manifest = false) {
21
+ let sources = false;
22
+ const parts = text.match(tokens) ?? [];
23
+ for (let i = 0; i < parts.length; i++) {
24
+ if (/^\s*\[.+\]$/u.test(parts[i]))
25
+ sources = /^(?:sources|"sources"|'sources')(?:\s*\.|$)/u.test(header(parts[i]));
26
+ if (!manifest && !sources) continue;
27
+ if (!['path', '"path"', "'path'"].includes(parts[i])) continue;
28
+ let j = i + 1;
29
+ while (/^\s+$/u.test(parts[j] ?? '')) j++;
30
+ if (parts[j++] !== '=') continue;
31
+ while (/^\s+$/u.test(parts[j] ?? '')) j++;
32
+ if (!/^["']/u.test(parts[j] ?? '')) continue;
33
+ const value = string(parts[j]);
34
+ if (!isAbsolute(value)) parts[j] = JSON.stringify(resolve(dirname(file), value));
35
+ i = j;
36
+ }
37
+ return parts.join('');
38
+ }
39
+ export function manifestNames(text) {
40
+ const names = new Map();
41
+ let name;
42
+ const parts = text.match(tokens) ?? [];
43
+ for (let i = 0; i < parts.length; i++) {
44
+ if (/^\s*\[.+\]$/u.test(parts[i])) {
45
+ const table = header(parts[i]).replace(/^deps\./u, '');
46
+ name = parts[i].trimStart().startsWith('[[')
47
+ ? /^["']/u.test(table)
48
+ ? string(table)
49
+ : table
50
+ : undefined;
51
+ }
52
+ if (!name || !['uuid', '"uuid"', "'uuid'"].includes(parts[i])) continue;
53
+ let j = i + 1;
54
+ while (/^\s+$/u.test(parts[j] ?? '')) j++;
55
+ if (parts[j++] !== '=') continue;
56
+ while (/^\s+$/u.test(parts[j] ?? '')) j++;
57
+ if (/^["']/u.test(parts[j] ?? '')) names.set(string(parts[j]), name);
58
+ }
59
+ return names;
60
+ }
61
+
62
+ // The Manifests of an environment, in the order Julia 1.13 picks them.
63
+ export const MANIFESTS = ['Manifest-v1.13.toml', 'Manifest.toml'];
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Warms the resolver cache for an environment, as lint would resolve it (for CI):
3
+ // npx eslint-plugin-julia-resolve-env Project.toml --pkg-resolver DIR [--pkg-wasm DIR] [--cache DIR]
4
+ import { existsSync } from 'node:fs';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { resolveEnvironment } from './index.js';
7
+ import { MANIFESTS } from './toml.js';
8
+
9
+ const [file, ...flags] = process.argv.slice(2);
10
+ const options = { '--pkg-resolver': 'pkgResolver', '--pkg-wasm': 'pkgWasm', '--cache': 'cacheDir' };
11
+ const julia = {};
12
+ if (!file || flags.length % 2 || flags.some((flag, i) => i % 2 === 0 && !options[flag])) {
13
+ console.error(
14
+ 'Usage: eslint-plugin-julia-resolve-env <Project.toml> [--pkg-resolver P] [--pkg-wasm DIR] [--cache DIR]',
15
+ );
16
+ process.exitCode = 1;
17
+ } else {
18
+ for (let i = 0; i < flags.length; i += 2) julia[options[flags[i]]] = resolve(flags[i + 1]);
19
+ const projectFile = resolve(file);
20
+ // The same Manifest lint picks, so the warmed key is the one lint looks up.
21
+ const manifestFile =
22
+ MANIFESTS.map((m) => join(dirname(projectFile), m)).find((m) => existsSync(m)) ?? null;
23
+ const result = resolveEnvironment({ projectFile, manifestFile }, { julia });
24
+ console.log(JSON.stringify(result, null, 2));
25
+ if (!result) process.exitCode = 1;
26
+ }
@@ -0,0 +1,52 @@
1
+ import { isInsideMacro, isQuoted } from '../parser/flags.js';
2
+
3
+ // Every shipped rule passes through this guard. A future rule cannot accidentally
4
+ // expose edits on a recovered file by forgetting a per-rule diagnostic check.
5
+ export function defineRule(rule) {
6
+ return {
7
+ ...rule,
8
+ create(context) {
9
+ if (!context.sourceCode.diagnostics.some((d) => d.level === 1)) return rule.create(context);
10
+ const guarded = Object.create(context, {
11
+ report: {
12
+ value(descriptor) {
13
+ const { fix, suggest, ...diagnostic } = descriptor;
14
+ context.report(diagnostic);
15
+ },
16
+ },
17
+ });
18
+ return rule.create(guarded);
19
+ },
20
+ };
21
+ }
22
+ export const isBareName = (n) =>
23
+ n?.kind === 'Identifier' && !n.interior && n.originalKind === 'Identifier';
24
+ export const isOpaque = (n, source) => isInsideMacro(n, source) || isQuoted(n, source);
25
+ export function isSignature(node, source) {
26
+ for (
27
+ let child = node, parent = source.getParent(child);
28
+ parent;
29
+ child = parent, parent = source.getParent(parent)
30
+ ) {
31
+ if (['function', 'macro', '->'].includes(parent.kind) && parent.children[0] === child)
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+
37
+ // Coordinate-free syntax identity. Visitable children already omit trivia.
38
+ // Strip redundant grouping only; retain kinds, exact leaf text, and parser
39
+ // semantic flags, following the pinned normal-form oracle's flag mask.
40
+ export function normalizedTreeKey(node) {
41
+ const parts = [],
42
+ stack = [node];
43
+ while (stack.length) {
44
+ let n = stack.pop();
45
+ while (n.kind === 'parens' && n.interior && n.children.length === 1) n = n.children[0];
46
+ let flags = (n.flags ?? 0) & ~(1 | 128);
47
+ if (n.kind === 'toplevel') flags &= ~256;
48
+ parts.push([n.kind, Boolean(n.interior), flags, n.value ?? null, n.children.length]);
49
+ stack.push(...n.children.toReversed());
50
+ }
51
+ return JSON.stringify(parts);
52
+ }
@@ -0,0 +1,90 @@
1
+ import { defineRule } from './common.js';
2
+ import { strip, span } from './idiom-common.js';
3
+ import { isInfixCall } from '../parser/flags.js';
4
+ import { getScopeManager, identifierName } from '../scope.js';
5
+ export { identifierName };
6
+ export { strip, nodes, ordinary, text, span, binary, baseAvailable } from './idiom-common.js';
7
+
8
+ // These checks need the physical file and entry-file settings for module facts.
9
+ export function checkRule(description, create, suggestions = false) {
10
+ return defineRule({
11
+ meta: {
12
+ type: 'problem',
13
+ docs: { description },
14
+ schema: [],
15
+ hasSuggestions: suggestions,
16
+ messages: { issue: '{{message}}', replace: '{{message}}' },
17
+ },
18
+ create(context) {
19
+ let manager;
20
+ const lazy = new Proxy(
21
+ {},
22
+ {
23
+ get(_, key) {
24
+ manager ??= getScopeManager(context.sourceCode, context);
25
+ const value = manager[key];
26
+ return typeof value === 'function' ? value.bind(manager) : value;
27
+ },
28
+ },
29
+ );
30
+ return create(context, lazy, context.sourceCode);
31
+ },
32
+ });
33
+ }
34
+ export function report(context, node, message, replacement) {
35
+ const source = context.sourceCode;
36
+ const comments = source.comments.some(
37
+ (c) => c.range[0] >= node.range[0] && c.range[1] <= node.range[1],
38
+ );
39
+ context.report({
40
+ node,
41
+ messageId: 'issue',
42
+ data: { message },
43
+ ...(replacement &&
44
+ !comments && {
45
+ suggest: [
46
+ {
47
+ messageId: 'replace',
48
+ data: { message: `Use ${replacement}.` },
49
+ fix: (fixer) => fixer.replaceTextRange(span(source, node), replacement),
50
+ },
51
+ ],
52
+ }),
53
+ });
54
+ }
55
+ export function smallInteger(node) {
56
+ while (node?.kind === 'parens' && node.children.length === 1) node = node.children[0];
57
+ if (node?.kind !== 'Integer' || !/^-?[0-9][0-9_]*$/u.test(node.value)) return null;
58
+ const n = Number(node.value.replaceAll('_', ''));
59
+ return Number.isInteger(n) && Math.abs(n) <= 2147483647 ? n : null;
60
+ }
61
+ export function statements(node) {
62
+ return ['block', 'toplevel'].includes(node.kind) ? node.children.flatMap(statements) : [node];
63
+ }
64
+ export function localSymbol(node, at, m) {
65
+ if (
66
+ node?.kind !== 'quote' ||
67
+ node.children.length !== 1 ||
68
+ node.children[0].kind !== 'Identifier'
69
+ )
70
+ return null;
71
+ const name = identifierName(node.children[0]),
72
+ scope = m.scopeFor(at);
73
+ const binding = scope && m.lookup(name, scope);
74
+ return binding &&
75
+ !['builtin', 'type-parameter'].includes(binding.kind) &&
76
+ binding.scope.kind !== 'module'
77
+ ? binding
78
+ : null;
79
+ }
80
+
81
+ // Match the spelling before requesting potentially expensive module facts.
82
+ export function call(node, name, m) {
83
+ node = strip(node);
84
+ if (node?.kind !== 'call' || isInfixCall(node)) return null;
85
+ let head = strip(node.children[0]);
86
+ if (head?.kind === 'curly') head = strip(head.children[0]);
87
+ const spelling = identifierName(head?.kind === '.' ? head.children[1] : head);
88
+ if (spelling !== name) return null;
89
+ return m.isUnshadowedBuiltin(head, name) ? node.children.slice(1) : null;
90
+ }
@@ -0,0 +1,93 @@
1
+ import { ordinary, strip, binary, call, nodes } from './idiom-common.js';
2
+ import { localBinding, within, emptyArray, positional } from './performance-common.js';
3
+
4
+ // Deliberately accept only an adjacent initializer and straight-line loop body.
5
+ // This is lexical recurrence recognition, not type or escape analysis.
6
+ export function growth(node, kind, m, source) {
7
+ if (!ordinary(node, source)) return [];
8
+ const block = source.getParent(node),
9
+ index = block?.children.indexOf(node),
10
+ init = block?.children[index - 1];
11
+ if (block?.kind !== 'block' || init?.kind !== '=') return [];
12
+ const binding = localBinding(init.children[0], m),
13
+ initial = strip(init.children[1]),
14
+ body = node.children.at(-1);
15
+ if (!binding || body.kind !== 'block') return [];
16
+ if (
17
+ kind === 'string'
18
+ ? initial.kind !== 'string' || initial.children.some((n) => n.kind !== 'String')
19
+ : !emptyArray(initial, m)
20
+ )
21
+ return [];
22
+ const forbidden = [
23
+ 'macrocall',
24
+ 'quote',
25
+ 'inert',
26
+ 'function',
27
+ '->',
28
+ 'do',
29
+ 'generator',
30
+ 'for',
31
+ 'while',
32
+ 'if',
33
+ 'elseif',
34
+ '?',
35
+ '&&',
36
+ '||',
37
+ 'try',
38
+ 'return',
39
+ 'break',
40
+ 'continue',
41
+ 'let',
42
+ 'local',
43
+ 'global',
44
+ ];
45
+ if ([...nodes(body)].some((n) => forbidden.includes(n.kind))) return [];
46
+ const recurrences = [];
47
+ for (const statement of body.children) {
48
+ if (m.resolve(statement.children[0]) !== binding) continue;
49
+ if (
50
+ kind === 'string' &&
51
+ statement.kind === 'op=' &&
52
+ m.isUnshadowedBuiltin(statement.children[1], '*')
53
+ ) {
54
+ recurrences.push({ statement, read: statement.children[0] });
55
+ continue;
56
+ }
57
+ if (statement.kind !== '=') continue;
58
+ const rhs = strip(statement.children[1]);
59
+ if (kind === 'string') {
60
+ const parts = binary(rhs);
61
+ if (parts && m.isUnshadowedBuiltin(parts[1], '*') && m.resolve(strip(parts[0])) === binding)
62
+ recurrences.push({ statement, read: strip(parts[0]) });
63
+ } else {
64
+ const args = call(rhs, 'vcat', m) ?? call(rhs, 'hcat', m);
65
+ if (positional(args) && args.length === 2 && m.resolve(strip(args[0])) === binding)
66
+ recurrences.push({ statement, read: strip(args[0]) });
67
+ }
68
+ }
69
+ if (
70
+ !recurrences.length ||
71
+ binding.definitions.length !== recurrences.length + 1 ||
72
+ binding.definitions.some(
73
+ (d) => d.assignment !== init && !recurrences.some((r) => r.statement === d.assignment),
74
+ )
75
+ )
76
+ return [];
77
+ const refs = binding.references.filter((r) => within(r.node, node));
78
+ if (
79
+ refs.length !== recurrences.length ||
80
+ refs.some((r) => !recurrences.some((candidate) => candidate.read === r.node))
81
+ )
82
+ return [];
83
+ // Captured prefixes may be observed indirectly through a callback.
84
+ if (
85
+ binding.references.some((r) => {
86
+ for (let at = r.scope; at && at !== binding.scope; at = at.parent)
87
+ if (at.kind === 'function') return true;
88
+ return false;
89
+ })
90
+ )
91
+ return [];
92
+ return recurrences.map((r) => r.statement);
93
+ }
@@ -0,0 +1,116 @@
1
+ import { defineRule, isOpaque, isSignature } from './common.js';
2
+ import { getScopeManager, identifierName } from '../scope.js';
3
+ import { isInfixCall } from '../parser/flags.js';
4
+ export { identifierName };
5
+ export const strip = (n) =>
6
+ n?.kind === 'parens' && n.children.length === 1 ? strip(n.children[0]) : n;
7
+ export function span(source, node) {
8
+ const first = source.getTokenAfter({ range: [node.range[0], node.range[0]] });
9
+ const last = source.getTokenBefore({ range: [node.range[1], node.range[1]] });
10
+ return first && last ? [first.range[0], last.range[1]] : node.range;
11
+ }
12
+ export const text = (source, node) => source.text.slice(...span(source, node));
13
+ export const ordinary = (n, source) => !isOpaque(n, source) && !isSignature(n, source);
14
+ export function call(node, name, m) {
15
+ node = strip(node);
16
+ if (node?.kind !== 'call' || isInfixCall(node)) return null;
17
+ let head = strip(node.children[0]);
18
+ if (head?.kind === 'curly') head = head.children[0];
19
+ return m.isUnshadowedBuiltin(head, name) ? node.children.slice(1) : null;
20
+ }
21
+ export function binary(node) {
22
+ node = strip(node);
23
+ if (node?.kind === '<:' && node.children.length === 2)
24
+ return [node.children[0], { value: '<:' }, node.children[1]];
25
+ return isInfixCall(node) && node.children.length === 3 ? node.children : null;
26
+ }
27
+ export function* nodes(root) {
28
+ const pending = [root];
29
+ while (pending.length) {
30
+ const n = pending.pop();
31
+ yield n;
32
+ pending.push(...n.children.toReversed());
33
+ }
34
+ }
35
+ export function baseAvailable(m, node) {
36
+ const b = m.lookup('Base', m.scopeFor(node));
37
+ return (
38
+ b?.kind === 'builtin' ||
39
+ b?.definitions.some(
40
+ (d) =>
41
+ d.kind === 'import' && d.moduleName === 'Base' && !b.writes.length && d.name === 'Base',
42
+ )
43
+ );
44
+ }
45
+ export function suggest(context, node, message, replacement) {
46
+ const range = span(context.sourceCode, node);
47
+ const comments = context.sourceCode.comments.some(
48
+ (c) => c.range[0] >= range[0] && c.range[1] <= range[1],
49
+ );
50
+ context.report({
51
+ node,
52
+ loc: {
53
+ start: context.sourceCode.getLocFromIndex(range[0]),
54
+ end: context.sourceCode.getLocFromIndex(range[1]),
55
+ },
56
+ messageId: 'diagnostic',
57
+ data: { message },
58
+ ...(replacement &&
59
+ !comments && {
60
+ suggest: [
61
+ {
62
+ messageId: 'replace',
63
+ data: { message: `Use ${replacement}.` },
64
+ fix: (fixer) => fixer.replaceTextRange(range, replacement),
65
+ },
66
+ ],
67
+ }),
68
+ });
69
+ }
70
+ export function rule(description, properties, create, hasSuggestions = true) {
71
+ return defineRule({
72
+ meta: {
73
+ type: 'suggestion',
74
+ hasSuggestions,
75
+ docs: { description },
76
+ schema: [{ type: 'object', properties, additionalProperties: false }],
77
+ messages: { diagnostic: '{{message}}', replace: '{{message}}' },
78
+ },
79
+ create(context) {
80
+ return create(
81
+ context,
82
+ getScopeManager(context.sourceCode, context),
83
+ context.sourceCode,
84
+ context.options[0] ?? {},
85
+ );
86
+ },
87
+ });
88
+ }
89
+ export function integer(node) {
90
+ node = strip(node);
91
+ if (node?.kind !== 'Integer') return null;
92
+ try {
93
+ return BigInt(node.value.replaceAll('_', ''));
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ export function sameName(a, b, m) {
99
+ a = strip(a);
100
+ b = strip(b);
101
+ if (identifierName(a) === null || identifierName(b) === null) return false;
102
+ const x = m.resolve(a),
103
+ y = m.resolve(b);
104
+ return x && y ? x === y : identifierName(a) === identifierName(b);
105
+ }
106
+ export function booleanUse(node, source) {
107
+ let parent = source.getParent(node);
108
+ while (parent?.kind === 'parens') {
109
+ node = parent;
110
+ parent = source.getParent(node);
111
+ }
112
+ return (
113
+ (['if', 'elseif', 'while', '?'].includes(parent?.kind) && parent.children[0] === node) ||
114
+ (['&&', '||'].includes(parent?.kind) && parent.children.at(-1) !== node)
115
+ );
116
+ }
@@ -0,0 +1,38 @@
1
+ import { defineRule, isOpaque } from './common.js';
2
+ export default defineRule({
3
+ meta: {
4
+ type: 'suggestion',
5
+ hasSuggestions: true,
6
+ schema: [],
7
+ docs: { description: 'Suggest combining an if whose only statement is another if.' },
8
+ messages: {
9
+ issue: 'These nested if conditions can be combined with &&.',
10
+ combine: 'Combine conditions with &&.',
11
+ },
12
+ },
13
+ create(context) {
14
+ const source = context.sourceCode;
15
+ return {
16
+ if(node) {
17
+ if (!node.interior || node.children.length !== 2 || isOpaque(node, source)) return;
18
+ const body = node.children[1];
19
+ if (body?.kind !== 'block' || body.children.length !== 1) return;
20
+ const inner = body.children[0];
21
+ if (inner.kind !== 'if' || !inner.interior || inner.children.length !== 2) return;
22
+ const comments = source.comments.some(
23
+ (c) => c.range[0] >= node.range[0] && c.range[1] <= node.range[1],
24
+ );
25
+ const replacement = `if (${source.getText(node.children[0])}) && (${source.getText(inner.children[0])})${source.text.slice(inner.children[1].range[0], inner.range[1])}`;
26
+ context.report({
27
+ node,
28
+ messageId: 'issue',
29
+ ...(!comments && {
30
+ suggest: [
31
+ { messageId: 'combine', fix: (fixer) => fixer.replaceText(node, replacement) },
32
+ ],
33
+ }),
34
+ });
35
+ },
36
+ };
37
+ },
38
+ });
@@ -0,0 +1,24 @@
1
+ import { rule, ordinary, call, suggest, text } from './idiom-common.js';
2
+ import { rangeCount } from './performance-common.js';
3
+ export default rule(
4
+ 'Review collect of a literal integer range used only as a for iterator.',
5
+ {},
6
+ (context, m, source) => ({
7
+ for(node) {
8
+ if (!ordinary(node, source)) return;
9
+ const clause = node.children[0];
10
+ if (clause.kind !== 'iteration') return;
11
+ for (const pair of clause.children) {
12
+ const iterator = pair.children[1],
13
+ args = call(iterator, 'collect', m);
14
+ if (args?.length !== 1 || rangeCount(args[0], m) === null) continue;
15
+ suggest(
16
+ context,
17
+ iterator,
18
+ 'Iterate the literal integer range directly instead of collecting it; review allocation timing.',
19
+ text(source, args[0]),
20
+ );
21
+ }
22
+ },
23
+ }),
24
+ );
@@ -0,0 +1,50 @@
1
+ import { check, ordinary, binary, strip, text, span, baseAvailable } from './semantic-common.js';
2
+ export default check(
3
+ 'Report equality comparisons that cannot distinguish signed floating zero.',
4
+ (context, m, source) => ({
5
+ call(node) {
6
+ const p = binary(node);
7
+ if (!p || !ordinary(node, source)) return;
8
+ const [a, op, b] = p;
9
+ if (!['==', '!='].includes(op.value) || !m.isUnshadowedBuiltin(op, op.value)) return;
10
+ const negativeZero = (node) => {
11
+ node = strip(node);
12
+ return (
13
+ ['Float', 'Float32'].includes(node?.kind) &&
14
+ /^-0+(?:\.0*)?(?:[ef][+-]?\d+)?$/iu.test(node.value.replaceAll('_', ''))
15
+ );
16
+ };
17
+ if (!negativeZero(a) && !negativeZero(b)) return;
18
+ const range = span(source, node);
19
+ const comments = source.comments.some(
20
+ (c) => c.range[0] >= range[0] && c.range[1] <= range[1],
21
+ );
22
+ const available =
23
+ baseAvailable(m, node) &&
24
+ (op.value === '==' || m.lookup('!', m.scopeFor(node))?.kind === 'builtin');
25
+ const replacement = `${op.value === '!=' ? '!' : ''}Base.isequal(${text(source, a)}, ${text(source, b)})`;
26
+ context.report({
27
+ node,
28
+ messageId: 'diagnostic',
29
+ data: {
30
+ message:
31
+ 'Numeric equality can treat negative and positive floating zero alike; review whether a sign-sensitive comparison was intended.',
32
+ },
33
+ ...(available &&
34
+ !comments && {
35
+ suggest: [
36
+ {
37
+ messageId: 'replace',
38
+ data: {
39
+ message:
40
+ 'Use isequal to distinguish signed zero (also changes missing/custom-type behavior).',
41
+ },
42
+ fix: (fixer) => fixer.replaceTextRange(range, replacement),
43
+ },
44
+ ],
45
+ }),
46
+ });
47
+ },
48
+ }),
49
+ { suggestions: true },
50
+ );
@@ -0,0 +1,18 @@
1
+ import { rule, suggest } from './idiom-common.js';
2
+ import { growth } from './growth-common.js';
3
+ export default rule(
4
+ 'Review repeated vcat/hcat of a growing local Array in a loop.',
5
+ {},
6
+ (context, m, source) => {
7
+ const check = (node) => {
8
+ for (const recurrence of growth(node, 'array', m, source))
9
+ suggest(
10
+ context,
11
+ recurrence,
12
+ 'Repeated concatenation can copy the growing Array prefix; consider sized block writes, one final concatenation or append! for compatible vectors.',
13
+ );
14
+ };
15
+ return { for: check, while: check };
16
+ },
17
+ false,
18
+ );