-
Notifications
You must be signed in to change notification settings - Fork 52
/
diff.py
executable file
·4027 lines (3532 loc) · 132 KB
/
diff.py
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
# PYTHON_ARGCOMPLETE_OK
import argparse
import enum
import sys
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Sequence,
Match,
NoReturn,
Optional,
Pattern,
Set,
Tuple,
Type,
Union,
)
def fail(msg: str) -> NoReturn:
print(msg, file=sys.stderr)
sys.exit(1)
def static_assert_unreachable(x: NoReturn) -> NoReturn:
raise Exception("Unreachable! " + repr(x))
# The encoding to use for reading the map file to text.
# It is expected the map file will be ASCII-only or mostly,
# which UTF-8 is compatible with.
MAPFILE_ENCODING = "UTF-8"
# In case the map file isn't UTF-8 and some bytes can't be decoded as UTF-8,
# don't error and subtitute with U+FFFD.
# (cf the Python documentation on `codecs.replace_errors`)
MAPFILE_ENCODING_ERROR_HANDLER = "replace"
class DiffMode(enum.Enum):
SINGLE = "single"
SINGLE_BASE = "single_base"
NORMAL = "normal"
THREEWAY_PREV = "3prev"
THREEWAY_BASE = "3base"
# ==== COMMAND-LINE ====
if __name__ == "__main__":
# Prefer to use diff_settings.py from the current working directory
sys.path.insert(0, ".")
try:
import diff_settings
except ModuleNotFoundError:
fail("Unable to find diff_settings.py in the same directory.")
sys.path.pop(0)
try:
import argcomplete
except ModuleNotFoundError:
argcomplete = None # type: ignore
parser = argparse.ArgumentParser(
description="Diff MIPS, PPC, AArch64, ARM32, SH2, SH4, or m68k assembly."
)
start_argument = parser.add_argument(
"start",
help="Function name or address to start diffing from.",
)
if argcomplete:
def complete_symbol(
prefix: str, parsed_args: argparse.Namespace, **kwargs: object
) -> List[str]:
if not prefix or prefix.startswith("-"):
# skip reading the map file, which would
# result in a lot of useless completions
return []
config: Dict[str, Any] = {}
diff_settings.apply(config, parsed_args) # type: ignore
mapfile = config.get("mapfile")
if not mapfile:
return []
completes = []
encoding = MAPFILE_ENCODING
# We assume the encoding is self-synchronizing,
# meaning that for example finding bytes corresponding to the space
# character, is equivalent to finding a space character.
# This is true for ASCII and UTF-8 data, for example.
# This allows processing the map file as bytes instead of entirely
# processing it as decoded text, which is slow.
space = " ".encode(encoding)
line_return = "\n".encode(encoding)
with open(mapfile, "rb") as f:
import mmap
data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
# assume symbols are prefixed by a space character
search = f" {prefix}".encode(encoding)
pos = data.find(search)
while pos != -1:
# skip the space character in the search string
pos += len(space)
# assume symbols are suffixed by either a space
# character or a (unix-style) line return
spacePos = data.find(space, pos)
lineReturnPos = data.find(line_return, pos)
if lineReturnPos == -1:
endPos = spacePos
elif spacePos == -1:
endPos = lineReturnPos
else:
endPos = min(spacePos, lineReturnPos)
if endPos == -1:
match = data[pos:]
pos = -1
else:
match = data[pos:endPos]
pos = data.find(search, endPos)
completes.append(match.decode(encoding))
return completes
setattr(start_argument, "completer", complete_symbol)
parser.add_argument(
"end",
nargs="?",
help="Address to end diff at.",
)
parser.add_argument(
"-o",
dest="diff_obj",
action="store_true",
help="""Diff .o files rather than a whole binary. This makes it possible to
see symbol names. (Recommended)""",
)
parser.add_argument(
"-f",
"--file",
dest="file",
type=str,
help="""File path for a file being diffed. When used the map
file isn't searched for the function given. Useful for dynamically
linked libraries.""",
)
parser.add_argument(
"-e",
"--elf",
dest="diff_elf_symbol",
metavar="SYMBOL",
help="""Diff a given function in two ELFs, one being stripped and the other
one non-stripped. Requires objdump from binutils 2.33+.""",
)
parser.add_argument(
"-c",
"--source",
dest="show_source",
action="store_true",
help="Show source code (if possible). Only works with -o or -e.",
)
parser.add_argument(
"-C",
"--source-old-binutils",
dest="source_old_binutils",
action="store_true",
help="""Tweak --source handling to make it work with binutils < 2.33.
Implies --source.""",
)
parser.add_argument(
"-j",
"--section",
dest="diff_section",
default=".text",
metavar="SECTION",
help="Diff restricted to a given output section.",
)
parser.add_argument(
"-L",
"--line-numbers",
dest="show_line_numbers",
action="store_const",
const=True,
help="""Show source line numbers in output, when available. May be enabled by
default depending on diff_settings.py.""",
)
parser.add_argument(
"--no-line-numbers",
dest="show_line_numbers",
action="store_const",
const=False,
help="Hide source line numbers in output.",
)
parser.add_argument(
"--inlines",
dest="inlines",
action="store_true",
help="Show inline function calls (if possible). Only works with -o or -e.",
)
parser.add_argument(
"--base-asm",
dest="base_asm",
metavar="FILE",
help="Read assembly from given file instead of configured base img.",
)
parser.add_argument(
"--write-asm",
dest="write_asm",
metavar="FILE",
help="Write the current assembly output to file, e.g. for use with --base-asm.",
)
parser.add_argument(
"-m",
"--make",
dest="make",
action="store_true",
help="Automatically run 'make' on the .o file or binary before diffing.",
)
parser.add_argument(
"-l",
"--skip-lines",
dest="skip_lines",
metavar="LINES",
type=int,
default=0,
help="Skip the first LINES lines of output.",
)
parser.add_argument(
"-s",
"--stop-at-ret",
dest="stop_at_ret",
action="count",
help="""Stop disassembling at the first return instruction.
You can also pass -ss to stop at the second return instruction, and so on.""",
)
parser.add_argument(
"-i",
"--ignore-large-imms",
dest="ignore_large_imms",
action="store_true",
help="Pretend all large enough immediates are the same.",
)
parser.add_argument(
"-I",
"--ignore-addr-diffs",
dest="ignore_addr_diffs",
action="store_true",
help="Ignore address differences. Currently only affects AArch64 and ARM32.",
)
parser.add_argument(
"-B",
"--no-show-branches",
dest="show_branches",
action="store_false",
help="Don't visualize branches/branch targets.",
)
parser.add_argument(
"-R",
"--no-show-rodata-refs",
dest="show_rodata_refs",
action="store_false",
help="Don't show .rodata -> .text references (typically from jump tables).",
)
parser.add_argument(
"-S",
"--base-shift",
dest="base_shift",
metavar="N",
type=str,
default="0",
help="""Diff position N in our img against position N + shift in the base img.
Arithmetic is allowed, so e.g. |-S "0x1234 - 0x4321"| is a reasonable
flag to pass if it is known that position 0x1234 in the base img syncs
up with position 0x4321 in our img. Not supported together with -o.""",
)
parser.add_argument(
"-w",
"--watch",
dest="watch",
action="store_true",
help="""Automatically update when source/object files change.
Recommended in combination with -m.""",
)
parser.add_argument(
"-y",
"--yes",
dest="agree",
action="store_true",
help="""Automatically agree to any yes/no questions asked.
Useful if you really want to use the -w option without -m.""",
)
parser.add_argument(
"-0",
"--diff_mode=single_base",
dest="diff_mode",
action="store_const",
const=DiffMode.SINGLE_BASE,
help="""View the base asm only (not a diff).""",
)
parser.add_argument(
"-1",
"--diff_mode=single",
dest="diff_mode",
action="store_const",
const=DiffMode.SINGLE,
help="""View the current asm only (not a diff).""",
)
parser.add_argument(
"-3",
"--threeway=prev",
dest="diff_mode",
action="store_const",
const=DiffMode.THREEWAY_PREV,
help="""Show a three-way diff between target asm, current asm, and asm
prior to -w rebuild. Requires -w.""",
)
parser.add_argument(
"-b",
"--threeway=base",
dest="diff_mode",
action="store_const",
const=DiffMode.THREEWAY_BASE,
help="""Show a three-way diff between target asm, current asm, and asm
when diff.py was started. Requires -w.""",
)
parser.add_argument(
"--width",
dest="column_width",
metavar="COLS",
type=int,
default=50,
help="Sets the width of the left and right view column.",
)
parser.add_argument(
"--algorithm",
dest="algorithm",
default="levenshtein",
choices=["levenshtein", "difflib"],
help="""Diff algorithm to use. Levenshtein gives the minimum diff, while difflib
aims for long sections of equal opcodes. Defaults to %(default)s.""",
)
parser.add_argument(
"--max-size",
"--max-lines",
metavar="LINES",
dest="max_lines",
type=int,
default=1024,
help="The maximum length of the diff, in lines.",
)
parser.add_argument(
"--no-pager",
dest="no_pager",
action="store_true",
help="""Disable the pager; write output directly to stdout, then exit.
Incompatible with --watch.""",
)
parser.add_argument(
"--format",
choices=("color", "plain", "html", "json"),
default="color",
help="Output format, default is color. --format=html or json implies --no-pager.",
)
parser.add_argument(
"-U",
"--compress-matching",
metavar="N",
dest="compress_matching",
type=int,
help="""Compress streaks of matching lines, leaving N lines of context
around non-matching parts.""",
)
parser.add_argument(
"-V",
"--compress-sameinstr",
metavar="N",
dest="compress_sameinstr",
type=int,
help="""Compress streaks of lines with same instructions (but possibly
different regalloc), leaving N lines of context around other parts.""",
)
parser.add_argument(
"-d",
"--diff-function-symbols",
dest="diff_function_symbols",
action="store_true",
help="Include and diff function symbols.",
)
# Project-specific flags, e.g. different versions/make arguments.
add_custom_arguments_fn = getattr(diff_settings, "add_custom_arguments", None)
if add_custom_arguments_fn:
add_custom_arguments_fn(parser)
if argcomplete:
argcomplete.autocomplete(parser)
# ==== IMPORTS ====
# (We do imports late to optimize auto-complete performance.)
import abc
from collections import Counter, defaultdict
from dataclasses import asdict, dataclass, field, replace
import difflib
import html
import itertools
import json
import os
import queue
import re
import string
import struct
import subprocess
import threading
import time
import traceback
MISSING_PREREQUISITES = (
"Missing prerequisite python module {}. "
"Run `python3 -m pip install --user colorama watchdog levenshtein cxxfilt` to install prerequisites (cxxfilt only needed with --source)."
)
try:
from colorama import Back, Fore, Style
import watchdog
except ModuleNotFoundError as e:
fail(MISSING_PREREQUISITES.format(e.name))
# ==== CONFIG ====
@dataclass
class ProjectSettings:
arch_str: str
objdump_executable: str
objdump_flags: List[str]
build_command: List[str]
map_format: str
build_dir: str
map_address_offset: int
baseimg: Optional[str]
myimg: Optional[str]
mapfile: Optional[str]
source_directories: Optional[List[str]]
source_extensions: List[str]
show_line_numbers_default: bool
disassemble_all: bool
reg_categories: Dict[str, int]
expected_dir: str
@dataclass
class Compress:
context: int
same_instr: bool
@dataclass
class Config:
arch: "ArchSettings"
# Build/objdump options
diff_obj: bool
file: Optional[str]
make: bool
source_old_binutils: bool
diff_section: str
inlines: bool
max_function_size_lines: int
max_function_size_bytes: int
# Display options
formatter: "Formatter"
diff_mode: DiffMode
base_shift: int
skip_lines: int
compress: Optional[Compress]
show_rodata_refs: bool
show_branches: bool
show_line_numbers: bool
show_source: bool
stop_at_ret: Optional[int]
ignore_large_imms: bool
ignore_addr_diffs: bool
algorithm: str
reg_categories: Dict[str, int]
diff_function_symbols: bool
# Score options
score_stack_differences = True
penalty_stackdiff = 1
penalty_regalloc = 5
penalty_reordering = 60
penalty_insertion = 100
penalty_deletion = 100
def create_project_settings(settings: Dict[str, Any]) -> ProjectSettings:
return ProjectSettings(
arch_str=settings.get("arch", "mips"),
baseimg=settings.get("baseimg"),
myimg=settings.get("myimg"),
mapfile=settings.get("mapfile"),
build_command=settings.get(
"make_command", ["make", *settings.get("makeflags", [])]
),
source_directories=settings.get("source_directories"),
source_extensions=settings.get(
"source_extensions", [".c", ".h", ".cpp", ".hpp", ".s"]
),
objdump_executable=get_objdump_executable(settings.get("objdump_executable")),
objdump_flags=settings.get("objdump_flags", []),
expected_dir=settings.get("expected_dir", "expected/"),
map_format=settings.get("map_format", "gnu"),
map_address_offset=settings.get(
"map_address_offset", settings.get("ms_map_address_offset", 0)
),
build_dir=settings.get("build_dir", settings.get("mw_build_dir", "build/")),
show_line_numbers_default=settings.get("show_line_numbers_default", True),
disassemble_all=settings.get("disassemble_all", False),
reg_categories=settings.get("reg_categories", {}),
)
def create_config(args: argparse.Namespace, project: ProjectSettings) -> Config:
arch = get_arch(project.arch_str)
formatter: Formatter
if args.format == "plain":
formatter = PlainFormatter(column_width=args.column_width)
elif args.format == "color":
formatter = AnsiFormatter(column_width=args.column_width)
elif args.format == "html":
formatter = HtmlFormatter()
elif args.format == "json":
formatter = JsonFormatter(arch_str=arch.name)
else:
raise ValueError(f"Unsupported --format: {args.format}")
compress = None
if args.compress_matching is not None:
compress = Compress(args.compress_matching, False)
if args.compress_sameinstr is not None:
if compress is not None:
raise ValueError(
"Cannot pass both --compress-matching and --compress-sameinstr"
)
compress = Compress(args.compress_sameinstr, True)
show_line_numbers = args.show_line_numbers
if show_line_numbers is None:
show_line_numbers = project.show_line_numbers_default
return Config(
arch=arch,
# Build/objdump options
diff_obj=args.diff_obj,
file=args.file,
make=args.make,
source_old_binutils=args.source_old_binutils
or "llvm-" in project.objdump_executable,
diff_section=args.diff_section,
inlines=args.inlines,
max_function_size_lines=args.max_lines,
max_function_size_bytes=args.max_lines * 4,
# Display options
formatter=formatter,
diff_mode=args.diff_mode or DiffMode.NORMAL,
base_shift=eval_int(
args.base_shift, "Failed to parse --base-shift (-S) argument as an integer."
),
skip_lines=args.skip_lines,
compress=compress,
show_rodata_refs=args.show_rodata_refs,
show_branches=args.show_branches,
show_line_numbers=show_line_numbers,
show_source=args.show_source or args.source_old_binutils,
stop_at_ret=args.stop_at_ret,
ignore_large_imms=args.ignore_large_imms,
ignore_addr_diffs=args.ignore_addr_diffs,
algorithm=args.algorithm,
reg_categories=project.reg_categories,
diff_function_symbols=args.diff_function_symbols,
)
def get_objdump_executable(objdump_executable: Optional[str]) -> str:
if objdump_executable is not None:
return objdump_executable
objdump_candidates = [
"mips-linux-gnu-objdump",
"mips64-elf-objdump",
"mips-elf-objdump",
"sh-elf-objdump",
"sh4-linux-gnu-objdump",
"m68k-elf-objdump",
]
for objdump_cand in objdump_candidates:
try:
subprocess.check_call(
[objdump_cand, "--version"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return objdump_cand
except subprocess.CalledProcessError:
pass
except FileNotFoundError:
pass
return fail(
f"Missing binutils; please ensure {' or '.join(objdump_candidates)} exists, or configure objdump_executable."
)
def get_arch(arch_str: str) -> "ArchSettings":
for settings in ARCH_SETTINGS:
if arch_str == settings.name:
return settings
raise ValueError(f"Unknown architecture: {arch_str}")
BUFFER_CMD: List[str] = ["tail", "-c", str(10**9)]
# -S truncates long lines instead of wrapping them
# -R interprets color escape sequences
# -i ignores case when searching
# -c something about how the screen gets redrawn; I don't remember the purpose
# -#6 makes left/right arrow keys scroll by 6 characters
LESS_CMD: List[str] = ["less", "-SRic", "-+F", "-+X", "-#6"]
DEBOUNCE_DELAY: float = 0.1
# ==== FORMATTING ====
@enum.unique
class BasicFormat(enum.Enum):
NONE = enum.auto()
IMMEDIATE = enum.auto()
STACK = enum.auto()
REGISTER = enum.auto()
REGISTER_CATEGORY = enum.auto()
DELAY_SLOT = enum.auto()
DIFF_CHANGE = enum.auto()
DIFF_ADD = enum.auto()
DIFF_REMOVE = enum.auto()
SOURCE_FILENAME = enum.auto()
SOURCE_FUNCTION = enum.auto()
SOURCE_LINE_NUM = enum.auto()
SOURCE_OTHER = enum.auto()
@dataclass(frozen=True)
class RotationFormat:
group: str
index: int
key: str
Format = Union[BasicFormat, RotationFormat]
FormatFunction = Callable[[str], Format]
class Text:
segments: List[Tuple[str, Format]]
def __init__(self, line: str = "", f: Format = BasicFormat.NONE) -> None:
self.segments = [(line, f)] if line else []
def reformat(self, f: Format) -> "Text":
return Text(self.plain(), f)
def plain(self) -> str:
return "".join(s for s, f in self.segments)
def __repr__(self) -> str:
return f"<Text: {self.plain()!r}>"
def __bool__(self) -> bool:
return any(s for s, f in self.segments)
def __str__(self) -> str:
# Use Formatter.apply(...) instead
return NotImplemented
def __eq__(self, other: object) -> bool:
return NotImplemented
def __add__(self, other: Union["Text", str]) -> "Text":
if isinstance(other, str):
other = Text(other)
result = Text()
# If two adjacent segments have the same format, merge their lines
if (
self.segments
and other.segments
and self.segments[-1][1] == other.segments[0][1]
):
result.segments = (
self.segments[:-1]
+ [(self.segments[-1][0] + other.segments[0][0], self.segments[-1][1])]
+ other.segments[1:]
)
else:
result.segments = self.segments + other.segments
return result
def __radd__(self, other: Union["Text", str]) -> "Text":
if isinstance(other, str):
other = Text(other)
return other + self
def finditer(self, pat: Pattern[str]) -> Iterator[Match[str]]:
"""Replacement for `pat.finditer(text)` that operates on the inner text,
and returns the exact same matches as `Text.sub(pat, ...)`."""
for chunk, f in self.segments:
for match in pat.finditer(chunk):
yield match
def sub(self, pat: Pattern[str], sub_fn: Callable[[Match[str]], "Text"]) -> "Text":
result = Text()
for chunk, f in self.segments:
i = 0
for match in pat.finditer(chunk):
start, end = match.start(), match.end()
assert i <= start <= end <= len(chunk)
sub = sub_fn(match)
if i != start:
result.segments.append((chunk[i:start], f))
result.segments.extend(sub.segments)
i = end
if chunk[i:]:
result.segments.append((chunk[i:], f))
return result
def ljust(self, column_width: int) -> "Text":
length = sum(len(x) for x, _ in self.segments)
return self + " " * max(column_width - length, 0)
@dataclass
class TableLine:
key: Optional[str]
is_data_ref: bool
cells: Tuple[Tuple[Text, Optional["Line"]], ...]
@dataclass
class TableData:
headers: Tuple[Text, ...]
current_score: int
max_score: int
previous_score: Optional[int]
lines: List[TableLine]
class Formatter(abc.ABC):
@abc.abstractmethod
def apply_format(self, chunk: str, f: Format) -> str:
"""Apply the formatting `f` to `chunk` and escape the contents."""
...
@abc.abstractmethod
def table(self, data: TableData) -> str:
"""Format a multi-column table with metadata"""
...
def apply(self, text: Text) -> str:
return "".join(self.apply_format(chunk, f) for chunk, f in text.segments)
@staticmethod
def outputline_texts(line: TableLine) -> Tuple[Text, ...]:
return tuple(cell[0] for cell in line.cells)
@dataclass
class PlainFormatter(Formatter):
column_width: int
def apply_format(self, chunk: str, f: Format) -> str:
return chunk
def table(self, data: TableData) -> str:
rows = [data.headers] + [self.outputline_texts(line) for line in data.lines]
return "\n".join(
"".join(self.apply(x.ljust(self.column_width)) for x in row) for row in rows
)
@dataclass
class AnsiFormatter(Formatter):
# Additional ansi escape codes not in colorama. See:
# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters
STYLE_UNDERLINE = "\x1b[4m"
STYLE_NO_UNDERLINE = "\x1b[24m"
STYLE_INVERT = "\x1b[7m"
STYLE_RESET = "\x1b[0m"
BASIC_ANSI_CODES = {
BasicFormat.NONE: "",
BasicFormat.IMMEDIATE: Fore.LIGHTBLUE_EX,
BasicFormat.STACK: Fore.YELLOW,
BasicFormat.REGISTER: Fore.YELLOW,
BasicFormat.REGISTER_CATEGORY: Fore.LIGHTYELLOW_EX,
BasicFormat.DIFF_CHANGE: Fore.LIGHTBLUE_EX,
BasicFormat.DIFF_ADD: Fore.GREEN,
BasicFormat.DIFF_REMOVE: Fore.RED,
BasicFormat.SOURCE_FILENAME: Style.DIM + Style.BRIGHT,
BasicFormat.SOURCE_FUNCTION: Style.DIM + Style.BRIGHT + STYLE_UNDERLINE,
BasicFormat.SOURCE_LINE_NUM: Fore.LIGHTBLACK_EX,
BasicFormat.SOURCE_OTHER: Style.DIM,
}
BASIC_ANSI_CODES_UNDO = {
BasicFormat.NONE: "",
BasicFormat.SOURCE_FILENAME: Style.NORMAL,
BasicFormat.SOURCE_FUNCTION: Style.NORMAL + STYLE_NO_UNDERLINE,
BasicFormat.SOURCE_OTHER: Style.NORMAL,
}
ROTATION_ANSI_COLORS = [
Fore.MAGENTA,
Fore.CYAN,
Fore.GREEN,
Fore.RED,
Fore.LIGHTYELLOW_EX,
Fore.LIGHTMAGENTA_EX,
Fore.LIGHTCYAN_EX,
Fore.LIGHTGREEN_EX,
Fore.LIGHTBLACK_EX,
]
column_width: int
def apply_format(self, chunk: str, f: Format) -> str:
if f == BasicFormat.NONE:
return chunk
undo_ansi_code = Fore.RESET
if isinstance(f, BasicFormat):
ansi_code = self.BASIC_ANSI_CODES[f]
undo_ansi_code = self.BASIC_ANSI_CODES_UNDO.get(f, undo_ansi_code)
elif isinstance(f, RotationFormat):
ansi_code = self.ROTATION_ANSI_COLORS[
f.index % len(self.ROTATION_ANSI_COLORS)
]
else:
static_assert_unreachable(f)
return f"{ansi_code}{chunk}{undo_ansi_code}"
def table(self, data: TableData) -> str:
rows = [(data.headers, False)] + [
(
self.outputline_texts(line),
line.is_data_ref,
)
for line in data.lines
]
return "\n".join(
"".join(
(self.STYLE_INVERT if is_data_ref else "")
+ self.apply(x.ljust(self.column_width))
+ (self.STYLE_RESET if is_data_ref else "")
for x in row
)
for (row, is_data_ref) in rows
)
@dataclass
class HtmlFormatter(Formatter):
rotation_formats: int = 9
def apply_format(self, chunk: str, f: Format) -> str:
chunk = html.escape(chunk)
if f == BasicFormat.NONE:
return chunk
if isinstance(f, BasicFormat):
class_name = f.name.lower().replace("_", "-")
data_attr = ""
elif isinstance(f, RotationFormat):
class_name = f"rotation-{f.index % self.rotation_formats}"
rotation_key = html.escape(f"{f.group};{f.key}", quote=True)
data_attr = f'data-rotation="{rotation_key}"'
else:
static_assert_unreachable(f)
return f"<span class='{class_name}' {data_attr}>{chunk}</span>"
def table(self, data: TableData) -> str:
def table_row(line: Tuple[Text, ...], is_data_ref: bool, cell_el: str) -> str:
tr_attrs = " class='data-ref'" if is_data_ref else ""
output_row = f" <tr{tr_attrs}>"
for cell in line:
cell_html = self.apply(cell)
output_row += f"<{cell_el}>{cell_html}</{cell_el}>"
output_row += "</tr>\n"
return output_row
output = "<table class='diff'>\n"
output += " <thead>\n"
output += table_row(data.headers, False, "th")
output += " </thead>\n"
output += " <tbody>\n"
output += "".join(
table_row(self.outputline_texts(line), line.is_data_ref, "td")
for line in data.lines
)
output += " </tbody>\n"
output += "</table>\n"
return output
@dataclass
class PythonFormatter(Formatter):
arch_str: str
def apply_format(self, chunk: str, f: Format) -> str:
# This method is unused by this formatter
return NotImplemented
def table(self, data: TableData) -> str:
# This method is unused by this formatter
return NotImplemented
def raw(self, data: TableData) -> Dict[str, Any]:
def serialize_format(s: str, f: Format) -> Dict[str, Any]:
if f == BasicFormat.NONE:
return {"text": s}
elif isinstance(f, BasicFormat):
return {"text": s, "format": f.name.lower()}
elif isinstance(f, RotationFormat):
attrs = asdict(f)
attrs.update({"text": s, "format": "rotation"})
return attrs
else:
static_assert_unreachable(f)
def serialize(text: Optional[Text]) -> List[Dict[str, Any]]:
if text is None:
return []
return [serialize_format(s, f) for s, f in text.segments]
output: Dict[str, Any] = {}
output["arch_str"] = self.arch_str
output["header"] = {
name: serialize(h)
for h, name in zip(data.headers, ("base", "current", "previous"))
}
output["current_score"] = data.current_score
output["max_score"] = data.max_score
if data.previous_score is not None:
output["previous_score"] = data.previous_score
output_rows: List[Dict[str, Any]] = []
for row in data.lines:
output_row: Dict[str, Any] = {}
output_row["key"] = row.key
output_row["is_data_ref"] = row.is_data_ref
iters: List[Tuple[str, Text, Optional[Line]]] = [
(label, *cell)
for label, cell in zip(("base", "current", "previous"), row.cells)
]
if all(line is None for _, _, line in iters):
# Skip rows that were only for displaying source code
continue
for column_name, text, line in iters:
column: Dict[str, Any] = {}
column["text"] = serialize(text)
if line:
if line.mnemonic is not None:
column["mnemonic"] = line.mnemonic
if line.symbol is not None:
column["symbol"] = line.symbol
if line.line_num is not None:
column["line"] = line.line_num
if line.branch_target is not None:
column["branch"] = line.branch_target
if line.source_lines:
column["src"] = line.source_lines
if line.comment is not None:
column["src_comment"] = line.comment
if line.source_line_num is not None:
column["src_line"] = line.source_line_num
if line or column["text"]:
output_row[column_name] = column
output_rows.append(output_row)
output["rows"] = output_rows
return output
@dataclass
class JsonFormatter(PythonFormatter):
def table(self, data: TableData) -> str: