-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrules.py
More file actions
2166 lines (1873 loc) · 74.2 KB
/
rules.py
File metadata and controls
2166 lines (1873 loc) · 74.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Rule definitions for `m lint`.
Each rule is a callable that takes the source bytes, the parsed tree,
the file path, and a per-file ``NodeIndex``, and yields zero or more
``Diagnostic`` instances.
Rules carry zero or more *tags* describing their provenance and
applicability; profiles in :mod:`m_cli.lint.profiles` resolve to a
tag-filtered selection. Two tags are in active use today:
- ``xindex`` — rule was ported from the VA VistA Toolkit ``^XINDEX``
scanner. This is a *provenance* tag: it records where the rule
came from, not whether it is a VA-mandated coding rule.
- ``sac`` — rule maps to a documented section of the VA SAC
(Standards & Conventions). This is a *policy* tag: a ``sac``-
tagged rule is something a VistA reviewer would call out as
non-compliant. Most ``sac`` rules are also ``xindex`` because
XINDEX was VA's automated SAC checker, but the two sets are not
interchangeable — see "SAC tag policy" below.
A future IRIS- or YDB-style profile would introduce its own tag
(``iris-style``, ``ydb-best-practice``, …); rules from those
profiles would not carry ``xindex`` or ``sac``. The greenfield
modernization track uses the ``modern`` tag; see "Rule ID
prefixes" below.
Rule ID prefixes
================
Rule IDs follow ``M-<PREFIX>-<NN>``. Two prefixes are in active use:
- **``M-XINDX-NN``** — ported from the VA VistA Toolkit ``^XINDEX``
scanner. ``NN`` mirrors XINDEX's numeric error code 1:1
(so ``M-XINDX-013`` is XINDEX rule 13). Use this prefix only
when porting an XINDEX rule; never invent new ``M-XINDX-NN``
numbers.
- **``M-MOD-NN``** — modernization track. Greenfield rules derived
from contemporary M idioms (YottaDB and IRIS, post-2000 code)
and modern lint practice, independent of the XINDEX baseline.
``NN`` is sequential per the modernization roster
(see ``docs/m-linting-survey.md`` §7). M-MOD rules carry the
``modern`` tag so the ``modern`` profile selects them.
When an M-MOD rule supersedes a legacy XINDEX rule — a more precise
detector, a configurable threshold replacing a hard-coded one, an
engine-aware allowlist replacing an absolute ban — declare the
relationship via ``Rule.replaces=("M-XINDX-NN", ...)``. Tooling and
docs use that field for the cross-reference table; the runtime does
not currently auto-suppress the legacy rule when both apply (users
pick a profile and stick with it). The cross-reference is pinned by
``tests/test_lint_replaces.py``.
Future prefixes — ``M-IRIS-NN``, ``M-YDB-NN``, ``M-ANSI-NN`` — land
under their own profile and tag when those profiles ship.
SAC tag policy
==============
XINDEX has 66 numeric error codes. m-cli ships 42 of them. Of those
42, *31 map to a documented SAC requirement* and carry both
``xindex`` and ``sac``; the remaining 11 are XINDEX-internal smells
or bug detectors and carry only ``xindex``.
Heuristic: XINDEX itself flags SAC violations at severity STANDARD
("S") and pure code smells at WARNING / INFO. m-cli inherits that
classification for the rules it ported, with two judgment calls:
M-XINDX-002 (non-Kernel Z command) and M-XINDX-017 (first-line
label = routine name) are SAC mandates that m-cli surfaces at
FATAL / WARNING for stronger CI signal.
**SAC-tagged (31)** — carry both ``xindex`` and ``sac``:
002, 017, 019, 020, 022, 023, 024, 025, 026, 027,
028, 029, 030, 031, 032, 033, 034, 035, 036, 041,
044, 045, 047, 050, 054, 056, 057, 058, 060, 061, 062.
**Not SAC-tagged (11)** — bug detection, parse failures, hygiene
smells, or control-flow smells without a corresponding SAC section:
007 (undefined routine), 008 (undefined label), 009 (dead code
after QUIT), 013 (trailing blanks), 014 (missing label),
015 (duplicate label), 018 (control char), 021 (parse error),
042 (null line), 049 (unused label), 051 (empty IF/ELSE).
The classification is pinned by ``tests/test_lint_profiles.py`` —
adding a new SAC tag, or removing one, requires a deliberate test
update.
XINDEX coverage policy
======================
42 of XINDEX's 66 rules are registered (37 single-file + 3 cross-routine
[M-XINDX-007/008/049] + 2 control-flow [M-XINDX-009/051]). The remaining 24 fall into
four buckets — recorded here so future contributors don't re-litigate
each one:
**Permanently skipped — redundant with the parser ERROR catch-all
(``M-XINDX-021`` already surfaces these as fatal diagnostics).**
XINDEX was a text-based scanner; tree-sitter-m gives us proper
structural validation, so these no longer need their own rules:
1, 3 undefined command / undefined function — typo'd
keywords show up as command_keyword + ERROR child
5, 6 unmatched parens / unmatched quotes
8, 10 FOR without ``=`` / unrecognized SET argument
11, 12 invalid local / global variable name (parser only emits
``local_variable`` / ``global_variable`` nodes for valid
identifiers; anything else is ERROR)
37 invalid label
40 space where a command should be
53, 59 bad numeric literal / WRITE syntax
51 block-structure mismatch (already mapped to M-XINDX-021)
**Deferred — out of scope for single-file lint.** These need a
workspace index of all routines, a call graph, or data-flow tracking;
none currently exist. Re-evaluate when a workspace-wide analysis
phase is funded:
39 kill of protected variable (needs scope tracking)
43 wrong argument count to function (needs signatures)
52 cross-routine reference doesn't exist (needs workspace index)
55 violates VA programming standards (catch-all — too vague
without explicit mapping to specific SAC sections)
63 GO/DO mismatch from block structure (needs control-flow
analysis)
**Deferred — niche, low value-per-rule.** Each is doable on a single
file but the per-rule design and false-positive-tuning cost is high
relative to the editor-UX payoff. Pick these up if they surface as
real complaints from `m lint` users in the wild rather than working
through them mechanically:
16 error in pattern code (M's ``?`` pattern grammar)
38 call-to-this format-specific (XINDEX-internal classifier)
46, 48, 49 postconditional / argument quirks per command
**Permanently skipped — engine-specific.**
64, 66 Caché / ICR-specific rules (m-cli's source-level tools are
engine-neutral; runtime tools target YottaDB)
A higher-leverage future direction than chasing the XINDEX edge cases:
refining ``M-XINDX-021`` to emit *specific* parse-error messages by
inspecting what comes before each ERROR node. ``FOOBAR`` parsing as
``FO`` (FOR abbreviation) + ERROR ``OBAR`` could become
"Unknown command keyword 'FOOBAR'"; ``$NOSUCH(...)`` parsing as
``$N`` + ERROR ``OSUCH(...)`` could become "Unknown intrinsic
function '$NOSUCH'". Best done after the LSP ships so the win lands
in-editor.
"""
from __future__ import annotations
import re
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from m_cli.lint._index import NodeIndex
from m_cli.lint._keywords import standard_commands, standard_functions, standard_isvs
from m_cli.lint.diagnostic import Category, Diagnostic, Severity
if TYPE_CHECKING:
pass
# ---------------------------------------------------------------------------
# Rule metadata + registry
# ---------------------------------------------------------------------------
# Standard rule signature: (src, tree, path, index) -> diags. Context-
# aware rules (Rule.needs_context=True) take a 5th arg, a
# :class:`m_cli.lint.context.LintContext` carrying thresholds, the
# target engine, the workspace index, and the resolved Config. The
# runner dispatches on ``needs_context``. We use ``Callable[..., ...]``
# so both shapes type-check; the runtime dispatch is the source of
# truth.
RuleFn = Callable[..., Iterator[Diagnostic]]
@dataclass(frozen=True)
class Rule:
id: str
severity: Severity
category: Category
title: str
tags: tuple[str, ...]
check: RuleFn
# Optional id of an `m fmt` rule that auto-fixes this diagnostic. The
# LSP wrapper exposes this as a Quick Fix code action; CI tools can
# surface it as "auto-fixable". `None` when no auto-fix exists.
fixer_id: str | None = None
# When True, ``check`` takes a 5th positional arg: a
# :class:`m_cli.lint.context.LintContext` carrying thresholds, the
# target engine, the workspace index (when present), and the
# resolved Config. Rules that only need the AST leave this False
# (the default) and use the standard 4-arg signature.
#
# Replaces the legacy ``needs_workspace`` flag — cross-routine
# rules now set ``needs_context=True`` and read ``ctx.workspace``.
# Single mechanism, future-proof for engine-aware and threshold-
# driven rules.
needs_context: bool = False
# Cross-reference for the M-MOD-NN modernization track: legacy rule
# IDs that this rule supersedes / generalizes. Used by the modern
# profile to avoid double-flagging when a user runs both profiles,
# and by the cross-reference table in docs. Empty for rules that
# are not modernizations of a legacy rule.
replaces: tuple[str, ...] = ()
_REGISTRY: dict[str, Rule] = {}
def register(rule: Rule) -> Rule:
if rule.id in _REGISTRY:
raise ValueError(f"duplicate rule id: {rule.id}")
_REGISTRY[rule.id] = rule
return rule
def all_rules() -> list[Rule]:
return sorted(_REGISTRY.values(), key=lambda r: r.id)
def rules_by_tag(tag: str) -> list[Rule]:
return [r for r in _REGISTRY.values() if tag in r.tags]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _decode_line(b: bytes) -> str:
"""Decode a line for human-readable output. M source is mostly ASCII;
we pass through unknown bytes via latin-1."""
return b.decode("latin-1", errors="replace")
def _walk(node) -> Iterator:
"""Pre-order tree walk."""
yield node
for child in node.children:
yield from _walk(child)
# Tokens that signal a routine reaches labels through runtime
# introspection / indirection, beyond what static analysis can
# follow. Used by M-XINDX-049 to skip files where any label may
# be reachable via a string lookup.
_RUNTIME_LABEL_LOOKUP_MARKERS: tuple[bytes, ...] = (
b"$TEXT(",
b"$T(",
b" @",
b"\t@",
b"^DD(",
b"^DIC(",
b"^XOBV",
b"^ORD(",
)
def _routine_uses_runtime_label_lookup(src: bytes) -> bool:
"""True iff the routine source contains a marker indicating
runtime label dispatch — `$TEXT(LABEL+0)`, `D @var`, `^DD(` or
`^DIC(` xref tables, etc. A coarse but conservative heuristic:
we'd rather under-report the rule than emit thousands of false
positives on routines whose label graph is dynamic.
"""
return any(marker in src for marker in _RUNTIME_LABEL_LOOKUP_MARKERS)
# ---------------------------------------------------------------------------
# Text-based rules (don't need the AST)
# ---------------------------------------------------------------------------
def _check_trailing_blanks(
src: bytes, _tree, path: Path, _index: NodeIndex
) -> Iterator[Diagnostic]:
"""M-XINDX-013 — Blank(s) at end of line."""
for i, raw in enumerate(src.splitlines(), start=1):
if raw.endswith((b" ", b"\t")):
stripped = raw.rstrip(b" \t")
yield Diagnostic(
rule_id="M-XINDX-013",
severity=Severity.STYLE,
message="Blank(s) at end of line",
path=path,
line=i,
column=len(stripped) + 1,
column_end=len(raw) + 1,
line_text=_decode_line(raw),
)
register(
Rule(
id="M-XINDX-013",
severity=Severity.STYLE,
category=Category.STYLE,
title="Blank(s) at end of line",
tags=("xindex",),
check=_check_trailing_blanks,
fixer_id="trim-trailing-whitespace",
)
)
def _check_control_chars(src: bytes, _tree, path: Path, _index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-018 — Line contains a CONTROL (non-graphic) character."""
for i, raw in enumerate(src.splitlines(), start=1):
for col, byte in enumerate(raw, start=1):
# Allow tab (9). Flag other controls (0-8, 11-31) and DEL (127).
if (byte < 32 and byte != 9) or byte == 127:
yield Diagnostic(
rule_id="M-XINDX-018",
severity=Severity.STYLE,
message=f"Line contains a CONTROL (non-graphic) character (byte 0x{byte:02x})",
path=path,
line=i,
column=col,
column_end=col + 1,
line_text=_decode_line(raw),
)
break # one diagnostic per line is enough
register(
Rule(
id="M-XINDX-018",
severity=Severity.STYLE,
category=Category.STYLE,
title="Line contains a CONTROL (non-graphic) character",
tags=("xindex",),
check=_check_control_chars,
)
)
def _check_line_length(src: bytes, _tree, path: Path, _index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-019 — Line is longer than 245 bytes (SACC limit)."""
for i, raw in enumerate(src.splitlines(), start=1):
if len(raw) > 245:
yield Diagnostic(
rule_id="M-XINDX-019",
severity=Severity.STYLE,
message=f"Line is longer than 245 bytes ({len(raw)} bytes)",
path=path,
line=i,
column=246,
column_end=len(raw) + 1,
line_text=_decode_line(raw[:80] + b"..."),
)
register(
Rule(
id="M-XINDX-019",
severity=Severity.STYLE,
category=Category.STYLE,
title="Line is longer than 245 bytes",
tags=("xindex", "sac"),
check=_check_line_length,
)
)
def _check_null_line(src: bytes, _tree, path: Path, _index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-042 — Null line (no commands or comment).
A line with only whitespace and a newline contributes nothing.
First-and-only blank line at end of file is allowed.
"""
lines = src.splitlines()
for i, raw in enumerate(lines, start=1):
if raw.strip() == b"" and i < len(lines): # blank trailing line is fine
yield Diagnostic(
rule_id="M-XINDX-042",
severity=Severity.STYLE,
message="Null line (no commands or comment)",
path=path,
line=i,
column=1,
line_text="",
)
register(
Rule(
id="M-XINDX-042",
severity=Severity.STYLE,
category=Category.STYLE,
title="Null line (no commands or comment)",
tags=("xindex",),
check=_check_null_line,
)
)
# ---------------------------------------------------------------------------
# AST-based rules
# ---------------------------------------------------------------------------
def _node_line_col(node, src: bytes) -> tuple[int, int]:
"""Return (1-based line, 1-based column) of a tree-sitter node."""
return node.start_point[0] + 1, node.start_point[1] + 1
def _node_text(node, src: bytes) -> str:
return src[node.start_byte : node.end_byte].decode("latin-1", errors="replace")
def _line_text(src: bytes, line_num: int) -> str:
"""Get the (1-indexed) line as decoded text."""
lines = src.splitlines()
if 1 <= line_num <= len(lines):
return _decode_line(lines[line_num - 1])
return ""
def _collect_labels(index: NodeIndex, src: bytes) -> dict[str, list[tuple[int, int]]]:
"""Map label name → list of (line, col) where it is defined."""
labels: dict[str, list[tuple[int, int]]] = {}
for node in index.of("label"):
name = _node_text(node, src)
line, col = _node_line_col(node, src)
labels.setdefault(name, []).append((line, col))
return labels
def _check_first_label(src: bytes, _tree, path: Path, index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-017 — First line label NOT routine name.
The routine's first label must equal the file basename (without `.m`).
Excludes routines starting with `%` (XINDEX exclusion).
"""
for node in index.of("label"):
first_label = _node_text(node, src)
expected = path.stem
if expected.startswith("%"):
return
if first_label != expected:
line, col = _node_line_col(node, src)
yield Diagnostic(
rule_id="M-XINDX-017",
severity=Severity.WARNING,
message=(
f"First line label ('{first_label}') does not match routine name ('{expected}')"
),
path=path,
line=line,
column=col,
column_end=col + len(first_label),
line_text=_line_text(src, line),
extra={"first_label": first_label, "expected": expected},
)
return # only check the first label
register(
Rule(
id="M-XINDX-017",
severity=Severity.WARNING,
category=Category.BUG,
title="First line label NOT routine name",
tags=("xindex", "sac"),
check=_check_first_label,
)
)
def _check_duplicate_labels(
src: bytes, _tree, path: Path, index: NodeIndex
) -> Iterator[Diagnostic]:
"""M-XINDX-015 — Duplicate label."""
labels = _collect_labels(index, src)
for name, occurrences in labels.items():
if len(occurrences) > 1:
for line, col in occurrences[1:]: # skip first definition
yield Diagnostic(
rule_id="M-XINDX-015",
severity=Severity.WARNING,
message=(
f"Duplicate label: '{name}' (first defined at line {occurrences[0][0]})"
),
path=path,
line=line,
column=col,
column_end=col + len(name),
line_text=_line_text(src, line),
extra={"label": name, "first_line": occurrences[0][0]},
)
register(
Rule(
id="M-XINDX-015",
severity=Severity.WARNING,
category=Category.BUG,
title="Duplicate label",
tags=("xindex",),
check=_check_duplicate_labels,
)
)
def _check_missing_label_call(
src: bytes, _tree, path: Path, index: NodeIndex
) -> Iterator[Diagnostic]:
"""M-XINDX-014 — Call to missing label '|' in this routine.
Looks at:
- `do <label>` / `do <label>(args)` / `goto <label>` / `job <label>`
where the argument is a bare local-variable-shaped reference
(no `^routine`) — these are in-routine label calls.
- `do <label>^<routine>` / `$$<func>^<routine>` where the routine
equals this file's routine name.
- `$$<func>` / `$$<func>(args)` — extrinsic function calls in the
current routine.
Cross-routine calls (`label^OTHER`) are out of scope: XINDEX's full
check resolves them via the routine database, which we don't have
at lint time. We only flag in-routine calls.
"""
labels = _collect_labels(index, src)
label_set = set(labels)
this_routine = path.stem
for node in index.of("command"):
yield from _check_command_label_calls(node, src, label_set, this_routine, path)
for node in index.of("extrinsic_function"):
yield from _check_extrinsic_label_call(node, src, label_set, this_routine, path)
def _check_command_label_calls(
cmd_node, src: bytes, label_set: set[str], this_routine: str, path: Path
) -> Iterator[Diagnostic]:
"""For `do`/`goto`/`job` commands, walk arguments looking for label refs."""
kw_node = next((c for c in cmd_node.children if c.type == "command_keyword"), None)
if kw_node is None:
return
kw = _node_text(kw_node, src).upper()
if kw not in ("D", "DO", "G", "GOTO", "J", "JOB"):
return
arg_list = next((c for c in cmd_node.children if c.type == "argument_list"), None)
if arg_list is None:
return
for arg in arg_list.children:
if arg.type != "argument":
continue
yield from _label_call_from_arg(arg, src, label_set, this_routine, path)
def _label_call_from_arg(
arg_node, src: bytes, label_set: set[str], this_routine: str, path: Path
) -> Iterator[Diagnostic]:
"""The argument's payload is the first child node (modulo punctuation)."""
payload = next(
(c for c in arg_node.children if c.type not in ("(", ")", ",")),
None,
)
if payload is None:
return
if payload.type == "entry_reference":
# `label^routine` form. Label can be `identifier` OR `number`
# (numeric labels). Routine after `^` is always `identifier`.
children = list(payload.children)
caret_idx = next(
(i for i, c in enumerate(children) if c.type == "^"),
None,
)
if caret_idx is not None:
# Cross-routine: check the routine name after ^
if caret_idx + 1 < len(children):
target_routine = _node_text(children[caret_idx + 1], src)
if target_routine != this_routine:
return # cross-routine call: out of scope
# Label is the node before ^ (may be empty for `^routine`)
if caret_idx == 0:
return # `^routine` form — no in-routine label to check
label_node = children[caret_idx - 1]
else:
# No ^ — bare label call (rare under entry_reference)
if not children:
return
label_node = children[0]
# We only check named labels; numeric labels (like `do 5^foo` or
# `do 5` in same routine) are out of scope for the in-routine
# missing-label check until we add numeric-label tracking.
if label_node.type != "identifier":
return
label_name = _node_text(label_node, src)
elif payload.type == "variable":
# Bare-label form: variable > local_variable > identifier
local_var = next((c for c in payload.children if c.type == "local_variable"), None)
if local_var is None:
return
label_node = next((c for c in local_var.children if c.type == "identifier"), None)
if label_node is None:
return
label_name = _node_text(label_node, src)
else:
return
if label_name not in label_set:
line, col = _node_line_col(label_node, src)
yield Diagnostic(
rule_id="M-XINDX-014",
severity=Severity.ERROR,
message=f"Call to missing label '{label_name}' in this routine",
path=path,
line=line,
column=col,
column_end=col + len(label_name),
line_text=_line_text(src, line),
extra={"label": label_name},
)
def _check_extrinsic_label_call(
func_node, src: bytes, label_set: set[str], this_routine: str, path: Path
) -> Iterator[Diagnostic]:
"""`$$func` / `$$func^routine` extrinsic function calls."""
ids = [c for c in func_node.children if c.type == "identifier"]
has_caret = any(c.type == "^" for c in func_node.children)
if len(ids) < 1:
return
label_node = ids[0]
if has_caret and len(ids) >= 2:
target_routine = _node_text(ids[1], src)
if target_routine != this_routine:
return # cross-routine call
label_name = _node_text(label_node, src)
if label_name not in label_set:
line, col = _node_line_col(label_node, src)
yield Diagnostic(
rule_id="M-XINDX-014",
severity=Severity.ERROR,
message=f"Call to missing label '{label_name}' in this routine",
path=path,
line=line,
column=col,
column_end=col + len(label_name),
line_text=_line_text(src, line),
extra={"label": label_name},
)
register(
Rule(
id="M-XINDX-014",
severity=Severity.ERROR,
category=Category.BUG,
title="Call to missing label in this routine",
tags=("xindex",),
check=_check_missing_label_call,
)
)
def _check_break_command(src: bytes, _tree, path: Path, index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-025 — Break command used (BREAK is dev-only)."""
for node in index.of("command_keyword"):
kw = _node_text(node, src).upper()
if kw in ("B", "BREAK"):
line, col = _node_line_col(node, src)
yield Diagnostic(
rule_id="M-XINDX-025",
severity=Severity.WARNING,
message="BREAK command used (debug-only; should not appear in production code)",
path=path,
line=line,
column=col,
column_end=col + len(kw),
line_text=_line_text(src, line),
)
register(
Rule(
id="M-XINDX-025",
severity=Severity.WARNING,
category=Category.BUG,
title="BREAK command used",
tags=("xindex", "sac"),
check=_check_break_command,
)
)
def _check_lowercase_command(
src: bytes, _tree, path: Path, index: NodeIndex
) -> Iterator[Diagnostic]:
"""M-XINDX-047 — Lowercase command(s) used in line.
XINDEX flags commands written in lowercase. Modern style (and the
m-tools 'lowercase pythonic MUMPS' convention) actually *prefers*
lowercase, so this rule is provided for XINDEX-parity but not
enabled in modern profiles. It is still in the `xindex` tag.
"""
for node in index.of("command_keyword"):
kw = _node_text(node, src)
# If keyword has any lowercase letters, flag it
if any(c.islower() for c in kw):
line, col = _node_line_col(node, src)
yield Diagnostic(
rule_id="M-XINDX-047",
severity=Severity.STYLE,
message=(
f"Lowercase command used: '{kw}' "
f"(XINDEX style; modern profiles often allow this)"
),
path=path,
line=line,
column=col,
column_end=col + len(kw),
line_text=_line_text(src, line),
extra={"command": kw},
)
register(
Rule(
id="M-XINDX-047",
severity=Severity.STYLE,
category=Category.STYLE,
title="Lowercase command(s) used in line",
tags=("xindex", "sac"),
check=_check_lowercase_command,
fixer_id="uppercase-command-keywords",
)
)
def _check_routine_size(src: bytes, _tree, path: Path, _index: NodeIndex) -> Iterator[Diagnostic]:
"""M-XINDX-035 — Routine exceeds SACC maximum size of 20000 bytes."""
if len(src) > 20000:
yield Diagnostic(
rule_id="M-XINDX-035",
severity=Severity.STYLE,
message=f"Routine exceeds SACC maximum size of 20000 bytes ({len(src)} bytes)",
path=path,
line=1,
column=1,
extra={"size_bytes": len(src)},
)
register(
Rule(
id="M-XINDX-035",
severity=Severity.STYLE,
category=Category.COMPLEXITY,
title="Routine exceeds SACC maximum size of 20000 bytes",
tags=("xindex", "sac"),
check=_check_routine_size,
)
)
def _check_second_line_sac(
src: bytes, _tree, path: Path, _index: NodeIndex
) -> Iterator[Diagnostic]:
"""M-XINDX-044 — 2nd line of routine violates the SAC.
SAC requires the second line in the form ` ;;version;package;...;date;build`.
"""
lines = src.splitlines()
if len(lines) < 2:
return
second = lines[1]
# Must start with ` ;;` (one indent space, two semicolons)
if not re.match(rb"^[ \t]*;;", second):
yield Diagnostic(
rule_id="M-XINDX-044",
severity=Severity.INFO,
message=(
"2nd line of routine violates the SAC "
"(must start with ';;version;package;...;date;build')"
),
path=path,
line=2,
column=1,
line_text=_decode_line(second),
)
register(
Rule(
id="M-XINDX-044",
severity=Severity.INFO,
category=Category.DOCUMENTATION,
title="2nd line of routine violates the SAC",
tags=("xindex", "sac", "vista"),
check=_check_second_line_sac,
)
)
# ---------------------------------------------------------------------------
# Helpers for command-keyword-based rules
# ---------------------------------------------------------------------------
def _commands(index: NodeIndex, src: bytes) -> Iterator[tuple]:
"""Yield (command_node, keyword_text_upper, kw_node) for every command."""
for node in index.of("command"):
kw_node = next((c for c in node.children if c.type == "command_keyword"), None)
if kw_node is None:
continue
kw = _node_text(kw_node, src).upper()
yield node, kw, kw_node
def _arg_list(cmd_node):
"""Return the argument_list child or None."""
return next((c for c in cmd_node.children if c.type == "argument_list"), None)
def _arguments(cmd_node):
"""Yield argument children of a command, or nothing if no arg_list."""
al = _arg_list(cmd_node)
if al is None:
return
for c in al.children:
if c.type == "argument":
yield c
def _has_postconditional(cmd_node) -> bool:
"""Check if the command itself has a `:condition` postconditional."""
return any(c.type == "command_postconditional" for c in cmd_node.children)
def _arg_has_timeout(arg_node) -> bool:
"""Check if argument has an `argument_postconditional` (`:timeout`)."""
return any(c.type == "argument_postconditional" for c in arg_node.children)
def _payload(arg_node):
"""First non-trivial child of an argument node."""
return next(
(c for c in arg_node.children if c.type not in ("(", ")", ",")),
None,
)
# ---------------------------------------------------------------------------
# Additional XINDEX rules
# ---------------------------------------------------------------------------
# --- M-XINDX-020: VIEW command used --------------------------------------
def _check_view_command(src, _tree, path, index):
for cmd, kw, kw_node in _commands(index, src):
if kw in ("V", "VIEW"):
line, col = _node_line_col(kw_node, src)
yield Diagnostic(
rule_id="M-XINDX-020",
severity=Severity.WARNING,
message="VIEW command used (non-portable; vendor-specific)",
path=path,
line=line,
column=col,
column_end=col + len(kw),
line_text=_line_text(src, line),
)
register(
Rule(
id="M-XINDX-020",
severity=Severity.WARNING,
category=Category.PORTABILITY,
title="VIEW command used",
tags=("xindex", "sac"),
check=_check_view_command,
)
)
# --- M-XINDX-022: Exclusive Kill (`KILL (var,...)`) ----------------------
def _check_exclusive_kill(src, _tree, path, index):
for cmd, kw, kw_node in _commands(index, src):
if kw not in ("K", "KILL"):
continue
for arg in _arguments(cmd):
payload = _payload(arg)
if payload is not None and payload.type == "set_target_list":
line, col = _node_line_col(kw_node, src)
yield Diagnostic(
rule_id="M-XINDX-022",
severity=Severity.STYLE,
message="Exclusive KILL — KILL (var,…) is non-standard / dangerous",
path=path,
line=line,
column=col,
column_end=col + len(kw),
line_text=_line_text(src, line),
)
break
register(
Rule(
id="M-XINDX-022",
severity=Severity.STYLE,
category=Category.STYLE,
title="Exclusive Kill",
tags=("xindex", "sac"),
check=_check_exclusive_kill,
)
)
# --- M-XINDX-023: Unargumented Kill --------------------------------------
def _check_unargumented_kill(src, _tree, path, index):
for cmd, kw, kw_node in _commands(index, src):
if kw not in ("K", "KILL"):
continue
if _arg_list(cmd) is None:
line, col = _node_line_col(kw_node, src)
yield Diagnostic(
rule_id="M-XINDX-023",
severity=Severity.WARNING,
message="Unargumented KILL — kills all locals; almost never what is intended",
path=path,
line=line,
column=col,
column_end=col + len(kw),
line_text=_line_text(src, line),
)
register(
Rule(
id="M-XINDX-023",
severity=Severity.WARNING,
category=Category.BUG,
title="Unargumented Kill",
tags=("xindex", "sac"),
check=_check_unargumented_kill,
)
)
# --- M-XINDX-024: Kill of unsubscripted global ---------------------------
def _check_kill_unsubscripted_global(src, _tree, path, index):
for cmd, kw, kw_node in _commands(index, src):
if kw not in ("K", "KILL"):
continue
for arg in _arguments(cmd):
payload = _payload(arg)
if payload is None or payload.type != "variable":
continue
gv = next((c for c in payload.children if c.type == "global_variable"), None)
if gv is None:
continue
has_subs = any(c.type == "subscripts" for c in gv.children)
if not has_subs:
line, col = _node_line_col(gv, src)
yield Diagnostic(
rule_id="M-XINDX-024",
severity=Severity.ERROR,
message="Kill of an unsubscripted global (kills the entire global tree)",
path=path,
line=line,
column=col,
column_end=col + len(_node_text(gv, src)),
line_text=_line_text(src, line),
)
register(
Rule(
id="M-XINDX-024",
severity=Severity.ERROR,
category=Category.BUG,
title="Kill of an unsubscripted global",
tags=("xindex", "sac"),
check=_check_kill_unsubscripted_global,
)
)
# --- M-XINDX-026: Exclusive or Unargumented NEW --------------------------
def _check_new_exclusive_or_unargumented(src, _tree, path, index):
for cmd, kw, kw_node in _commands(index, src):
if kw not in ("N", "NEW"):
continue
al = _arg_list(cmd)
line, col = _node_line_col(kw_node, src)
if al is None:
yield Diagnostic(
rule_id="M-XINDX-026",