Repository navigation
Expand file tree
/
Copy pathcheck_test_changes.py
More file actions
2868 lines (2569 loc) · 105 KB
/
Copy pathcheck_test_changes.py
File metadata and controls
2868 lines (2569 loc) · 105 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
"""Flag the changes of a pull request to its repository's existing tests.
Compares the head of a pull request with its merge base, and reports every
existing test asset that the head modifies or removes, in six categories:
- test code: the items of the Rust test files and of the code that only tests
compile in production files, such as an inline `tests` module, a test
helper, or a test hook; the functions, classes, and other statements of the
Python unit tests and of their PowerShell test support;
- test data: fixtures, conformance vectors, and other data files of the tests,
and the scenario and adversarial case lists;
- end-to-end tests: the scenario drivers, the `*_tests.py` modules of
scripts/nvx_tools/, the guest scripts of the microVM tests, and the guest
probes;
- test doubles: the fake OpenVMM of `nvx::testing` and its binary;
- test policy: an allowlist entry of scripts/test-layout-allowlist.json that
is new or allows more, and any change to the layout check, to this script,
or to its workflow;
- CI test wiring: a removed or changed line of the actions and workflow that
run the tests, and of the ci.yml jobs that run them, or an added line there
that may skip them, such as an `if:`, a `continue-on-error`, or a
conditional that wraps a test command; a test job
that ci.yml no longer has, and a test action, workflow, command, module, or
scenario that it no longer names; and a scenario that leaves a backend's
shards. Comments count for none of these.
It compares items, not lines: a Rust item is the same item where it keeps its
module path, kind, name, and cfg, so an inline `tests` module that moves to
its own file keeps its items. Formatting, comments, lint attributes, imports'
order, and visibility do not count, nor does an item that moves unchanged
under the same cfg predicates, its own and those that it inherits from its
module and file, in each way that a target compiles it, such as a test helper
that moves into a `tests` module with its cfg(test) dropped. A new test flags
nothing, and a test whose module no
target of its crate compiles any more, as when its crate's manifest sets the
`test` key of its target to false or roots the target elsewhere, counts as
removed.
The script reads the commits' blobs and never runs their code, so a
workflow that pull_request_target triggers can run it, from the default
branch, on the commits of any pull request.
"""
from __future__ import annotations
import argparse
import ast
import copy
import difflib
import json
import os
import posixpath
import re
import subprocess
import sys
import urllib.parse
from collections import Counter, defaultdict
from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import cast
import check_test_layout as layout
from check_test_layout import IDENT, LITERAL, PUNCT, Item, RustFile, Token
REPO_ROOT = layout.REPO_ROOT
DEFAULT_BASE = "origin/dev"
LABEL = "tests-modified"
LABEL_COLOR = "d93f0b"
LABEL_DESCRIPTION = "Changes existing tests, test data, or test wiring"
COMMENT_MARKER = "<!-- nvx-test-changes -->"
# GitHub refuses comments longer than 65536 characters.
COMMENT_LIMIT = 60000
ROWS_PER_SECTION = 50
TEST_CODE = "test code"
TEST_DATA = "test data"
END_TO_END = "end-to-end tests"
TEST_DOUBLES = "test doubles"
TEST_POLICY = "test policy"
CI_WIRING = "CI test wiring"
CATEGORIES = (TEST_CODE, TEST_DATA, END_TO_END, TEST_DOUBLES, TEST_POLICY, CI_WIRING)
# The actions that flag a pull request.
FLAGGING = frozenset({"modified", "removed", "loosened", "added a line that may skip"})
POLICY_FILES = frozenset(
{
"scripts/check_test_changes.py",
"scripts/check_test_layout.py",
".github/workflows/test-changes.yml",
}
)
# The actions and workflow that run tests and nothing else, whose every line is
# test wiring, and the workflow that names them, whose test actions,
# workflows, commands, modules, and scenarios are.
WIRING_FILES = frozenset(
{
".github/actions/check-nvx-rs/action.yml",
".github/actions/check-quality/action.yml",
".github/actions/validate-nvx/action.yml",
".github/workflows/run-nvx-microvm-tests.yml",
}
)
WIRING_TOKEN_FILES = frozenset({".github/workflows/ci.yml"})
SHARDS_FILE = "scripts/nvx_tools/microvm_shards.json"
DOUBLES = re.compile(r"nvx-rs/src/testing/.+\.rs|nvx-rs/src/bin/nvx-fake-openvmm\.rs")
END_TO_END_FILES = re.compile(
r"scripts/nvx_tools/microvm_test_scripts/.+"
r"|guest/common/nvx-(?:identity-probe|sandbox-smoke|virtio-restore-probe)"
)
TEST_DATA_FILES = re.compile(
r"scripts/nvx_tools/adversarial_cases/.+|tests/runtime-adapter/scenarios\.txt"
)
# Lines that may keep tests from running when a test action or workflow adds
# them: a step's condition or its tolerance of failure, a command that ends the
# script early or skips tests, and a shell or PowerShell conditional or loop,
# which may wrap a test command without changing its line.
SKIPPING = re.compile(
r"continue-on-error|(?:^|\s)if:|\|\|\s*(?:true|:)(?:\s|$)|\bexit\s+0\b"
r"|--skip\b|--exclude\b"
r"|(?:^\s*|[;&|:]\s*)(?i:if|elif|elseif|else|then|fi|case|esac|switch|while"
r"|until|for|foreach|do|done|return)\b(?!:)"
)
# A Python test module that a test command names, such as scripts/test_a.py.
TEST_MODULE = re.compile(r"(?:\.[/\\])?(?:[\w.-]+[/\\])*test_\w+\.py")
WIRING_TOKENS = (
re.compile(
r"uses:\s*(\./\.github/(?:actions/(?:check-nvx-rs|check-quality|validate-nvx)"
r"|workflows/run-nvx-microvm-tests\.yml))"
),
re.compile(r"\bnvx\.py\s+((?:test|check)-[\w-]+)"),
re.compile(r"--scenario\s+([\w.-]+)"),
re.compile(r"scripts[/\\](test_\w+\.py)"),
re.compile(r"(\bcargo\b[^\n]*\b(?:test|nextest)\b[^\n]*)"),
)
LINT_ATTRIBUTES = frozenset({"allow", "deny", "expect", "forbid", "warn"})
class FlagError(RuntimeError):
"""Raised when the commits cannot be compared or the pull request cannot
be flagged."""
# What changed.
@dataclass(frozen=True)
class Location:
path: str
line: int
@dataclass(frozen=True)
class Change:
"""A change to a test asset: modified, removed, relocated, added, or one
of the actions of the test policy and CI wiring."""
category: str
action: str
kind: str
what: str
base: Location | None = None
head: Location | None = None
detail: str = ""
@property
def flags(self) -> bool:
return self.action in FLAGGING
def order(self) -> tuple[int, str, str, str, int, str, int, str]:
"""Sorts changes by category, action, kind, and place."""
base = self.base or Location("", 0)
head = self.head or Location("", 0)
return (
CATEGORIES.index(self.category),
self.action,
self.kind,
base.path,
base.line,
head.path,
head.line,
self.what,
)
# The ways that code compiles: for each target that compiles it, through each
# chain of declarations, the cfg predicates that must all hold. The
# conditions of code that compiles where nothing needs to hold, or nowhere,
# are ANYWHERE and empty.
Conditions = frozenset[frozenset[str]]
ANYWHERE: Conditions = frozenset({frozenset()})
def _reduced(ways: Iterable[frozenset[str]]) -> Conditions:
"""Returns ways without those that another, which needs fewer predicates
to hold, makes moot."""
unique = set(ways)
return frozenset(way for way in unique if not any(other < way for other in unique))
def _within(conditions: Conditions, predicates: Iterable[str]) -> Conditions:
"""Returns the ways that code compiles where conditions say that the code
that holds it does, and predicates hold too."""
added = frozenset(predicates)
return _reduced(way | added for way in conditions)
@dataclass(frozen=True)
class Entry:
"""A test asset that may change: an item, a pseudo-item such as a module's
imports, or a file. Its key identifies it across commits; loose is its
kind and name, and scope the module or file and container that hold it.
content is what counts as a change, and moved what an unchanged copy
elsewhere holds. The content of a monotone entry is a set of lines, which
may grow without changing what it was. conditions are the ways that a
Rust item compiles: for each, the cfg predicates that must hold, its own
and those that its module and the items that hold it inherit, which a move
must keep."""
key: tuple[str, ...]
loose: tuple[str, ...]
scope: tuple[str, ...]
name: str
content: str
moved: str
category: str
kind: str
what: str
location: Location
monotone: bool = False
conditions: Conditions = ANYWHERE
# How alike the content of a removed entry and of a new one in the same scope
# must be for the new one to count as the old one renamed.
RENAMED_SIMILARITY = 0.6
_WORDS = re.compile(r"\w+|[^\w\s]")
def compare(base: Sequence[Entry], head: Sequence[Entry]) -> list[Change]:
"""Compares the entries of two commits: an entry of both is modified when
its content or its conditions changed; one of the base only is relocated
when the head holds its content elsewhere under its conditions, modified
when the head holds its content under others, or an entry of its kind and
name or, in its scope, of content like its own, and removed otherwise;
and one of the head only is added."""
before = {entry.key: entry for entry in base}
after = {entry.key: entry for entry in head}
changes: list[Change] = []
for key in sorted(before.keys() & after.keys()):
old, new = before[key], after[key]
same_conditions = old.conditions == new.conditions
if old.content == new.content and same_conditions:
if old.location.path != new.location.path:
changes.append(_change(old, new, "relocated"))
continue
if (
old.monotone
and same_conditions
and set(old.content.split("\n")) <= set(new.content.split("\n"))
):
changes.append(_change(old, new, "extended"))
continue
details = [] if old.content == new.content else [_detail(old, new)]
if not same_conditions:
details.append(_conditions_detail(old, new))
changes.append(_change(old, new, "modified", _join(details)))
removed = [before[key] for key in sorted(before.keys() - after.keys())]
unmatched = {key: after[key] for key in sorted(after.keys() - before.keys())}
by_moved: dict[str, list[Entry]] = defaultdict(list)
by_loose: dict[tuple[str, ...], list[Entry]] = defaultdict(list)
by_scope: dict[tuple[str, ...], list[Entry]] = defaultdict(list)
for entry in unmatched.values():
by_moved[entry.moved].append(entry)
by_loose[entry.loose].append(entry)
by_scope[entry.scope].append(entry)
def take(candidates: Sequence[Entry], entry: Entry) -> Entry | None:
"""Takes the unmatched candidate most like entry: of its conditions,
then of its kind and name."""
left = [candidate for candidate in candidates if candidate.key in unmatched]
if not left:
return None
match = min(
left,
key=lambda candidate: (
candidate.conditions != entry.conditions,
candidate.loose != entry.loose,
),
)
del unmatched[match.key]
return match
left: list[Entry] = []
for entry in removed:
match = take(by_moved.get(entry.moved, []), entry)
if match is None:
left.append(entry)
elif match.conditions == entry.conditions:
changes.append(_change(entry, match, "relocated"))
else:
detail = _join(["moved", _conditions_detail(entry, match)])
changes.append(_change(entry, match, "modified", detail))
for entry in left:
match = take(by_loose.get(entry.loose, []), entry) if entry.name else None
if match is not None:
details = [_detail(entry, match, moved=True)]
if match.conditions != entry.conditions:
details.append(_conditions_detail(entry, match))
changes.append(_change(entry, match, "modified", _join(details)))
continue
match = _renamed(entry, by_scope.get(entry.scope, []), unmatched)
if match is not None:
del unmatched[match.key]
details = [f"renamed to `{match.name}`"]
if match.conditions != entry.conditions:
details.append(_conditions_detail(entry, match))
changes.append(_change(entry, match, "modified", _join(details)))
continue
changes.append(_change(entry, None, "removed"))
changes.extend(_change(None, entry, "added") for entry in unmatched.values())
return changes
def _join(details: Sequence[str]) -> str:
return ", and ".join(detail for detail in details if detail)
def _conditions_detail(old: Entry, new: Entry) -> str:
"""Says how the conditions under which an entry compiles changed."""
def listed(conditions: Conditions) -> str:
ways = sorted(
" and ".join(f"`{predicate}`" for predicate in sorted(way))
for way in conditions
)
if len(ways) == 1:
return ways[0]
return " or ".join(f"({way})" if " and " in way else way for way in ways)
if new.conditions == ANYWHERE:
return f"it compiles without {listed(old.conditions)}"
if old.conditions == ANYWHERE:
return f"it now compiles only where {listed(new.conditions)} hold"
return (
f"it now compiles where {listed(new.conditions)} hold, "
f"not where {listed(old.conditions)} did"
)
def _renamed(
entry: Entry,
candidates: Sequence[Entry],
unmatched: Mapping[tuple[str, ...], Entry],
) -> Entry | None:
"""Returns the new entry in entry's scope whose content is most like its
own, if alike enough."""
if entry.kind not in ("test", "helper"):
return None
words = _WORDS.findall(entry.content)
best: tuple[float, Entry] | None = None
for candidate in candidates:
if candidate.key not in unmatched or candidate.kind != entry.kind:
continue
matcher = difflib.SequenceMatcher(
None, words, _WORDS.findall(candidate.content), autojunk=False
)
if matcher.quick_ratio() < RENAMED_SIMILARITY:
continue
ratio = matcher.ratio()
if ratio >= RENAMED_SIMILARITY and (best is None or ratio > best[0]):
best = (ratio, candidate)
return None if best is None else best[1]
def _change(
old: Entry | None, new: Entry | None, action: str, detail: str = ""
) -> Change:
entry = old if old is not None else new
assert entry is not None
return Change(
entry.category,
action,
entry.kind,
entry.what,
None if old is None else old.location,
None if new is None else new.location,
detail,
)
_PATH_PREFIX = re.compile(r"(?:(?<![\w#])[\w#]+ :: )+")
def _detail(old: Entry, new: Entry, moved: bool = False) -> str:
first, second = (old.moved, new.moved) if moved else (old.content, new.content)
paths = old.key[0] == "rust" and _PATH_PREFIX.sub("", first) == _PATH_PREFIX.sub(
"", second
)
if moved:
return "moved, and only the paths that it names changed" if paths else "moved"
return "only the paths that it names changed" if paths else ""
# Rust items.
def _tokens(tokens: Sequence[Token], start: int, end: int) -> str:
return _joined(tokens, range(start, end))
# The pairs of punctuation that Rust reads as one operator when nothing
# separates them, which rustfmt keeps together: `a && b` and `a & &b` differ.
_OPERATOR_PAIRS = frozenset(
{"!=", "%=", "&&", "&=", "*=", "+=", "-=", "->", "..", "/=", "::", "<<"}
| {"<=", "==", "=>", ">=", ">>", "^=", "|=", "||"}
)
def _joined(tokens: Sequence[Token], indices: Iterable[int]) -> str:
"""Joins the texts of the tokens at indices with spaces, but for the
punctuation that forms an operator with the punctuation right before it
in the source, as the second `&` of `&&` does, which joins it."""
words: list[str] = []
previous: Token | None = None
for index in indices:
token = tokens[index]
if (
previous is not None
and previous.kind == PUNCT
and token.kind == PUNCT
and previous.end == token.start
and previous.text + token.text in _OPERATOR_PAIRS
):
words[-1] += token.text
else:
words.append(token.text)
previous = token
return " ".join(words)
# Keywords after which a parenthesized group is an expression or a pattern,
# not the arguments of a call.
_EXPRESSION_KEYWORDS = frozenset(
{"box", "break", "else", "if", "in", "let", "match", "move", "mut", "ref"}
| {"return", "while", "yield"}
)
def _one_tuple(parsed: RustFile, comma: int) -> bool:
"""Whether the comma before a `)` makes its group a tuple of one element,
whose comma rustfmt never drops."""
tokens, partner = parsed.tokens, parsed.partner
opener = partner[comma + 1]
if tokens[opener].text != "(":
return False
pieces = layout.split_commas(tokens, partner, opener + 1, comma + 1)
if len(pieces) != 1:
return False
if opener == 0:
return True
before = tokens[opener - 1]
if before.kind == IDENT:
return before.text in _EXPRESSION_KEYWORDS
if (
before.kind == PUNCT
and before.text == ">"
and layout.is_token(tokens, opener - 2, PUNCT, "-", "=")
and tokens[opener - 2].end == before.start
):
# After `->` or `=>`, a group is a type or an expression, not the
# arguments of a call: `-> (u8,)` returns a tuple.
return True
return not (before.kind == PUNCT and before.text in "!>)]?")
def _statements(parsed: RustFile, opener: int) -> bool:
"""Whether the block that opener opens holds a statement: a `;` outside
its inner brackets, or nothing at all."""
tokens, partner = parsed.tokens, parsed.partner
close = partner[opener]
if close == opener + 1:
return True
index = opener + 1
while index < close:
token = tokens[index]
if token.kind == PUNCT:
if token.text == ";":
return True
if token.text in "([{":
index = partner[index] + 1
continue
index += 1
return False
def _match_arms(parsed: RustFile, keyword: int, end: int) -> int | None:
"""Returns the brace that opens the arms of the match at keyword."""
tokens, partner = parsed.tokens, parsed.partner
index = keyword + 1
while index < end:
token = tokens[index]
if token.kind == PUNCT and token.text in "([":
index = partner[index] + 1
continue
if token.kind == PUNCT and token.text == "{":
# A block may be the scrutinee, as in `match { x } { ... }`.
after = partner[index] + 1
if index == keyword + 1 and layout.is_token(tokens, after, PUNCT, "{"):
return after
return index
index += 1
return None
# The macros of the standard library whose arguments are expressions, or a
# pattern, and that accept a trailing comma, in which commas count as they do
# outside macros.
_EXPRESSION_MACROS = frozenset(
{"assert", "assert_eq", "assert_ne", "debug_assert", "debug_assert_eq"}
| {"debug_assert_ne", "dbg", "eprint", "eprintln", "format", "format_args"}
| {"matches", "panic", "print", "println", "todo", "unimplemented"}
| {"unreachable", "vec", "write", "writeln"}
)
def _opaque_trees(parsed: RustFile, start: int, end: int) -> list[int]:
"""Returns the openers of the token trees from start to end that macros
read as they choose: those of the invocations of the macros but those of
_EXPRESSION_MACROS, and of the macro_rules! definitions."""
tokens, partner = parsed.tokens, parsed.partner
trees: list[int] = []
for index in range(max(start, 1), end):
before = tokens[index - 1]
if (
not layout.is_token(tokens, index, PUNCT, "!")
or before.kind != IDENT
or before.text in _EXPRESSION_KEYWORDS
or before.text in _EXPRESSION_MACROS
):
continue
opener = index + 1
if before.text == "macro_rules" and opener < end:
opener += 1
if (
opener < end
and layout.is_token(tokens, opener, PUNCT, "(", "[", "{")
and partner[opener] < end
):
trees.append(opener)
return trees
def _formatting(parsed: RustFile, start: int, end: int) -> set[int]:
"""Returns the tokens from start to end whose presence rustfmt chooses by
the width that the code has: the commas between the arms of a match, the
braces of a match arm's or closure's body that holds one expression, and
the comma before a closing bracket. In the token tree of
a macro, which rustfmt leaves as it finds it but for its expressions'
match arms and blocks, and whose commas may choose the macro's rule, only
the commas between the arms of a match and the braces of their bodies and
of closures' bodies count as formatting, unless the macro is one of the
standard library's that take expressions and a trailing comma."""
tokens, partner = parsed.tokens, parsed.partner
opaque: set[int] = set()
for opener in _opaque_trees(parsed, start, end):
opaque.update(range(opener + 1, partner[opener]))
arms_of_matches: set[int] = set()
skipped: set[int] = set()
for index in range(start, end):
token = tokens[index]
if token.kind == IDENT and token.text == "match":
arms = _match_arms(parsed, index, end)
if arms is None:
continue
arms_of_matches.add(arms)
position = arms + 1
while position < partner[arms]:
if layout.is_token(tokens, position, PUNCT, "(", "[", "{"):
position = partner[position] + 1
continue
if layout.is_token(tokens, position, PUNCT, ","):
skipped.add(position)
position += 1
elif token.kind == PUNCT and token.text == "{" and index > 0:
arm = index >= 2 and (tokens[index - 2].text, tokens[index - 1].text) == (
"=",
">",
)
if arm and index in opaque:
# In a macro, `=>` may be the macro's own, as in its rules.
arm = _innermost(parsed, start, index) in arms_of_matches
closure = _closure_body(parsed, index, start)
if (arm or closure) and not _statements(parsed, index):
skipped.update((index, partner[index]))
elif token.kind == PUNCT and token.text == "," and index not in opaque:
closer = layout.is_token(tokens, index + 1, PUNCT, ")", "]", "}")
one_tuple = layout.is_token(tokens, index + 1, PUNCT, ")") and _one_tuple(
parsed, index
)
if closer and not one_tuple:
skipped.add(index)
return skipped
def _closure_body(parsed: RustFile, brace: int, start: int) -> bool:
"""Whether the brace at index brace opens the body of a closure, right
after the `|` that ends its parameters, rather than a block that follows
an operator `|`, as in `a | { b }`: the `|` that starts the parameters,
after start, starts an operand."""
tokens, partner = parsed.tokens, parsed.partner
if not layout.is_token(tokens, brace - 1, PUNCT, "|"):
return False
index = brace - 2
while index >= start:
token = tokens[index]
if token.kind == PUNCT and token.text in ")]}":
index = partner[index] - 1
continue
if token.kind == PUNCT and token.text in "([{;":
return False
if token.kind == PUNCT and token.text == "|":
return _operand(tokens, index, start)
index -= 1
return False
def _innermost(parsed: RustFile, start: int, index: int) -> int | None:
"""Returns the opener of the innermost bracket group from start that
holds index."""
tokens, partner = parsed.tokens, parsed.partner
found: int | None = None
position = start
while position < index:
if layout.is_token(tokens, position, PUNCT, "(", "[", "{"):
if partner[position] > index:
found = position
position += 1
continue
position = partner[position] + 1
continue
position += 1
return found
def _render(parsed: RustFile, start: int, end: int) -> str:
"""Renders tokens as they count for a change: without those whose presence
rustfmt chooses by the width that the code has, so that code that moves to
another indentation renders the same."""
skipped = _formatting(parsed, start, end)
return _joined(
parsed.tokens, (index for index in range(start, end) if index not in skipped)
)
_INCLUDE = re.compile(r'\b(include_str|include_bytes|include) ! \( "([^"\\]*)" \)')
def _resolve_includes(content: str, path: str) -> str:
"""Names the file of each include_str!, include_bytes!, or include! from
the repository's root rather than from the file that includes it, so that
the include stays the same when its file moves."""
def resolve(match: re.Match[str]) -> str:
relative = match.group(2)
resolved = posixpath.normpath(posixpath.join(posixpath.dirname(path), relative))
return f'{match.group(1)} ! ( "/{resolved}" )'
return _INCLUDE.sub(resolve, content)
def _after_visibility(parsed: RustFile, index: int) -> int:
if layout.is_token(parsed.tokens, index, IDENT, "pub"):
index += 1
if layout.is_token(parsed.tokens, index, PUNCT, "("):
index = parsed.partner[index] + 1
return index
def _render_cfg(cfg: layout.Cfg) -> str | None:
if cfg.operator == "option":
return cfg.name if cfg.value is None else f"{cfg.name} = {cfg.value}"
if cfg.operator in ("all", "any", "not"):
operands = [_render_cfg(operand) for operand in cfg.operands]
if any(operand is None for operand in operands):
return None
return f"{cfg.operator} ( {' , '.join(cast(list[str], operands))} )"
return None
def _cfg_text(cfg: layout.Cfg) -> str:
"""Renders a predicate, with the tokens of what does not parse."""
if cfg.operator in ("all", "any", "not"):
operands = " , ".join(_cfg_text(operand) for operand in cfg.operands)
return f"{cfg.operator} ( {operands} )" if operands else f"{cfg.operator} ( )"
return _render_cfg(cfg) or " ".join(cfg.words)
def _conjuncts(
parsed: RustFile, attributes: Iterable[layout.Attribute]
) -> frozenset[str]:
"""Returns the predicates that the cfg attributes among attributes all
require: the operands of an `all`, whose own operands an `all` among them
extends, and any other predicate, each rendered; and for a cfg that
cfg_attr applies where P holds, which nested cfg_attrs extend, `any(not(P),
X)`, where X is what the cfg requires."""
tokens, partner = parsed.tokens, parsed.partner
found: set[str] = set()
def add(cfg: layout.Cfg) -> None:
if cfg.operator == "all":
for operand in cfg.operands:
add(operand)
return
found.add(_cfg_text(cfg))
def conditional(start: int, end: int, held: tuple[layout.Cfg, ...]) -> None:
"""Adds what the cfg attributes that the cfg_attr from start to end
applies require where held holds too."""
pieces = layout.split_commas(tokens, partner, start, end)
if not pieces:
return
held = (*held, layout.parse_cfg(tokens, partner, *pieces[0]))
where = held[0] if len(held) == 1 else layout.Cfg("all", operands=held)
for begin, finish in pieces[1:]:
if finish - begin < 3 or not layout.is_token(tokens, begin + 1, PUNCT, "("):
continue
inner = (begin + 2, partner[begin + 1])
if layout.is_token(tokens, begin, IDENT, "cfg"):
required = _cfg_text(layout.parse_cfg(tokens, partner, *inner))
found.add(f"any ( not ( {_cfg_text(where)} ) , {required} )")
elif layout.is_token(tokens, begin, IDENT, "cfg_attr"):
conditional(*inner, held)
for attribute in attributes:
if attribute.arguments is None:
continue
if attribute.path == "cfg":
add(layout.parse_cfg(tokens, partner, *attribute.arguments))
elif attribute.path == "cfg_attr":
conditional(*attribute.arguments, ())
return frozenset(found)
def _assume_test(cfg: layout.Cfg) -> layout.Cfg | None:
"""Returns what a predicate requires besides `test`, or None if nothing."""
if cfg.operator == "option" and cfg.name == "test" and cfg.value is None:
return None
if cfg.operator == "all":
rest = [
residue
for residue in (_assume_test(operand) for operand in cfg.operands)
if residue is not None
]
if not rest:
return None
return rest[0] if len(rest) == 1 else layout.Cfg("all", operands=tuple(rest))
return cfg
def _attribute_text(parsed: RustFile, attribute: layout.Attribute, moved: bool) -> str:
"""Renders an attribute as it counts for a change: nothing for a lint
attribute, and for moved content, a cfg without its `test`."""
tokens, partner = parsed.tokens, parsed.partner
paths = layout.attribute_paths(tokens, partner, attribute)
if paths[0] in LINT_ATTRIBUTES or (
paths[0] == "cfg_attr" and all(path in LINT_ATTRIBUTES for path in paths[1:])
):
return ""
if moved and attribute.path == "cfg" and attribute.arguments is not None:
cfg = layout.parse_cfg(tokens, partner, *attribute.arguments)
if layout.requires_test(cfg):
residue = _assume_test(cfg)
if residue is None:
return ""
rendered = _render_cfg(residue)
if rendered is not None:
return f"# [ cfg ( {rendered} ) ]"
return _tokens(tokens, attribute.start, attribute.end + 1)
def _item_text(
parsed: RustFile, item: Item, moved: bool, stop: int | None = None
) -> str:
parts = [_attribute_text(parsed, attribute, moved) for attribute in item.attributes]
start = _after_visibility(parsed, item.head)
parts.append(_render(parsed, start, item.end if stop is None else stop))
return " ".join(part for part in parts if part)
def _inner_text(parsed: RustFile, attributes: Iterable[layout.Attribute]) -> str:
return " ".join(
text
for text in (
_attribute_text(parsed, attribute, False) for attribute in attributes
)
if text
)
def _use_paths(parsed: RustFile, item: Item) -> list[str]:
"""Expands a `use` item into the paths that it imports."""
tokens, partner = parsed.tokens, parsed.partner
start = _after_visibility(parsed, item.head) + 1
end = (
item.end - 1 if layout.is_token(tokens, item.end - 1, PUNCT, ";") else item.end
)
def tree(first: int, last: int, prefix: Sequence[str]) -> list[str]:
parts = list(prefix)
index = first
while index < last:
token = tokens[index]
if token.kind == PUNCT and token.text == "{":
found: list[str] = []
for begin, finish in layout.split_commas(
tokens, partner, index + 1, partner[index]
):
found.extend(tree(begin, finish, parts))
return found
if token.kind == PUNCT and token.text == "*":
return ["::".join([*parts, "*"])]
if token.kind == IDENT and token.text == "as" and index + 1 < last:
return ["::".join(parts) + " as " + tokens[index + 1].text]
if token.kind == IDENT:
parts.append(layout.unraw(token.text))
index += 1
if parts and parts[-1] == "self":
parts.pop()
return ["::".join(parts)]
return tree(start, end, ())
_BLOCK_STARTS = frozenset(
{"async", "const", "enum", "fn", "for", "if", "impl", "loop", "match", "mod"}
| {"static", "struct", "trait", "type", "unsafe", "use", "while"}
)
def _context(parsed: RustFile, item: Item, limit: int) -> str:
"""Returns what the bracket group of item that closes at limit holds:
"statements", those of a block; "types", the fields or variants of a type
or the parameters of a function; or "expressions", such as match arms or
the fields of a struct expression."""
tokens, partner = parsed.tokens, parsed.partner
if limit >= item.end or not layout.is_token(tokens, limit, PUNCT, ")", "]", "}"):
return "expressions"
opener = partner[limit]
if tokens[opener].text == "{" and _statements(parsed, opener):
return "statements"
if item.kind in ("struct", "union", "enum"):
return "types"
if item.kind == "fn" and (item.body is None or opener < item.body[0]):
return "types"
return "expressions"
# The keywords after which an operand starts.
_OPERAND_KEYWORDS = frozenset({"break", "in", "move", "return", "yield"})
def _operand(tokens: Sequence[Token], index: int, first: int) -> bool:
"""Whether the token at index starts an operand, as the `|` of a closure
or the `<` of a qualified path do, rather than following one, as a binary
operator does."""
if index == first:
return True
before = tokens[index - 1]
if before.kind == IDENT:
return before.text in _OPERAND_KEYWORDS
if before.kind != PUNCT:
return False
if before.text == ">":
return layout.is_token(tokens, index - 2, PUNCT, "=")
return before.text in "([{,=:;"
# The constructs whose condition, scrutinee, or iterator precedes their body,
# and the keywords after which a `{` opens a block operand, not a body.
_CONDITIONS = frozenset({"for", "if", "match", "while"})
_CONDITION_KEYWORDS = frozenset(
{"break", "if", "in", "let", "match", "return", "while", "yield"}
)
def _ends_operand(tokens: Sequence[Token], index: int) -> bool:
"""Whether the token before index ends an operand, as an identifier, a
literal, or a closing bracket does, so that the `{` at index ends a
condition and opens the body after it."""
if index == 0:
return False
before = tokens[index - 1]
if before.kind == LITERAL:
return True
if before.kind == IDENT:
return before.text not in _CONDITION_KEYWORDS
return before.kind == PUNCT and before.text in ")]}?"
def _lone_equals(tokens: Sequence[Token], index: int) -> bool:
"""Whether the `=` at index stands alone, as that of a `let` does, rather
than in an operator such as `==`, `<=`, `=>`, or `..=`."""
equals = tokens[index]
before = tokens[index - 1] if index > 0 else None
after = tokens[index + 1] if index + 1 < len(tokens) else None
joined_before = (
before is not None
and before.kind == PUNCT
and before.end == equals.start
and before.text in "=!<>.+-*/%^&|"
)
joined_after = (
after is not None
and after.kind == PUNCT
and equals.end == after.start
and after.text in "=>"
)
return not (joined_before or joined_after)
def _construct_end(
parsed: RustFile, start: int, limit: int, context: str = "expressions"
) -> int:
"""Returns the index after the field, variant, statement, match arm, or
expression that starts at start, after its attributes, within limit, in a
group of the context that _context names. A `;` ends it, and so does a
`,`, but for one in a block of statements, which only generic arguments
and closures' parameters hold, and one in the generic arguments of a type,
a turbofish, or a qualified path, or in a closure's parameters."""
tokens, partner = parsed.tokens, parsed.partner
index = start
while index < limit:
attribute = layout.attribute_at(tokens, partner, index)
if attribute is None:
break
index = attribute.end + 1
first = index
first_text = tokens[first].text if first < limit else ""
conditional = first_text in _CONDITIONS
def scan(generics: bool) -> tuple[int, bool]:
"""Returns the end, and whether a `<` that it took to open generic
arguments stayed open."""
index = first
angles = 0
# Whether a pattern runs at index, from `let` to its `=` or from `for`
# to `in`, whose braces open no body.
pattern = first_text == "for"
while index < limit:
token = tokens[index]
if token.kind == IDENT and conditional:
if token.text == "let":
pattern = True
elif token.text == "in" and first_text == "for":
pattern = False
if token.kind != PUNCT:
index += 1
continue
text = token.text
if pattern and text == "=" and _lone_equals(tokens, index):
pattern = False
if text == ";" or (text == "," and not angles and context != "statements"):
return index + 1, False
if text in ")]}":
return index, angles > 0
if text in "([":
index = partner[index] + 1
continue
if text == "{":
close = partner[index]
after = close + 1
if angles or (
conditional and (pattern or not _ends_operand(tokens, index))
):
# The braces of a const argument, as in `S<{ 1 }>`, of a
# pattern, or of a block in a condition, as in
# `if let Some(value) = { take() } { ... }`.
index = after
continue
if layout.is_token(tokens, after, IDENT, "else"):
index = after + 1
continue
arm = (
index >= 2
and tokens[index - 1].text == ">"
and tokens[index - 2].text == "="
)
invocation = index >= 1 and tokens[index - 1].text == "!"
if (
arm
or invocation
or first_text in _BLOCK_STARTS
or first_text == "{"
):
if layout.is_token(tokens, after, PUNCT, ";", ","):
return after + 1, False
return after, False