Repository navigation
Expand file tree
/
Copy pathcheck_test_layout.py
More file actions
1934 lines (1711 loc) · 72.4 KB
/
Copy pathcheck_test_layout.py
File metadata and controls
1934 lines (1711 loc) · 72.4 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
#!/usr/bin/env python3
"""Check that tests live apart from the code that they test.
A Rust crate of the repository, a directory with a tracked Cargo.toml, keeps
its tests in test files: the files beneath the crate's `tests` directory, and
in `src/`, the `tests.rs` files and the files beneath a `tests` directory. The
crate's other files in `src/` are production files. A production file
declares its unit tests only as an out-of-line module named `tests` whose cfg
requires `test`, and whose file holds them:
#[cfg(test)]
mod tests;
A test file belongs to a module that a target of its crate whose tests
`cargo test` runs, its library, a binary, or an integration test, as the
crate's manifest names it or Cargo discovers it, reaches through `mod`
declarations from its root that builds of tests compile: no cfg that no build
of tests satisfies, such as `any()` or `not(test)`, guards one. The Rust
files of `tests/fixtures/` and `tests/vectors/` are data, not modules.
A production file holds no other test code: outside function bodies, no
inline module, module of another name, or item that a cfg requiring `test`
guards, directly or through cfg_attr; no test attribute, such as #[test],
#[should_panic], or #[ignore]; no proptest! block; and no #![cfg(test)] that
makes the whole file test-only. What it may hold are test hooks, the
attributes and cfg! invocations whose predicates mention `test`, such as a
field, statement, or match arm that only tests compile, or a derive that only
tests need: exactly as many as the seams of scripts/test-layout-allowlist.json
allow the file. A hook is test code that cannot move out of the code that it
hooks. `--tighten` lowers the seams to the hooks that the files hold; it never
raises an entry or adds a file.
Every module named `tests` is out of line and requires `test`, and its file
exists. No file in `src/` sets a module's file with #[path].
Python unit tests are the `test_*.py` modules of scripts/,
.github/specula/tests/, and .github/skills/*/scripts/, and the end-to-end
scenario drivers are the `*_tests.py` modules of scripts/nvx_tools/. No other
module imports unittest, pytest, doctest, a `test_*` module, or the
PowerShell test support of powershell_testing.py.
The checks read the files that Git tracks, so stage a new file before you run
them.
"""
from __future__ import annotations
import argparse
import ast
import bisect
import json
import os
import posixpath
import re
import subprocess
import sys
from collections.abc import Collection, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, cast
REPO_ROOT = Path(__file__).resolve().parents[1]
ALLOWLIST = "scripts/test-layout-allowlist.json"
ALLOWLIST_SCHEMA = "nvx-test-layout-allowlist"
ALLOWLIST_SCHEMA_VERSION = 2
TIGHTEN_COMMAND = "python3 scripts/check_test_layout.py --tighten"
# The directories, relative to a crate, of the data of its tests, such as
# fixtures and conformance vectors, whose Rust files are no modules.
TEST_DATA_DIRECTORIES = ("tests/fixtures/", "tests/vectors/")
# The places of the Python unit tests and of the end-to-end scenario drivers,
# and the modules that only the unit tests import.
PYTHON_UNIT_TESTS = re.compile(
r"(?:scripts|\.github/specula/tests|\.github/skills/[^/]+/scripts)"
r"/test_[^/]*\.py"
)
PYTHON_END_TO_END_TESTS = re.compile(r"scripts/nvx_tools/[^/]*_tests\.py")
PYTHON_TEST_SUPPORT = frozenset({"scripts/powershell_testing.py"})
PYTHON_TEST_FRAMEWORKS = frozenset({"doctest", "pytest", "unittest"})
# Attributes that only tests take, and those of them that make a function a
# test.
TEST_ATTRIBUTES = frozenset({"bench", "ignore", "should_panic", "test"})
TEST_FUNCTION_ATTRIBUTES = frozenset({"bench", "test"})
IDENT = "ident"
LIFETIME = "lifetime"
LITERAL = "literal"
PUNCT = "punct"
class CheckError(RuntimeError):
"""Raised when the files of the repository cannot be listed or read."""
@dataclass(frozen=True, order=True)
class Problem:
"""A place where test code is not where the layout puts it."""
path: str
line: int
rule: str
message: str
def __str__(self) -> str:
location = f"{self.path}:{self.line}" if self.line else self.path
return f"{location}: {self.rule}: {self.message}"
def annotation(self) -> str:
"""Formats the problem as a GitHub Actions error annotation."""
properties = f"file={_escape_property(self.path)}"
if self.line:
properties += f",line={self.line}"
return f"::error {properties}::{_escape_data(str(self))}"
def _escape_data(value: str) -> str:
return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
def _escape_property(value: str) -> str:
return _escape_data(value).replace(":", "%3A").replace(",", "%2C")
# Rust tokens.
class RustSyntaxError(ValueError):
"""Raised when a Rust file does not split into tokens whose brackets
balance."""
def __init__(self, line: int, message: str) -> None:
super().__init__(f"line {line}: {message}")
self.line = line
@dataclass(frozen=True)
class Token:
"""A token of Rust source: an identifier, which includes keywords and raw
identifiers; a lifetime or label; a literal; or one punctuation
character. Comments, doc comments included, are no tokens."""
kind: str
text: str
start: int
end: int
line: int
_SPACE_OR_LINE_COMMENT = re.compile(r"(?:\s+|//[^\n]*)+")
_BLOCK_COMMENT_DELIMITER = re.compile(r"/\*|\*/")
_IDENTIFIER = re.compile(r"[^\W\d]\w*")
_NUMBER = re.compile(r"[0-9]\w*(?:\.[0-9]\w*)?")
_STRING_REST = re.compile(r'[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL)
_CHAR = re.compile(
r"'(?:[^'\\\n]|\\(?:u\{[0-9A-Fa-f_]*\}|x[0-9A-Fa-f]{2}|.))'", re.DOTALL
)
_LIFETIME = re.compile(r"'(?:r#)?[^\W\d]\w*")
def tokenize_rust(text: str) -> list[Token]:
"""Splits Rust source into tokens, without its comments."""
newlines = [match.start() for match in re.finditer("\n", text)]
def line_of(offset: int) -> int:
return bisect.bisect_right(newlines, offset) + 1
tokens: list[Token] = []
def add(kind: str, start: int, end: int) -> int:
tokens.append(Token(kind, text[start:end], start, end, line_of(start)))
return end
position = 1 if text.startswith("\ufeff") else 0
size = len(text)
while position < size:
skipped = _SPACE_OR_LINE_COMMENT.match(text, position)
if skipped is not None:
position = skipped.end()
continue
if text.startswith("/*", position):
position = _block_comment_end(text, position, line_of(position))
continue
char = text[position]
if char == '"':
position = add(
LITERAL, position, _string_end(text, position, position + 1, line_of)
)
continue
if char == "'":
literal = _CHAR.match(text, position)
if literal is not None:
position = add(LITERAL, position, literal.end())
continue
lifetime = _LIFETIME.match(text, position)
if lifetime is not None:
position = add(LIFETIME, position, lifetime.end())
continue
position = add(PUNCT, position, position + 1)
continue
if "0" <= char <= "9":
number = _NUMBER.match(text, position)
assert number is not None
position = add(LITERAL, position, number.end())
continue
word = _IDENTIFIER.match(text, position)
if word is None:
position = add(PUNCT, position, position + 1)
continue
end = word.end()
prefix = word.group()
following = text[end] if end < size else ""
if prefix in ("r", "br", "cr") and following in ('"', "#"):
hashes = end
while hashes < size and text[hashes] == "#":
hashes += 1
if hashes < size and text[hashes] == '"':
delimiter = '"' + "#" * (hashes - end)
close = text.find(delimiter, hashes + 1)
if close < 0:
raise RustSyntaxError(line_of(position), "unterminated raw string")
position = add(LITERAL, position, close + len(delimiter))
continue
if prefix == "r" and hashes == end + 1:
raw = _IDENTIFIER.match(text, hashes)
if raw is not None:
position = add(IDENT, position, raw.end())
continue
elif prefix in ("b", "c") and following == '"':
position = add(
LITERAL, position, _string_end(text, position, end + 1, line_of)
)
continue
elif prefix == "b" and following == "'":
literal = _CHAR.match(text, end)
if literal is not None:
position = add(LITERAL, position, literal.end())
continue
position = add(IDENT, position, end)
return tokens
def _block_comment_end(text: str, start: int, line: int) -> int:
depth = 0
position = start
while True:
delimiter = _BLOCK_COMMENT_DELIMITER.search(text, position)
if delimiter is None:
raise RustSyntaxError(line, "unterminated block comment")
depth += 1 if delimiter.group() == "/*" else -1
position = delimiter.end()
if depth == 0:
return position
def _string_end(text: str, start: int, body: int, line_of: _LineOf) -> int:
rest = _STRING_REST.match(text, body)
if rest is None:
raise RustSyntaxError(line_of(start), "unterminated string")
return rest.end()
class _LineOf(Protocol):
def __call__(self, offset: int, /) -> int: ...
_CLOSERS = {")": "(", "]": "[", "}": "{"}
def match_brackets(tokens: Sequence[Token]) -> list[int]:
"""Returns, for each token, the index of the bracket that it opens or
closes, or -1."""
partner = [-1] * len(tokens)
stack: list[int] = []
for index, token in enumerate(tokens):
if token.kind != PUNCT:
continue
if token.text in "([{":
stack.append(index)
elif token.text in _CLOSERS:
if not stack or tokens[stack[-1]].text != _CLOSERS[token.text]:
raise RustSyntaxError(token.line, f"unbalanced {token.text!r}")
opener = stack.pop()
partner[opener] = index
partner[index] = opener
if stack:
raise RustSyntaxError(tokens[stack[-1]].line, "unclosed bracket")
return partner
def unraw(name: str) -> str:
"""Returns an identifier without its raw prefix, `r#`."""
return name[2:] if name.startswith("r#") else name
def is_token(tokens: Sequence[Token], index: int, kind: str, *texts: str) -> bool:
"""Whether the token at index is of kind and, if any texts are given, one
of them."""
if index >= len(tokens):
return False
token = tokens[index]
return token.kind == kind and (not texts or token.text in texts)
def _path(tokens: Sequence[Token], start: int, end: int) -> tuple[str, int]:
"""Reads a path of identifiers, such as `tokio::test`, from start; returns
it, empty when none starts there, and the index after it."""
index = start
if is_token(tokens, index, PUNCT, ":") and is_token(tokens, index + 1, PUNCT, ":"):
index += 2
parts: list[str] = []
while index < end and is_token(tokens, index, IDENT):
parts.append(unraw(tokens[index].text))
index += 1
if (
index + 2 < end
and is_token(tokens, index, PUNCT, ":")
and is_token(tokens, index + 1, PUNCT, ":")
and is_token(tokens, index + 2, IDENT)
):
index += 2
continue
break
if not parts:
return "", start
return "::".join(parts), index
def split_commas(
tokens: Sequence[Token], partner: Sequence[int], start: int, end: int
) -> list[tuple[int, int]]:
"""Splits the tokens from start to end at the commas outside brackets."""
pieces: list[tuple[int, int]] = []
piece = start
index = start
while index < end:
token = tokens[index]
if token.kind == PUNCT:
if token.text in "([{":
index = partner[index] + 1
continue
if token.text == ",":
pieces.append((piece, index))
piece = index + 1
index += 1
pieces.append((piece, end))
return [(first, last) for first, last in pieces if first < last]
# cfg predicates and attributes.
@dataclass(frozen=True)
class Cfg:
"""A cfg predicate: `all`, `any`, or `not` of operands; an `option`, with
the literal of its value if it has one; or `other`, whatever does not
parse, with its tokens."""
operator: str
name: str = ""
value: str | None = None
operands: tuple[Cfg, ...] = ()
words: tuple[str, ...] = ()
def parse_cfg(
tokens: Sequence[Token], partner: Sequence[int], start: int, end: int
) -> Cfg:
"""Parses the cfg predicate from start to end."""
if start < end and tokens[start].kind == IDENT:
name = unraw(tokens[start].text)
if start + 1 == end:
return Cfg("option", name)
if (
name in ("all", "any", "not")
and is_token(tokens, start + 1, PUNCT, "(")
and partner[start + 1] == end - 1
):
operands = tuple(
parse_cfg(tokens, partner, first, last)
for first, last in split_commas(tokens, partner, start + 2, end - 1)
)
return Cfg(name, operands=operands)
if (
start + 3 == end
and is_token(tokens, start + 1, PUNCT, "=")
and is_token(tokens, start + 2, LITERAL)
):
return Cfg("option", name, tokens[start + 2].text)
words = tuple(
token.text
for index, token in enumerate(tokens[start:end], start)
if token.kind == IDENT
and unraw(token.text) == "test"
and not is_token(tokens, index - 1, PUNCT, "$")
and not is_token(tokens, index + 1, PUNCT, "=")
)
return Cfg("other", words=words)
def mentions_test(cfg: Cfg) -> bool:
"""Whether the predicate depends on the `test` option."""
if cfg.operator == "option":
return cfg.name == "test" and cfg.value is None
if cfg.operator == "other":
return bool(cfg.words)
return any(mentions_test(operand) for operand in cfg.operands)
def requires_test(cfg: Cfg) -> bool:
"""Whether the predicate holds only when `test` does."""
if cfg.operator == "option":
return cfg.name == "test" and cfg.value is None
if cfg.operator == "all":
return any(requires_test(operand) for operand in cfg.operands)
if cfg.operator == "any":
live = [operand for operand in cfg.operands if not _never(operand)]
return bool(live) and all(requires_test(operand) for operand in live)
if cfg.operator == "not":
return len(cfg.operands) == 1 and forbids_test(cfg.operands[0])
return False
def forbids_test(cfg: Cfg) -> bool:
"""Whether the predicate holds only when `test` does not."""
if cfg.operator == "all":
return any(forbids_test(operand) for operand in cfg.operands)
if cfg.operator == "any":
live = [operand for operand in cfg.operands if not _never(operand)]
return bool(live) and all(forbids_test(operand) for operand in live)
if cfg.operator == "not":
return len(cfg.operands) == 1 and requires_test(cfg.operands[0])
return False
def _never(cfg: Cfg) -> bool:
"""Whether the predicate holds for no configuration, as `any()` does."""
if cfg.operator == "any":
return all(_never(operand) for operand in cfg.operands)
if cfg.operator == "all":
return any(_never(operand) for operand in cfg.operands)
if cfg.operator == "not":
return len(cfg.operands) == 1 and _always(cfg.operands[0])
return False
def _always(cfg: Cfg) -> bool:
"""Whether the predicate holds for every configuration, as `all()` does."""
if cfg.operator == "all":
return all(_always(operand) for operand in cfg.operands)
if cfg.operator == "any":
return any(_always(operand) for operand in cfg.operands)
if cfg.operator == "not":
return len(cfg.operands) == 1 and _never(cfg.operands[0])
return False
def excludes_tests(cfg: Cfg) -> bool:
"""Whether the predicate holds in no build of tests: for no configuration,
as `any()`, or only where `test` does not, as `not(test)`."""
return _never(cfg) or forbids_test(cfg)
@dataclass(frozen=True)
class Attribute:
"""An attribute: the indices of its `#` and of its closing `]`, its path,
such as `cfg` or `tokio::test`, empty when it starts with none, and the
range of the tokens between the delimiters after its path, if any."""
start: int
end: int
inner: bool
path: str
arguments: tuple[int, int] | None
line: int
def attribute_at(
tokens: Sequence[Token], partner: Sequence[int], index: int
) -> Attribute | None:
"""Returns the attribute whose `#` is at index, if one is."""
if not is_token(tokens, index, PUNCT, "#"):
return None
bracket = index + 1
inner = is_token(tokens, bracket, PUNCT, "!")
if inner:
bracket += 1
if not is_token(tokens, bracket, PUNCT, "["):
return None
close = partner[bracket]
path, after = _path(tokens, bracket + 1, close)
arguments = None
if path and after < close and is_token(tokens, after, PUNCT, "(", "[", "{"):
arguments = (after + 1, partner[after])
return Attribute(index, close, inner, path, arguments, tokens[index].line)
def attribute_cfg(
tokens: Sequence[Token], partner: Sequence[int], attribute: Attribute
) -> Cfg | None:
"""Returns the predicate of a #[cfg(...)] attribute."""
if attribute.path != "cfg" or attribute.arguments is None:
return None
return parse_cfg(tokens, partner, *attribute.arguments)
def attribute_requires_test(
tokens: Sequence[Token], partner: Sequence[int], attribute: Attribute
) -> bool:
"""Whether the attribute is a cfg that only lets tests compile what it
guards, or a cfg_attr that applies such a cfg wherever its predicate
holds: `cfg_attr(P, cfg(X))` guards with `any(not(P), X)`."""
if attribute.arguments is None:
return False
if attribute.path == "cfg":
return requires_test(parse_cfg(tokens, partner, *attribute.arguments))
if attribute.path == "cfg_attr":
return any(
requires_test(cfg)
for cfg in _cfg_attr_guards(tokens, partner, *attribute.arguments, ())
)
return False
def attribute_excludes_tests(
tokens: Sequence[Token], partner: Sequence[int], attribute: Attribute
) -> bool:
"""Whether the attribute is a cfg that no build of tests satisfies, or a
cfg_attr that applies one wherever tests build, so that what it is on
never compiles for tests, as with #[cfg(any())] or
#[cfg_attr(test, cfg(not(test)))]."""
if attribute.arguments is None:
return False
if attribute.path == "cfg":
return excludes_tests(parse_cfg(tokens, partner, *attribute.arguments))
if attribute.path == "cfg_attr":
return any(
excludes_tests(cfg)
for cfg in _cfg_attr_guards(tokens, partner, *attribute.arguments, ())
)
return False
def _cfg_attr_guards(
tokens: Sequence[Token],
partner: Sequence[int],
start: int,
end: int,
held: tuple[Cfg, ...],
) -> list[Cfg]:
"""Returns the predicates with which the cfgs that the cfg_attr from start
to end applies, where held holds too, guard what it is on."""
pieces = split_commas(tokens, partner, start, end)
if not pieces:
return []
held = (*held, parse_cfg(tokens, partner, *pieces[0]))
where = held[0] if len(held) == 1 else Cfg("all", operands=held)
guards: list[Cfg] = []
for first, last in pieces[1:]:
path, after = _path(tokens, first, last)
if not is_token(tokens, after, PUNCT, "(") or partner[after] != last - 1:
continue
if path == "cfg":
applied = parse_cfg(tokens, partner, after + 1, partner[after])
guards.append(Cfg("any", operands=(Cfg("not", operands=(where,)), applied)))
elif path == "cfg_attr":
guards.extend(
_cfg_attr_guards(tokens, partner, after + 1, partner[after], held)
)
return guards
def attribute_mentions_test(
tokens: Sequence[Token], partner: Sequence[int], attribute: Attribute
) -> bool:
"""Whether the attribute is a cfg or cfg_attr whose predicate, or that of
an attribute that it applies, depends on `test`."""
if attribute.arguments is None:
return False
if attribute.path == "cfg":
return mentions_test(parse_cfg(tokens, partner, *attribute.arguments))
if attribute.path == "cfg_attr":
return _cfg_attr_mentions_test(tokens, partner, *attribute.arguments)
return False
def _cfg_attr_mentions_test(
tokens: Sequence[Token], partner: Sequence[int], start: int, end: int
) -> bool:
pieces = split_commas(tokens, partner, start, end)
if not pieces:
return False
if mentions_test(parse_cfg(tokens, partner, *pieces[0])):
return True
for first, last in pieces[1:]:
path, after = _path(tokens, first, last)
if not is_token(tokens, after, PUNCT, "(") or partner[after] != last - 1:
continue
if path == "cfg" and mentions_test(
parse_cfg(tokens, partner, after + 1, last - 1)
):
return True
if path == "cfg_attr" and _cfg_attr_mentions_test(
tokens, partner, after + 1, last - 1
):
return True
return False
def attribute_paths(
tokens: Sequence[Token], partner: Sequence[int], attribute: Attribute
) -> list[str]:
"""Returns the paths of the attribute and of those that it applies through
cfg_attr."""
paths = [attribute.path]
if attribute.path == "cfg_attr" and attribute.arguments is not None:
paths.extend(_cfg_attr_paths(tokens, partner, *attribute.arguments))
return paths
def _cfg_attr_paths(
tokens: Sequence[Token], partner: Sequence[int], start: int, end: int
) -> list[str]:
paths: list[str] = []
for first, last in split_commas(tokens, partner, start, end)[1:]:
path, after = _path(tokens, first, last)
paths.append(path)
if path == "cfg_attr" and is_token(tokens, after, PUNCT, "("):
paths.extend(_cfg_attr_paths(tokens, partner, after + 1, partner[after]))
return paths
def is_test_attribute(path: str) -> bool:
"""Whether an attribute's path makes a test, such as #[test] or
#[tokio::test], or applies only to tests, such as #[ignore]."""
return path in TEST_ATTRIBUTES or path.endswith("::test")
def is_test_function_attribute(path: str) -> bool:
"""Whether an attribute's path makes its function a test or benchmark."""
return path in TEST_FUNCTION_ATTRIBUTES or path.endswith("::test")
# Rust items.
@dataclass
class Item:
"""An item: a module, function, type, impl, use, macro invocation, or
another. Its tokens run from start, its first attribute, through end,
exclusive; head is the first token after its attributes. A module, impl,
trait, extern block, or proptest! block holds the items between the braces
of its body."""
kind: str
name: str
start: int
head: int
end: int
line: int
attributes: tuple[Attribute, ...]
body: tuple[int, int] | None = None
inner_attributes: tuple[Attribute, ...] = ()
children: list[Item] = field(default_factory=list["Item"])
_QUALIFIERS = frozenset({"async", "auto", "default", "gen", "safe", "unsafe"})
_FUNCTION_QUALIFIERS = frozenset({"async", "extern", "fn", "safe", "unsafe"})
class _ItemParser:
def __init__(self, tokens: Sequence[Token], partner: Sequence[int]) -> None:
self.tokens = tokens
self.partner = partner
def block(self, start: int, end: int) -> tuple[tuple[Attribute, ...], list[Item]]:
"""Parses the inner attributes and the items from start to end."""
inner: list[Attribute] = []
index = start
while index < end:
attribute = attribute_at(self.tokens, self.partner, index)
if attribute is None or not attribute.inner:
break
inner.append(attribute)
index = attribute.end + 1
items: list[Item] = []
while index < end:
if is_token(self.tokens, index, PUNCT, ";"):
index += 1
continue
item = self.item(index, end)
items.append(item)
index = item.end
return tuple(inner), items
def item(self, start: int, end: int) -> Item:
tokens = self.tokens
index = start
attributes: list[Attribute] = []
while index < end:
attribute = attribute_at(tokens, self.partner, index)
if attribute is None:
break
attributes.append(attribute)
index = attribute.end + 1
head = index
line = tokens[head].line if head < end else tokens[start].line
def make(
kind: str,
name: str,
stop: int,
body: tuple[int, int] | None = None,
children: bool = False,
) -> Item:
item = Item(
kind, name, start, head, max(stop, head + 1), line, tuple(attributes)
)
if body is not None:
item.body = body
if children:
item.inner_attributes, item.children = self.block(
body[0] + 1, body[1]
)
return item
if head >= end:
return Item("other", "", start, head, end, line, tuple(attributes))
if is_token(tokens, index, IDENT, "pub"):
index += 1
if is_token(tokens, index, PUNCT, "("):
index = self.partner[index] + 1
keyword = index
while keyword < end and is_token(tokens, keyword, IDENT):
word = tokens[keyword].text
if word in _QUALIFIERS and is_token(tokens, keyword + 1, IDENT):
keyword += 1
elif word == "const" and is_token(
tokens, keyword + 1, IDENT, *_FUNCTION_QUALIFIERS
):
keyword += 1
elif word == "extern" and not is_token(tokens, keyword + 1, IDENT, "crate"):
after = keyword + 1
if is_token(tokens, after, LITERAL):
after += 1
if is_token(tokens, after, PUNCT, "{"):
return make(
"extern",
"",
self.partner[after] + 1,
(after, self.partner[after]),
True,
)
keyword = after
else:
break
word = tokens[keyword].text if is_token(tokens, keyword, IDENT) else ""
name = (
unraw(tokens[keyword + 1].text)
if is_token(tokens, keyword + 1, IDENT)
else ""
)
if word == "extern" and is_token(tokens, keyword + 1, IDENT, "crate"):
name = (
unraw(tokens[keyword + 2].text)
if is_token(tokens, keyword + 2, IDENT)
else ""
)
return make("extern crate", name, self._scan(keyword, end, False)[0])
if word == "mod" and name:
if is_token(tokens, keyword + 2, PUNCT, ";"):
return make("mod", name, keyword + 3)
if is_token(tokens, keyword + 2, PUNCT, "{"):
close = self.partner[keyword + 2]
return make("mod", name, close + 1, (keyword + 2, close), True)
if word in ("fn", "struct", "enum", "trait") or (word == "union" and name):
stop, brace = self._scan(keyword + 1, end, True, True)
if word == "trait" and brace is not None:
return make("trait", name, stop, (brace, stop - 1), True)
return make(word, name, stop, None if brace is None else (brace, stop - 1))
if word == "impl":
stop, brace = self._scan(keyword + 1, end, True, True)
header = " ".join(
token.text
for token in tokens[keyword : (brace if brace is not None else stop)]
)
if brace is None:
return make("impl", header, stop)
return make("impl", header, stop, (brace, stop - 1), True)
if word in ("type", "const", "static", "use"):
if word == "static" and is_token(tokens, keyword + 1, IDENT, "mut"):
name = (
unraw(tokens[keyword + 2].text)
if is_token(tokens, keyword + 2, IDENT)
else ""
)
return make(
word, "" if word == "use" else name, self._scan(keyword, end, False)[0]
)
path, after = _path(tokens, keyword, end)
if path and is_token(tokens, after, PUNCT, "!"):
group = after + 1
if path == "macro_rules" and is_token(tokens, group, IDENT):
name = unraw(tokens[group].text)
group += 1
else:
name = path
if is_token(tokens, group, PUNCT, "(", "[", "{"):
close = self.partner[group]
stop = close + 1
brace = tokens[group].text == "{"
if not brace and is_token(tokens, stop, PUNCT, ";"):
stop += 1
kind = "macro_rules" if path == "macro_rules" else "macro"
if brace and path.split("::")[-1] == "proptest":
return make(kind, name, stop, (group, close), True)
return make(kind, name, stop, (group, close) if brace else None)
return make("other", "", self._scan(head, end, True)[0])
def _scan(
self, index: int, end: int, braces: bool, generics: bool = False
) -> tuple[int, int | None]:
"""Returns the index after the item that runs on from index, and the
index of the brace that opens its body if it has one: the item ends
with the first `;` outside brackets or, if braces, with the first
`{...}` group outside them. In the header of a generic item, the
braces of a const argument inside `<...>`, as in `S<{ 1 }>`, open no
body."""
tokens = self.tokens
start = index
angles = 0
while index < end:
token = tokens[index]
if token.kind == PUNCT:
if token.text == ";" and not angles:
return index + 1, None
if token.text == "{" and braces and not angles:
return self.partner[index] + 1, index
if token.text in "([{":
index = self.partner[index] + 1
continue
if generics and token.text == "<":
angles += 1
elif (
generics
and token.text == ">"
and angles
and not is_token(tokens, index - 1, PUNCT, "-", "=")
):
angles -= 1
index += 1
if angles:
# A `<` that no `>` closes is no generic argument list.
return self._scan(start, end, braces)
return end, None
@dataclass
class RustFile:
"""A parsed Rust file: its tokens, the partners of its brackets, its inner
attributes and items, and every attribute and cfg! invocation in it, with
the index of the invocation's `cfg` and its predicate."""
tokens: list[Token]
partner: list[int]
inner_attributes: tuple[Attribute, ...]
items: list[Item]
attributes: list[Attribute]
cfg_macros: list[tuple[int, Cfg]]
def parse_rust(text: str) -> RustFile:
"""Parses Rust source; raises RustSyntaxError when it does not tokenize or
its brackets do not balance."""
tokens = tokenize_rust(text)
partner = match_brackets(tokens)
inner, items = _ItemParser(tokens, partner).block(0, len(tokens))
attributes: list[Attribute] = []
cfg_macros: list[tuple[int, Cfg]] = []
for index, token in enumerate(tokens):
if token.kind == PUNCT and token.text == "#":
attribute = attribute_at(tokens, partner, index)
if attribute is not None:
attributes.append(attribute)
elif (
token.kind == IDENT
and token.text == "cfg"
and is_token(tokens, index + 1, PUNCT, "!")
and is_token(tokens, index + 2, PUNCT, "(", "[", "{")
):
group = index + 2
cfg_macros.append(
(index, parse_cfg(tokens, partner, group + 1, partner[group]))
)
return RustFile(tokens, partner, inner, items, attributes, cfg_macros)
# The files of a repository.
class Snapshot(Protocol):
"""The tracked files of a tree, which may be a work tree or a commit."""
@property
def files(self) -> frozenset[str]: ...
def read(self, path: str) -> bytes: ...
def git(root: Path, *arguments: str, stdin: bytes | None = None) -> bytes:
"""Runs git in root and returns what it printed; raises CheckError when it
fails."""
try:
result = subprocess.run(
["git", *arguments],
cwd=root,
input=stdin,
capture_output=True,
check=False,
)
except OSError as error:
raise CheckError(f"cannot run git: {error}") from error
if result.returncode != 0:
detail = result.stderr.decode("utf-8", "replace").strip()
raise CheckError(f"git {arguments[0]} failed in {root}: {detail}")
return result.stdout
class WorkTree:
"""The tracked files of a Git work tree, outside its submodules."""
def __init__(self, root: Path) -> None:
self.root = root
files: set[str] = set()
for entry in git(root, "ls-files", "--stage", "-z").split(b"\0"):
if not entry:
continue
metadata, _, name = entry.partition(b"\t")
path = os.fsdecode(name)
if metadata.split()[0] != b"160000" and os.path.lexists(root / path):
files.add(path)
self._files = frozenset(files)
@property
def files(self) -> frozenset[str]:
return self._files
def read(self, path: str) -> bytes:
try:
return (self.root / path).read_bytes()
except OSError as error:
raise CheckError(f"cannot read {path}: {error}") from error
def decode(data: bytes) -> str:
"""Decodes a source file's bytes, with its newlines normalized."""
return data.decode("utf-8-sig", "replace").replace("\r\n", "\n").replace("\r", "\n")
def rust_crates(files: Iterable[str]) -> tuple[str, ...]:
"""Returns the directories of the tracked Cargo.toml files, the crates."""
return tuple(
sorted(
{
posixpath.dirname(path)
for path in files
if posixpath.basename(path) == "Cargo.toml"
}
)
)
_TOML_TABLE = re.compile(r"^\s*(\[\[?)\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$")
_TOML_KEY = re.compile(r"""^\s*([A-Za-z0-9_.-]+|"[^"]*"|'[^']*')\s*=\s*(.*?)\s*$""")
_TOML_VALUE = re.compile(
r"""(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|(true|false))\s*(?:#.*)?"""
)
# The directories where Cargo discovers each kind of target but the library,
# and the package settings that turn its discovery of each kind off.
_TARGET_DIRECTORIES = {
"bin": "src/bin",
"test": "tests",
"bench": "benches",
"example": "examples",
}
_DISCOVERY = {
"lib": "autolib",
"bin": "autobins",
"test": "autotests",
"bench": "autobenches",
"example": "autoexamples",
}
# The keys of the package and target tables that target_roots reads.
_TARGET_KEYS = frozenset({"name", "path", "test", *_DISCOVERY.values()})
def _unquoted(key: str) -> str:
"""Returns a TOML key or table name of one part without its quotes."""
if len(key) >= 2 and key[0] == key[-1] and key[0] in "\"'":