From facebef9e54a2aa39a86928cb525d6a9b9fa1029 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:17:07 +0100 Subject: [PATCH] refactor: index source lines once per file core.lines.LineIndex answers the line of an offset by binary search. mame_parser and fbneo_parser counted the newlines before each match, O(n) per set, and csharp_source kept its own copy of the index. arcade_parent_importer reads a profile's repository slug through core.upstream.parse_repo and refuses a source that is not on GitHub, the only forge its fetches reach. --- scripts/core/lines.py | 27 +++++++++++++++ scripts/scraper/arcade_parent_importer.py | 10 +++--- scripts/scraper/fbneo_parser.py | 5 ++- scripts/scraper/mame_parser.py | 5 ++- tests/test_lines.py | 42 +++++++++++++++++++++++ 5 files changed, 83 insertions(+), 6 deletions(-) create mode 100644 scripts/core/lines.py create mode 100644 tests/test_lines.py diff --git a/scripts/core/lines.py b/scripts/core/lines.py new file mode 100644 index 000000000..ce4782371 --- /dev/null +++ b/scripts/core/lines.py @@ -0,0 +1,27 @@ +"""Line numbers of offsets in a text, read from one index of line starts.""" + +from __future__ import annotations + +import bisect + + +class LineIndex: + """1-based line of any offset of *text*, by binary search. + + Counting the newlines before each match is O(n) per lookup: a parser + that reports the line of every match of a file reads it once here. + """ + + def __init__(self, text: str) -> None: + self._starts = [0] + position = text.find("\n") + while position != -1: + self._starts.append(position + 1) + position = text.find("\n", position + 1) + + def line(self, offset: int) -> int: + return bisect.bisect_right(self._starts, offset) + + def start(self, line: int) -> int: + """Offset of the first character of a 1-based line.""" + return self._starts[line - 1] diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index e0dcabf5a..cbdd7276d 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -55,6 +55,7 @@ from core.artifacts import write_if_changed from model.profiles import load_emulator_profiles from core.cli import run_cli from core.hashing import compute_hashes +from core.upstream import parse_repo from .base_scraper import download from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members from .romset_dat_importer import ( @@ -935,10 +936,11 @@ def _dat_cross_check( def _repo_slug(url: str) -> str: - parts = [p for p in urllib.parse.urlsplit(url).path.split("/") if p] - if len(parts) < 2: - raise ValueError(f"not a repository URL: {url}") - return f"{parts[0]}/{parts[1].removesuffix('.git')}" + """owner/name of the GitHub repository a profile's source names.""" + repo = parse_repo(url) + if repo is None or repo.family != "github": + raise ValueError(f"not a GitHub repository URL: {url}") + return repo.slug def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple[Path, str]: diff --git a/scripts/scraper/fbneo_parser.py b/scripts/scraper/fbneo_parser.py index 695db82c4..900867a74 100644 --- a/scripts/scraper/fbneo_parser.py +++ b/scripts/scraper/fbneo_parser.py @@ -11,6 +11,8 @@ import os import re from pathlib import Path +from core.lines import LineIndex + _ROM_ENTRY_RE = re.compile( r'\{\s*"([^"]+)"\s*,\s*(0x[\da-fA-F]+)\s*,\s*(0x[\da-fA-F]+)\s*,\s*([^}]+)\}', ) @@ -33,6 +35,7 @@ def find_bios_sets(source: str, filename: str) -> dict[str, dict]: {set_name: {"source_file": str, "source_line": int}} """ results: dict[str, dict] = {} + lines = LineIndex(source) for match in _BURN_DRIVER_RE.finditer(source): body = match.group(2) @@ -45,7 +48,7 @@ def find_bios_sets(source: str, filename: str) -> dict[str, dict]: continue set_name = name_match.group(1) - line_num = source[: match.start()].count("\n") + 1 + line_num = lines.line(match.start()) results[set_name] = { "source_file": filename, diff --git a/scripts/scraper/mame_parser.py b/scripts/scraper/mame_parser.py index b77b5458f..80740f666 100644 --- a/scripts/scraper/mame_parser.py +++ b/scripts/scraper/mame_parser.py @@ -13,6 +13,8 @@ import os import re from pathlib import Path +from core.lines import LineIndex + # Macros that declare a machine entry. GAMEL is GAME plus a layout and is # the only suffixed form MAME declares (src/emu/gamedrv.h): a BIOS root that # ships a layout, such as gq863 or aristmk5, is written with it. @@ -126,6 +128,7 @@ def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]: MACHINE_IS_BIOS_ROOT, returns set names with source location. """ results: dict[str, dict] = {} + lines = LineIndex(source) for match in MACHINE_MACROS.finditer(source): start = match.end() - 1 # position of opening paren @@ -154,7 +157,7 @@ def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]: continue set_name = args[1].strip() - line_no = source[: match.start()].count("\n") + 1 + line_no = lines.line(match.start()) results[set_name] = { "source_file": filename, diff --git a/tests/test_lines.py b/tests/test_lines.py new file mode 100644 index 000000000..e5f4446a3 --- /dev/null +++ b/tests/test_lines.py @@ -0,0 +1,42 @@ +"""One line index answers the line of every offset a parser reports.""" + +from __future__ import annotations + +import tests + +import unittest + +from core.lines import LineIndex + + +class LinesOfOffsets(unittest.TestCase): + TEXT = "a\nbc\n\nd" + + def test_each_offset_gets_the_count_of_newlines_before_it_plus_one(self): + index = LineIndex(self.TEXT) + for offset in range(len(self.TEXT) + 1): + with self.subTest(offset=offset): + self.assertEqual(index.line(offset), self.TEXT[:offset].count("\n") + 1) + + def test_a_line_starts_after_the_newline_before_it(self): + index = LineIndex(self.TEXT) + self.assertEqual([index.start(n) for n in (1, 2, 3, 4)], [0, 2, 5, 6]) + + def test_a_text_without_newline_is_one_line(self): + self.assertEqual(LineIndex("").line(0), 1) + self.assertEqual(LineIndex("abc").line(2), 1) + + +class ParsersReportLines(unittest.TestCase): + def test_mame_and_fbneo_sets_carry_their_line(self): + from scripts.scraper.fbneo_parser import find_bios_sets + from scripts.scraper.mame_parser import find_bios_root_sets + + mame = "\n\nGAME( 1990, neogeo, 0, ng, ng, ng_state, init, ROT0, \"SNK\", \"Neo\", MACHINE_IS_BIOS_ROOT )\n" + self.assertEqual(find_bios_root_sets(mame, "neogeo.cpp")["neogeo"]["source_line"], 3) + fbneo = '\n\n\nstruct BurnDriver BurnDrvNeogeo = {\n\t"neogeo", NULL, NULL, NULL, "1990",\n\tBDF_BOARDROM,\n};\n' + self.assertEqual(find_bios_sets(fbneo, "d_neogeo.cpp")["neogeo"]["source_line"], 4) + + +if __name__ == "__main__": + unittest.main()