| 1 | #!/usr/bin/env python3 |
| 2 | # |
| 3 | # SPDX-FileCopyrightText: Copyright 2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 4 | # |
| 5 | # SPDX-License-Identifier: Apache-2.0 |
| 6 | |
| 7 | |
| 8 | def annotate(text: str, descriptions: list[tuple[int, str]]) -> str: |
| 9 | """Annotate offsets in ``text`` with aligned descriptions.""" |
| 10 | if not descriptions: |
| 11 | return text |
| 12 | |
| 13 | for offset, _ in descriptions: |
| 14 | if offset < 0 or offset >= len(text): |
| 15 | raise ValueError(f"annotation offset out of range: {offset}") |
| 16 | |
| 17 | sorted_descriptions = sorted(descriptions, key=lambda description: description[0]) |
| 18 | offsets = sorted({offset for offset, _ in sorted_descriptions}) |
| 19 | annotated_offsets = set(offsets) |
| 20 | |
| 21 | display_positions: dict[int, int] = {} |
| 22 | display_text_parts: list[str] = [] |
| 23 | for offset, char in enumerate(text): |
| 24 | if offset in annotated_offsets and offset != 0: |
| 25 | display_text_parts.append(" ") |
| 26 | |
| 27 | if offset in annotated_offsets: |
| 28 | display_positions[offset] = len(display_text_parts) |
| 29 | |
| 30 | display_text_parts.append(char) |
| 31 | |
| 32 | display_text = "".join(display_text_parts) |
| 33 | display_width = len(display_text) |
| 34 | |
| 35 | lines = [display_text] |
| 36 | |
| 37 | marker_line = [" "] * display_width |
| 38 | for offset in offsets: |
| 39 | marker_line[display_positions[offset]] = "|" |
| 40 | lines.append("".join(marker_line).rstrip()) |
| 41 | |
| 42 | descriptions_by_offset: dict[int, list[str]] = {} |
| 43 | for offset, description in sorted_descriptions: |
| 44 | descriptions_by_offset.setdefault(offset, []).append(description) |
| 45 | |
| 46 | for index, offset in enumerate(reversed(offsets)): |
| 47 | remaining_offsets = [remaining for remaining in offsets if remaining < offset] |
| 48 | for description_index, description in enumerate(descriptions_by_offset[offset]): |
| 49 | line = [" "] * display_width |
| 50 | for remaining in remaining_offsets: |
| 51 | line[display_positions[remaining]] = "|" |
| 52 | |
| 53 | connector = ( |
| 54 | "`" |
| 55 | if description_index == len(descriptions_by_offset[offset]) - 1 |
| 56 | else "|" |
| 57 | ) |
| 58 | position = display_positions[offset] |
| 59 | line[position] = connector |
| 60 | line[position + 1 :] = ["-"] * (display_width - position - 1) |
| 61 | lines.append(f"{''.join(line)} {description}") |
| 62 | |
| 63 | if index != len(offsets) - 1: |
| 64 | separator = [" "] * display_width |
| 65 | for remaining in remaining_offsets: |
| 66 | separator[display_positions[remaining]] = "|" |
| 67 | lines.append("".join(separator).rstrip()) |
| 68 | |
| 69 | return "\n".join(lines) |