Add proton.record statements to the FMMS kernel TTGIR file. Uses a two-pass approach: first scan for insertion points, then insert from bottom to top so line indices remain stable.
(input_file: str)
| 32 | |
| 33 | |
| 34 | def add_proton_records(input_file: str) -> None: |
| 35 | """Add proton.record statements to the FMMS kernel TTGIR file. |
| 36 | |
| 37 | Uses a two-pass approach: first scan for insertion points, then insert |
| 38 | from bottom to top so line indices remain stable. |
| 39 | """ |
| 40 | with open(input_file) as f: |
| 41 | lines = f.readlines() |
| 42 | |
| 43 | if any("proton.record" in line for line in lines): |
| 44 | raise AssertionError( |
| 45 | "File already contains `proton.record` statements! " |
| 46 | "Re-dump the TTGIR without proton scopes first." |
| 47 | ) |
| 48 | |
| 49 | insertions = _find_insertion_points(lines) |
| 50 | _validate_insertions(insertions, input_file) |
| 51 | |
| 52 | # Insert from bottom to top so earlier indices stay valid. |
| 53 | # At the same line index, the last-processed item ends up first in the file. |
| 54 | # Secondary key: "end" before "start" in the output (so end=0, start=1). |
| 55 | # Tertiary key: "kernel" is the outermost scope, so its start must appear |
| 56 | # first (processed last → nesting=0 for start) and its end must appear |
| 57 | # last (processed first → nesting=0 for end). |
| 58 | def _sort_key(item): |
| 59 | line_idx, text = item |
| 60 | is_start = 1 if text.startswith("start") else 0 |
| 61 | is_kernel = '"kernel"' in text |
| 62 | # For starts at same line: kernel (nesting=0) processed last → first in file |
| 63 | # For ends at same line: kernel (nesting=1) processed first → last in file |
| 64 | nesting = (0 if is_kernel else 1) if is_start else (1 if is_kernel else 0) |
| 65 | return (line_idx, is_start, nesting) |
| 66 | |
| 67 | for line_idx, text in sorted(insertions, key=_sort_key, reverse=True): |
| 68 | lines.insert(line_idx, f" proton.record {text} loc(#loc1)\n") |
| 69 | |
| 70 | with open(input_file, "w") as f: |
| 71 | f.writelines(lines) |
| 72 | |
| 73 | scopes = sorted({t.split('"')[1] for _, t in insertions}) |
| 74 | print(f"Added proton records to {input_file}: {scopes}") |
| 75 | |
| 76 | |
| 77 | def _find_insertion_points(lines: list[str]) -> list[tuple[int, str]]: |
no test coverage detected