Repository navigation
Expand file tree
/
Copy pathfind_new_issue_2.py
More file actions
997 lines (837 loc) · 31.8 KB
/
Copy pathfind_new_issue_2.py
File metadata and controls
997 lines (837 loc) · 31.8 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
from __future__ import annotations
import argparse
import hashlib
import json
import random
import sys
import tempfile
from contextlib import redirect_stderr, redirect_stdout
from dataclasses import dataclass
from enum import Enum
from io import StringIO
from pathlib import Path
from typing import Protocol
from matchify.assumptions import Assumptions
from matchify.cli import convert_file
SAMPLES_DIR = Path("tests/samples")
CLASS_NAMES = ("Point", "Token", "Node")
ATTR_NAMES = ("x", "y", "kind", "items")
LITERALS = ("-1", "0", "1", "2", "'red'", "'ready'")
SINGLETONS = ("None", "True", "False")
class IfStyle(Enum):
CANONICAL = "canonical"
MEMBERSHIP = "membership"
TYPE_NONE = "type-none"
PAREN_CLASSINFO = "paren-classinfo"
RAW_GUARDS = "raw-guards"
MIXED = "mixed"
@dataclass(frozen=True)
class RenderContext:
rng: random.Random
style: IfStyle
def choose_style(self, *styles: IfStyle) -> bool:
return self.style in styles or (
self.style is IfStyle.MIXED and self.rng.choice([True, False])
)
class Pattern(Protocol):
def render_match(self) -> str: ...
def render_if_conditions(
self, subject: str, context: RenderContext
) -> list[str]: ...
def render_if(self, subject: str, context: RenderContext) -> str: ...
def matching_value(self) -> str: ...
def nonmatching_value(self) -> str: ...
def capture_names(self) -> tuple[str, ...]: ...
def if_capture_assignments(self, subject: str) -> tuple[str, ...]: ...
def render_condition_expr(conditions: list[str]) -> str:
return " and ".join(conditions) or "True"
@dataclass(frozen=True)
class LiteralPattern:
value: str
def render_match(self) -> str:
return self.value
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
return [f"{subject} == {self.value}"]
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return self.value
def nonmatching_value(self) -> str:
return "'miss'" if self.value.startswith("'") else "99"
def capture_names(self) -> tuple[str, ...]:
return ()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return ()
@dataclass(frozen=True)
class SingletonPattern:
value: str
def render_match(self) -> str:
return self.value
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
return [f"{subject} is {self.value}"]
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return self.value
def nonmatching_value(self) -> str:
return "object()"
def capture_names(self) -> tuple[str, ...]:
return ()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return ()
@dataclass(frozen=True)
class CapturePattern:
name: str
def render_match(self) -> str:
return self.name
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
return []
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return "42"
def nonmatching_value(self) -> str:
return "42"
def capture_names(self) -> tuple[str, ...]:
return (self.name,)
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return (f"{self.name} = {subject}",)
@dataclass(frozen=True)
class WildcardPattern:
def render_match(self) -> str:
return "_"
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
return []
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return "object()"
def nonmatching_value(self) -> str:
return "object()"
def capture_names(self) -> tuple[str, ...]:
return ()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return ()
@dataclass(frozen=True)
class OrPattern:
alternatives: tuple[Pattern, ...]
def render_match(self) -> str:
return " | ".join(pattern.render_match() for pattern in self.alternatives)
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
return [self.render_if(subject, context)]
def render_if(self, subject: str, context: RenderContext) -> str:
if (
context.choose_style(IfStyle.MEMBERSHIP)
and self._all_literal_alternatives()
and not self.capture_names()
):
values = ", ".join(
pattern.value # type: ignore[attr-defined]
for pattern in self.alternatives
)
return f"{subject} in ({values},)"
return (
"("
+ " or ".join(
render_condition_expr(pattern.render_if_conditions(subject, context))
for pattern in self.alternatives
)
+ ")"
)
def matching_value(self) -> str:
return self.alternatives[0].matching_value()
def nonmatching_value(self) -> str:
return self.alternatives[0].nonmatching_value()
def capture_names(self) -> tuple[str, ...]:
names = self.alternatives[0].capture_names()
if all(pattern.capture_names() == names for pattern in self.alternatives[1:]):
return names
return ()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
if not self.capture_names():
return ()
return self.alternatives[0].if_capture_assignments(subject)
def _all_literal_alternatives(self) -> bool:
return all(isinstance(pattern, LiteralPattern) for pattern in self.alternatives)
@dataclass(frozen=True)
class ClassPattern:
class_name: str
attrs: tuple[tuple[str, Pattern], ...] = ()
def render_match(self) -> str:
if not self.attrs:
return f"{self.class_name}()"
args = ", ".join(
f"{name}={pattern.render_match()}" for name, pattern in self.attrs
)
return f"{self.class_name}({args})"
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
parts = [f"isinstance({subject}, {self._classinfo(context)})"]
for attr, pattern in self.attrs:
parts.append(f"hasattr({subject}, {attr!r})")
parts.extend(pattern.render_if_conditions(f"{subject}.{attr}", context))
return parts
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
if not self.attrs:
return f"{self.class_name}()"
args = ", ".join(
f"{name}={pattern.matching_value()}" for name, pattern in self.attrs
)
return f"{self.class_name}({args})"
def nonmatching_value(self) -> str:
if not self.attrs:
return "object()"
attr, pattern = self.attrs[0]
args = [f"{attr}={pattern.nonmatching_value()}"]
args.extend(
f"{name}={other.matching_value()}" for name, other in self.attrs[1:]
)
return f"{self.class_name}({', '.join(args)})"
def capture_names(self) -> tuple[str, ...]:
return tuple(
name for _, pattern in self.attrs for name in pattern.capture_names()
)
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return tuple(
assignment
for attr, pattern in self.attrs
for assignment in pattern.if_capture_assignments(f"{subject}.{attr}")
)
def _classinfo(self, context: RenderContext) -> str:
if self.class_name == "NoneType" or context.choose_style(IfStyle.TYPE_NONE):
if self.class_name == "NoneType":
return "type(None)"
if context.choose_style(IfStyle.PAREN_CLASSINFO):
return f"({self.class_name})"
return self.class_name
@dataclass(frozen=True)
class NoneTypeOrClassPattern:
class_name: str
def render_match(self) -> str:
return f"None | {self.class_name}()"
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
if context.choose_style(IfStyle.TYPE_NONE):
return [f"isinstance({subject}, (type(None), {self.class_name}))"]
return [f"({subject} is None or isinstance({subject}, {self.class_name}))"]
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return "None"
def nonmatching_value(self) -> str:
return "object()"
def capture_names(self) -> tuple[str, ...]:
return ()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return ()
@dataclass(frozen=True)
class SequencePattern:
elements: tuple[Pattern, ...]
star: bool = False
tuple_value: bool = False
def render_match(self) -> str:
parts = [pattern.render_match() for pattern in self.elements]
if self.star:
parts.append("*_")
return "[" + ", ".join(parts) + "]"
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
op = ">=" if self.star else "=="
parts = [
f"isinstance({subject}, (list, tuple))",
f"len({subject}) {op} {len(self.elements)}",
]
for index, pattern in enumerate(self.elements):
parts.extend(pattern.render_if_conditions(f"{subject}[{index}]", context))
return parts
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
values = [pattern.matching_value() for pattern in self.elements]
if self.star:
values.append("object()")
return render_sequence_value(values, self.tuple_value)
def nonmatching_value(self) -> str:
if not self.elements:
return "object()"
values = [self.elements[0].nonmatching_value()]
values.extend(pattern.matching_value() for pattern in self.elements[1:])
return render_sequence_value(values, self.tuple_value)
def capture_names(self) -> tuple[str, ...]:
return tuple(
name for pattern in self.elements for name in pattern.capture_names()
)
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return tuple(
assignment
for index, pattern in enumerate(self.elements)
for assignment in pattern.if_capture_assignments(f"{subject}[{index}]")
)
@dataclass(frozen=True)
class GuardedPattern:
pattern: Pattern
guard: str
def render_match(self) -> str:
return self.pattern.render_match()
def render_guard(self, subject: str) -> str:
return self.guard.format(subject=subject)
def render_if_conditions(self, subject: str, context: RenderContext) -> list[str]:
conditions = self.pattern.render_if_conditions(subject, context)
guard = self.render_guard(subject)
if guard != "True":
conditions.append(guard)
return conditions
def render_if(self, subject: str, context: RenderContext) -> str:
return render_condition_expr(self.render_if_conditions(subject, context))
def matching_value(self) -> str:
return self.pattern.matching_value()
def nonmatching_value(self) -> str:
return self.pattern.nonmatching_value()
def capture_names(self) -> tuple[str, ...]:
return self.pattern.capture_names()
def if_capture_assignments(self, subject: str) -> tuple[str, ...]:
return self.pattern.if_capture_assignments(subject)
@dataclass(frozen=True)
class Case:
pattern: Pattern
body: str
@dataclass(frozen=True)
class Program:
classes: tuple[str, ...]
subject: str
cases: tuple[Case, ...]
default_body: str | None
sample_values: tuple[str, ...]
def class_defs_code(self) -> str:
return "\n".join(
f"class {class_name}:\n"
" def __init__(self, **attrs):\n"
" self.__dict__.update(attrs)\n"
for class_name in self.classes
)
def setup_code(self) -> str:
return (
f"{self.class_defs_code()}"
"def stable_repr(value):\n"
" if type(value) is object:\n"
" return 'object()'\n"
" if hasattr(value, '__dict__'):\n"
" attrs = ', '.join(\n"
" f'{name}={stable_repr(attr)}'\n"
" for name, attr in sorted(value.__dict__.items())\n"
" )\n"
" return f'{type(value).__name__}({attrs})'\n"
" if isinstance(value, list):\n"
" return '[' + ', '.join(stable_repr(item) for item in value) + ']'\n"
" if isinstance(value, tuple):\n"
" inner = ', '.join(stable_repr(item) for item in value)\n"
" return f'({inner},)' if len(value) == 1 else f'({inner})'\n"
" return repr(value)\n"
f"values = [\n{self._value_lines()}\n]\n"
)
def render_if_code(self, style: IfStyle, seed: int) -> str:
context = RenderContext(random.Random(seed), style)
branch_blocks = []
for index, case in enumerate(self.cases):
keyword = "if" if index == 0 else "elif"
condition = case.pattern.render_if(self.subject, context)
body = indent_code(
render_body(case, self.subject, include_captures=True), " "
)
branch_blocks.append(f" {keyword} {condition}:\n{body}")
if self.default_body is not None:
branch_blocks.append(f" else:\n print({self.default_body!r})")
return (
self.setup_code()
+ "for value in values:\n"
+ "\n".join(branch_blocks)
+ "\n"
)
def render_match_code(self) -> str:
case_blocks = []
for case in self.cases:
pattern = case.pattern
guard = ""
if isinstance(pattern, GuardedPattern):
guard = f" if {pattern.render_guard(self.subject)}"
body = indent_code(
render_body(case, self.subject, include_captures=False), " "
)
case_blocks.append(f" case {pattern.render_match()}{guard}:\n{body}")
if self.default_body is not None:
case_blocks.append(
f" case _:\n print({self.default_body!r})"
)
return (
self.setup_code()
+ "for value in values:\n"
+ f" match {self.subject}:\n"
+ "\n".join(case_blocks)
+ "\n"
)
def _value_lines(self) -> str:
return "\n".join(f" {value}," for value in self.sample_values)
@dataclass(frozen=True)
class Issue:
kind: str
seed: int
index: int
style: str
original: str
converted: str
match_reference: str
expected_trace: tuple[str, str, type[BaseException] | None]
actual_trace: tuple[str, str, type[BaseException] | None]
changed: bool
error: str | None = None
def trace_text(self) -> str:
return format_trace(self.expected_trace)
def render_body(case: Case, subject: str, *, include_captures: bool) -> str:
names = case.pattern.capture_names()
capture_lines = (
list(case.pattern.if_capture_assignments(subject)) if include_captures else []
)
if names:
values = ", ".join(f"stable_repr({name})" for name in names)
print_line = f"print({case.body!r}, {values})"
else:
print_line = f"print({case.body!r})"
return "\n".join([*capture_lines, print_line])
def render_sequence_value(values: list[str], tuple_value: bool) -> str:
if not tuple_value:
return "[" + ", ".join(values) + "]"
if len(values) == 1:
return f"({values[0]},)"
return "(" + ", ".join(values) + ")"
def indent_code(code: str, prefix: str) -> str:
return "\n".join(f"{prefix}{line}" if line else line for line in code.splitlines())
def execute_result(source: str) -> tuple[str, str, type[BaseException] | None]:
stdout = StringIO()
stderr = StringIO()
exception_type = None
namespace: dict[str, object] = {}
try:
with redirect_stdout(stdout), redirect_stderr(stderr):
exec(source, namespace)
except BaseException as error:
exception_type = type(error)
return (
str(namespace.get("result")),
stdout.getvalue() + stderr.getvalue(),
exception_type,
)
def exception_name(exception_type: type[BaseException] | None) -> str:
return "None" if exception_type is None else exception_type.__name__
def format_trace(trace: tuple[str, str, type[BaseException] | None]) -> str:
return "\n".join(
[
f"result: {trace[0]}",
f"output: {trace[1]!r}",
f"exception: {exception_name(trace[2])}",
"",
]
)
def generate_program(rng: random.Random) -> Program:
class_count = rng.randint(1, len(CLASS_NAMES))
classes = CLASS_NAMES[:class_count]
case_count = rng.randint(2, 5)
cases = tuple(
Case(
generate_pattern(
rng,
classes,
depth=4,
capture_prefix=f"capture_{index}",
allow_guard=True,
allow_irrefutable=False,
),
f"branch_{index}",
)
for index in range(case_count)
)
sample_values = []
for case in cases:
sample_values.append(case.pattern.matching_value())
sample_values.append(case.pattern.nonmatching_value())
sample_values.append("object()")
default_body = "default" if rng.choice([True, False]) else None
return Program(classes, "value", cases, default_body, tuple(sample_values))
def generate_pattern(
rng: random.Random,
classes: tuple[str, ...],
*,
depth: int,
capture_prefix: str,
allow_guard: bool,
allow_irrefutable: bool,
) -> Pattern:
if depth <= 0:
return generate_leaf_pattern(
rng, capture_prefix, allow_irrefutable=allow_irrefutable
)
choices = ["literal", "singleton", "class", "sequence", "or", "capture"]
if not allow_irrefutable:
choices.remove("capture")
if allow_guard:
choices.append("guard")
if len(classes) > 1:
choices.append("none-or-class")
kind = rng.choice(choices)
if kind == "literal":
return LiteralPattern(rng.choice(LITERALS))
if kind == "singleton":
return SingletonPattern(rng.choice(SINGLETONS))
if kind == "capture":
return CapturePattern(capture_prefix)
if kind == "none-or-class":
return NoneTypeOrClassPattern(rng.choice(classes))
if kind == "class":
return generate_class_pattern(
rng, classes, depth=depth, capture_prefix=capture_prefix
)
if kind == "sequence":
return generate_sequence_pattern(
rng, classes, depth=depth, capture_prefix=capture_prefix
)
if kind == "or":
return generate_or_pattern(
rng, classes, depth=depth, capture_prefix=capture_prefix
)
return GuardedPattern(
generate_pattern(
rng,
classes,
depth=depth - 1,
capture_prefix=capture_prefix,
allow_guard=False,
allow_irrefutable=False,
),
rng.choice(
(
"True",
"not False",
"hasattr({subject}, '__class__')",
"not isinstance({subject}, dict)",
)
),
)
def generate_leaf_pattern(
rng: random.Random, capture_prefix: str, *, allow_irrefutable: bool
) -> Pattern:
kind = rng.choice(["literal", "singleton", "capture", "wildcard"])
if not allow_irrefutable and kind in {"capture", "wildcard"}:
kind = rng.choice(["literal", "singleton"])
if kind == "literal":
return LiteralPattern(rng.choice(LITERALS))
if kind == "singleton":
return SingletonPattern(rng.choice(SINGLETONS))
if kind == "capture":
return CapturePattern(capture_prefix)
return WildcardPattern()
def generate_class_pattern(
rng: random.Random, classes: tuple[str, ...], *, depth: int, capture_prefix: str
) -> ClassPattern:
attrs = tuple(
(
attr,
generate_pattern(
rng,
classes,
depth=depth - 1,
capture_prefix=f"{capture_prefix}_{attr}",
allow_guard=False,
allow_irrefutable=True,
),
)
for attr in rng.sample(ATTR_NAMES, rng.randint(0, 2))
)
return ClassPattern(rng.choice(classes), attrs)
def generate_sequence_pattern(
rng: random.Random, classes: tuple[str, ...], *, depth: int, capture_prefix: str
) -> SequencePattern:
length = rng.randint(1, 3)
elements = tuple(
generate_pattern(
rng,
classes,
depth=depth - 1,
capture_prefix=f"{capture_prefix}_{index}",
allow_guard=False,
allow_irrefutable=True,
)
for index in range(length)
)
return SequencePattern(
elements,
star=rng.choice([True, False]),
tuple_value=rng.choice([True, False]),
)
def generate_or_pattern(
rng: random.Random, classes: tuple[str, ...], *, depth: int, capture_prefix: str
) -> OrPattern:
if rng.choice([True, False]):
alternatives: tuple[Pattern, ...] = tuple(
LiteralPattern(value) for value in rng.sample(LITERALS, rng.randint(2, 4))
)
return OrPattern(alternatives)
alternatives = tuple(
generate_pattern(
rng,
classes,
depth=depth - 1,
capture_prefix=capture_prefix,
allow_guard=False,
allow_irrefutable=False,
)
for _ in range(rng.randint(2, 3))
)
# Python OR patterns require the same capture names in every alternative.
if len({pattern.capture_names() for pattern in alternatives}) > 1:
return OrPattern(
tuple(LiteralPattern(value) for value in rng.sample(LITERALS, 2))
)
return OrPattern(alternatives)
def check_program(program: Program, style: IfStyle, *, seed: int) -> Issue | None:
original = program.render_if_code(style, seed)
match_reference = program.render_match_code()
expected_trace = execute_result(match_reference)
original_trace = execute_result(original)
if original_trace != expected_trace:
return Issue(
kind="generator-bug",
seed=-1,
index=-1,
style=style.value,
original=original,
converted=original,
match_reference=match_reference,
expected_trace=expected_trace,
actual_trace=original_trace,
changed=False,
error="if renderer does not match match renderer",
)
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "candidate.py"
path.write_text(original, encoding="utf-8")
converted_path, changed, error = convert_file(
path,
assumptions=Assumptions.from_names(),
)
converted = path.read_text(encoding="utf-8") if path.exists() else ""
if converted_path != path:
return Issue(
kind="wrong-path",
seed=-1,
index=-1,
style=style.value,
original=original,
converted=converted,
match_reference=match_reference,
expected_trace=expected_trace,
actual_trace=("", "", None),
changed=changed,
error=f"converted_path={converted_path}",
)
if error is not None:
return Issue(
kind="convert-error",
seed=-1,
index=-1,
style=style.value,
original=original,
converted=converted,
match_reference=match_reference,
expected_trace=expected_trace,
actual_trace=("", "", None),
changed=changed,
error=error,
)
if not changed:
return Issue(
kind="not-converted",
seed=-1,
index=-1,
style=style.value,
original=original,
converted=converted,
match_reference=match_reference,
expected_trace=expected_trace,
actual_trace=original_trace,
changed=False,
)
actual_trace = execute_result(converted)
if actual_trace != expected_trace:
return Issue(
kind="trace-mismatch",
seed=-1,
index=-1,
style=style.value,
original=original,
converted=converted,
match_reference=match_reference,
expected_trace=expected_trace,
actual_trace=actual_trace,
changed=changed,
)
return None
def issue_survives(source: str, style: IfStyle) -> bool:
# Minimization only has original.py, so classify against itself by checking whether
# Matchify still has a conversion problem. This intentionally skips not-converted
# enhancement samples because they need the match reference for classification.
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "candidate.py"
path.write_text(source, encoding="utf-8")
expected_trace = execute_result(source)
_, changed, error = convert_file(path)
converted = path.read_text(encoding="utf-8")
if error is not None:
return True
return changed and execute_result(converted) != expected_trace
def minimize_source(source: str, *, enabled: bool, style: IfStyle) -> str:
if not enabled:
return source
try:
from pysource_minimize import minimize
except ImportError as error:
raise RuntimeError(
"pysource-minimize is required. Install it or rerun with --no-minimize."
) from error
return minimize(source, lambda candidate: issue_survives(candidate, style))
def make_sample_id(issue: Issue) -> str:
digest = hashlib.sha256(issue.original.encode("utf-8")).hexdigest()[:12]
return f"{issue.kind}-{issue.style}-seed-{issue.seed}-case-{issue.index}-{digest}"
def save_issue(issue: Issue, samples_dir: Path) -> Path:
sample_dir = samples_dir / make_sample_id(issue)
sample_dir.mkdir(parents=True, exist_ok=True)
(sample_dir / "original.py").write_text(issue.original, encoding="utf-8")
(sample_dir / "converted.py").write_text(issue.converted, encoding="utf-8")
(sample_dir / "trace.txt").write_text(issue.trace_text(), encoding="utf-8")
(sample_dir / "match_reference.py").write_text(
issue.match_reference, encoding="utf-8"
)
(sample_dir / "meta.json").write_text(
json.dumps(
{
"kind": issue.kind,
"seed": issue.seed,
"index": issue.index,
"style": issue.style,
"changed": issue.changed,
"error": issue.error,
"expected": {
"output": issue.expected_trace[1],
"exception": exception_name(issue.expected_trace[2]),
},
"actual": {
"output": issue.actual_trace[1],
"exception": exception_name(issue.actual_trace[2]),
},
},
indent=2,
sort_keys=True,
)
+ "\n",
encoding="utf-8",
)
return sample_dir
def find_issues(
*,
count: int,
seed: int,
style: IfStyle,
samples_dir: Path,
minimize: bool,
stop_after: int,
include_not_converted: bool,
) -> list[Path]:
rng = random.Random(seed)
saved = []
for index in range(count):
program = generate_program(rng)
issue = check_program(program, style, seed=seed + index)
if issue is None:
continue
if issue.kind == "not-converted" and not include_not_converted:
continue
issue = Issue(
kind=issue.kind,
seed=seed,
index=index,
style=style.value,
original=issue.original,
converted=issue.converted,
match_reference=issue.match_reference,
expected_trace=issue.expected_trace,
actual_trace=issue.actual_trace,
changed=issue.changed,
error=issue.error,
)
if issue.kind in {"trace-mismatch", "convert-error"}:
minimized = minimize_source(issue.original, enabled=minimize, style=style)
if minimized != issue.original:
minimized_issue = check_minimized_issue(minimized, issue)
if minimized_issue is not None:
issue = minimized_issue
sample_dir = save_issue(issue, samples_dir)
print(f"saved {sample_dir}")
saved.append(sample_dir)
if len(saved) >= stop_after:
break
return saved
def check_minimized_issue(source: str, original_issue: Issue) -> Issue | None:
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "candidate.py"
path.write_text(source, encoding="utf-8")
expected_trace = execute_result(source)
_, changed, error = convert_file(path)
converted = path.read_text(encoding="utf-8")
if error is None and (not changed or execute_result(converted) == expected_trace):
return None
return Issue(
kind="convert-error" if error is not None else "trace-mismatch",
seed=original_issue.seed,
index=original_issue.index,
style=original_issue.style,
original=source,
converted=converted,
match_reference=source,
expected_trace=expected_trace,
actual_trace=("", "", None) if error is not None else execute_result(converted),
changed=changed,
error=error,
)
def parse_args(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Generate match-representable if/elif programs and classify Matchify gaps."
)
parser.add_argument("--count", type=int, default=1000)
parser.add_argument("--seed", type=int, default=20260625)
parser.add_argument("--samples-dir", type=Path, default=SAMPLES_DIR)
parser.add_argument("--stop-after", type=int, default=1)
parser.add_argument(
"--style",
choices=[style.value for style in IfStyle],
default=IfStyle.MIXED.value,
)
parser.add_argument(
"--include-not-converted",
action="store_true",
help="Store match-representable inputs that Matchify currently leaves unchanged.",
)
parser.add_argument("--no-minimize", action="store_true")
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = parse_args(sys.argv[1:] if argv is None else argv)
saved = find_issues(
count=args.count,
seed=args.seed,
style=IfStyle(args.style),
samples_dir=args.samples_dir,
minimize=not args.no_minimize,
stop_after=args.stop_after,
include_not_converted=args.include_not_converted,
)
if not saved:
print("no issues found")
return 0
if __name__ == "__main__":
raise SystemExit(main())