mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: read c comments and calls through clex
This commit is contained in:
1 parent
9f8ac141c1
commit
e16caf57b4
6 files changed
+119
-217
No files matched your search
@@ -29,7 +29,8 @@ sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core import upstream
|
||||
from core.cli import add_repo_inputs, require_directory
|
||||
from model.safeparse import yaml_load
|
||||
from scraper.mame_parser import MACHINE_MACROS, strip_comments
|
||||
from scraper.clex import blank_comments
|
||||
from scraper.mame_parser import MACHINE_MACROS
|
||||
|
||||
# An optional role word names the repository the lines are in.
|
||||
DRIVER_REF = re.compile(r"^(?:(source|upstream) )?(src/[\w./+-]+):(\d+)$")
|
||||
@@ -49,7 +50,7 @@ class Finding:
|
||||
|
||||
def declares(line: str, set_name: str) -> bool:
|
||||
"""Whether this line is the machine declaration of that set."""
|
||||
clean = strip_comments(line)
|
||||
clean = blank_comments(line)
|
||||
match = MACHINE_MACROS.search(clean)
|
||||
if not match:
|
||||
return False
|
||||
|
||||
@@ -57,6 +57,7 @@ from core.cli import add_repo_inputs, run_cli
|
||||
from core.hashing import compute_hashes
|
||||
from core.upstream import parse_repo
|
||||
from .base_scraper import download
|
||||
from .clex import DriverSourceError, blank_comments, call_args, call_span
|
||||
from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members
|
||||
from .romset_dat_importer import (
|
||||
MAME_LISTXML_URL,
|
||||
@@ -312,30 +313,6 @@ def fbneo_sets(
|
||||
_TOKEN = re.compile(r'"(?:\\.|[^"\\])*"|[{},]|[^\s{},"]+')
|
||||
|
||||
|
||||
def _strip_comments(text: str) -> str:
|
||||
"""C source with comments removed, string literals kept intact."""
|
||||
out: list[str] = []
|
||||
i, n = 0, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c == '"':
|
||||
j = i + 1
|
||||
while j < n and text[j] != '"':
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
out.append(text[i : j + 1])
|
||||
i = j + 1
|
||||
elif text.startswith("//", i):
|
||||
i = text.find("\n", i)
|
||||
i = n if i == -1 else i
|
||||
elif text.startswith("/*", i):
|
||||
i = text.find("*/", i + 2)
|
||||
i = n if i == -1 else i + 2
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _initializer(text: str, array: str) -> list:
|
||||
"""The brace initializer of ``const <type> <array>[] = {...}`` as nested
|
||||
lists of tokens, each element split on its top-level commas."""
|
||||
@@ -376,7 +353,7 @@ def _string(token: object) -> str | None:
|
||||
|
||||
def flycast_index(source: str) -> dict:
|
||||
"""BIOS archive per NAOMI/Atomiswave game from naomi_roms.cpp."""
|
||||
text = _strip_comments(source)
|
||||
text = blank_comments(source)
|
||||
archive_of: dict[str, str] = {}
|
||||
for element in _initializer(text, "BIOS"):
|
||||
if not isinstance(element, list) or not element:
|
||||
@@ -448,47 +425,6 @@ _IDENTIFIER = re.compile(r"\b[A-Za-z_]\w*\b")
|
||||
_INCLUDE = re.compile(r'"([^"]+)"')
|
||||
|
||||
|
||||
class DriverSourceError(ValueError):
|
||||
"""The driver source does not have the shape the reader knows."""
|
||||
|
||||
|
||||
def _call_args(text: str, start: int) -> list[str]:
|
||||
"""Top-level arguments of the call whose opening parenthesis ends at
|
||||
*start*, string literals kept whole."""
|
||||
return _call_span(text, start)[0]
|
||||
|
||||
|
||||
def _call_span(text: str, start: int) -> tuple[list[str], int]:
|
||||
"""The arguments of a call and the offset just past its parenthesis."""
|
||||
args: list[str] = []
|
||||
current: list[str] = []
|
||||
depth, i, n = 1, start, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c == '"':
|
||||
j = i + 1
|
||||
while j < n and text[j] != '"':
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
current.append(text[i : j + 1])
|
||||
i = j + 1
|
||||
continue
|
||||
if c == "(":
|
||||
depth += 1
|
||||
elif c == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
args.append("".join(current).strip())
|
||||
return args, i + 1
|
||||
elif c == "," and depth == 1:
|
||||
args.append("".join(current).strip())
|
||||
current = []
|
||||
i += 1
|
||||
continue
|
||||
current.append(c)
|
||||
i += 1
|
||||
raise DriverSourceError("unterminated macro call")
|
||||
|
||||
|
||||
def _condition_value(expr: str, defines: dict[str, str], depth: int = 0) -> int:
|
||||
"""An ``#if`` expression the way the C preprocessor reads it: a name not
|
||||
defined is 0, a defined name is its value."""
|
||||
@@ -590,7 +526,7 @@ class _Preprocessor:
|
||||
self, path: str, text: str, defines: dict[str, str],
|
||||
local: dict[str, tuple[list[str] | None, str]] | None, seen: set[str],
|
||||
) -> str:
|
||||
text = _strip_comments(text).replace("\\\r\n", " ").replace("\\\n", " ")
|
||||
text = blank_comments(text, keep_lines=False).replace("\\\r\n", " ").replace("\\\n", " ")
|
||||
out: list[str] = []
|
||||
# Each level: (enclosing level active, a branch already taken, this branch active).
|
||||
stack: list[tuple[bool, bool, bool]] = []
|
||||
@@ -700,7 +636,7 @@ def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str
|
||||
if match.start() < position:
|
||||
continue
|
||||
params, body = writers[match.group(1)]
|
||||
args, end = _call_span(text, match.end())
|
||||
args, end = call_span(text, match.end())
|
||||
if len(args) != len(params):
|
||||
raise DriverSourceError(f"{match.group(1)} called with {len(args)} arguments")
|
||||
values = dict(zip(params, args))
|
||||
@@ -726,7 +662,7 @@ def _holds_roms(
|
||||
seen: frozenset[str] = frozenset(),
|
||||
) -> bool:
|
||||
for match in _ROM_LOAD.finditer(body):
|
||||
if _dumped(_call_args(body, match.end())):
|
||||
if _dumped(call_args(body, match.end())):
|
||||
return True
|
||||
# A ROM list shared through a macro of the same file (a BIOS
|
||||
# block every game of the board pulls in).
|
||||
@@ -753,7 +689,7 @@ def _read_driver(
|
||||
match.group(1), (_holds_roms(body, local, known), bool(_DISK_IMAGE.search(body)))
|
||||
)
|
||||
for match in _GAME_MACRO.finditer(text):
|
||||
args = _call_args(text, match.end())
|
||||
args = call_args(text, match.end())
|
||||
if len(args) < 9:
|
||||
raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments")
|
||||
name, parent = args[1], args[2]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""C and C++ source read the way the compiler reads it: comments apart from
|
||||
code, string and character literals kept whole, macro calls split into their
|
||||
arguments (MAME, FBNeo and flycast drivers)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_COMMENT_OR_LITERAL = re.compile(
|
||||
r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S
|
||||
)
|
||||
|
||||
|
||||
class DriverSourceError(ValueError):
|
||||
"""The driver source does not have the shape the reader knows."""
|
||||
|
||||
|
||||
def blank_comments(text: str, keep_lines: bool = True) -> str:
|
||||
"""Text with every comment blanked, literals untouched.
|
||||
|
||||
By default a comment becomes as many spaces as it has characters, its
|
||||
newlines kept: offsets and line numbers survive, so a block found in the
|
||||
result is cited at its line in the file, and a ROM_START written inside
|
||||
a comment is not a block. With `keep_lines` false a comment becomes one
|
||||
space, as translation phase 3 does: a directive a comment spans several
|
||||
lines of stays one line.
|
||||
"""
|
||||
|
||||
def blank(match: re.Match[str]) -> str:
|
||||
found = match.group(0)
|
||||
if found[0] in "\"'":
|
||||
return found
|
||||
return re.sub(r"[^\n]", " ", found) if keep_lines else " "
|
||||
|
||||
return _COMMENT_OR_LITERAL.sub(blank, text)
|
||||
|
||||
|
||||
def call_span(text: str, start: int) -> tuple[list[str], int]:
|
||||
"""The top-level arguments of the call whose opening parenthesis ends at
|
||||
*start*, literals kept whole, and the offset just past its parenthesis."""
|
||||
args: list[str] = []
|
||||
current: list[str] = []
|
||||
depth, i, n = 1, start, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c in "\"'":
|
||||
j = i + 1
|
||||
while j < n and text[j] != c:
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
current.append(text[i : j + 1])
|
||||
i = j + 1
|
||||
continue
|
||||
if c == "(":
|
||||
depth += 1
|
||||
elif c == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
args.append("".join(current).strip())
|
||||
return args, i + 1
|
||||
elif c == "," and depth == 1:
|
||||
args.append("".join(current).strip())
|
||||
current = []
|
||||
i += 1
|
||||
continue
|
||||
current.append(c)
|
||||
i += 1
|
||||
raise DriverSourceError("unterminated macro call")
|
||||
|
||||
|
||||
def call_args(text: str, start: int) -> list[str]:
|
||||
"""The top-level arguments of the call whose opening parenthesis ends at
|
||||
*start*, literals kept whole."""
|
||||
return call_span(text, start)[0]
|
||||
@@ -27,6 +27,7 @@ from typing import IO, NamedTuple
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
from ._hash_merge import generated_start
|
||||
from .clex import blank_comments
|
||||
from .listxml import LISTXML_CHUNK, attrs, iter_elements, rom_members
|
||||
from .mame_parser import _collect_rom_macros, _expand_macros, _parse_rom_entries
|
||||
|
||||
@@ -40,9 +41,6 @@ _SOFTWARE_LIST = re.compile(rb'<softwarelist\b[^>]*\bname="([^"]+)"')
|
||||
_ROM_START = re.compile(r"ROM_START\s*\(\s*(\w+)\s*\)")
|
||||
_ROM_END = re.compile(r"\bROM_END\b")
|
||||
_CRC = re.compile(r"CRC\s*\(\s*([0-9a-fA-F]+)\s*\)")
|
||||
_COMMENT_OR_LITERAL = re.compile(
|
||||
r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S
|
||||
)
|
||||
_ROM_NAME = re.compile(r"\bROM_NAME\s*\(\s*(\w+)\s*\)")
|
||||
_CLASS_END = re.compile(r"^\};", re.M)
|
||||
|
||||
@@ -410,22 +408,6 @@ def source_path(sourcefile: str) -> str:
|
||||
return f"src/mame/{sourcefile}"
|
||||
|
||||
|
||||
def blank_comments(text: str) -> str:
|
||||
"""Text with every comment blanked and its newlines kept.
|
||||
|
||||
Line numbers survive, so a block found in the result is cited at its
|
||||
line in the file. A ROM_START written inside a comment is not a block.
|
||||
"""
|
||||
|
||||
def blank(match: re.Match[str]) -> str:
|
||||
found = match.group(0)
|
||||
if found[0] in "\"'":
|
||||
return found
|
||||
return re.sub(r"[^\n]", " ", found)
|
||||
|
||||
return _COMMENT_OR_LITERAL.sub(blank, text)
|
||||
|
||||
|
||||
def rom_region_label(text: str, set_name: str) -> str:
|
||||
"""ROM_START label the device class of *set_name* returns, or "".
|
||||
|
||||
|
||||
+16
-126
@@ -15,6 +15,8 @@ from pathlib import Path
|
||||
|
||||
from core.lines import LineIndex
|
||||
|
||||
from .clex import DriverSourceError, blank_comments, call_span
|
||||
|
||||
# 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.
|
||||
@@ -73,54 +75,6 @@ _ROM_BIOS = re.compile(r"ROM_BIOS\s*\(\s*(\d+)\s*\)")
|
||||
_OPTIONAL = re.compile(r"\bROM_OPTIONAL\b|\bROMX?_LOAD\w*_OPTIONAL\b")
|
||||
|
||||
|
||||
def strip_comments(source: str) -> str:
|
||||
"""Remove C block and line comments, preserving string and char literals.
|
||||
|
||||
Drivers disable a flag by commenting it out inside the macro call, as in
|
||||
MACHINE_IMPERFECT_SOUND /*| MACHINE_IS_BIOS_ROOT*/. A plain substring test
|
||||
on the raw text reads those as active.
|
||||
"""
|
||||
out: list[str] = []
|
||||
i, end = 0, len(source)
|
||||
|
||||
while i < end:
|
||||
ch = source[i]
|
||||
|
||||
if ch in ('"', "'"):
|
||||
quote = ch
|
||||
out.append(ch)
|
||||
i += 1
|
||||
while i < end:
|
||||
out.append(source[i])
|
||||
if source[i] == "\\":
|
||||
i += 2
|
||||
if i - 1 < end:
|
||||
out.append(source[i - 1])
|
||||
continue
|
||||
if source[i] == quote:
|
||||
i += 1
|
||||
break
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if ch == "/" and i + 1 < end:
|
||||
if source[i + 1] == "*":
|
||||
closing = source.find("*/", i + 2)
|
||||
i = end if closing == -1 else closing + 2
|
||||
out.append(" ")
|
||||
continue
|
||||
if source[i + 1] == "/":
|
||||
newline = source.find("\n", i + 2)
|
||||
i = end if newline == -1 else newline
|
||||
out.append(" ")
|
||||
continue
|
||||
|
||||
out.append(ch)
|
||||
i += 1
|
||||
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]:
|
||||
"""Find machine entries flagged as BIOS root sets.
|
||||
|
||||
@@ -129,21 +83,17 @@ def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]:
|
||||
"""
|
||||
results: dict[str, dict] = {}
|
||||
lines = LineIndex(source)
|
||||
# Drivers disable a flag by commenting it out inside the macro call, as
|
||||
# in MACHINE_IMPERFECT_SOUND /*| MACHINE_IS_BIOS_ROOT*/: a substring test
|
||||
# on the raw text reads those as active. Blanking keeps every offset.
|
||||
code = blank_comments(source)
|
||||
|
||||
for match in MACHINE_MACROS.finditer(source):
|
||||
start = match.end() - 1 # position of opening paren
|
||||
block_end = _find_closing_paren(source, start)
|
||||
if block_end == -1:
|
||||
for match in MACHINE_MACROS.finditer(code):
|
||||
try:
|
||||
args, block_end = call_span(code, match.end())
|
||||
except DriverSourceError:
|
||||
continue
|
||||
|
||||
block = strip_comments(source[start : block_end + 1])
|
||||
if "MACHINE_IS_BIOS_ROOT" not in block:
|
||||
continue
|
||||
|
||||
# Extract set name: first arg after the opening paren
|
||||
inner = block[1:] # skip opening paren
|
||||
args = _split_macro_args(inner)
|
||||
if not args:
|
||||
if "MACHINE_IS_BIOS_ROOT" not in code[match.end() : block_end]:
|
||||
continue
|
||||
|
||||
# The set name position varies by macro type
|
||||
@@ -319,67 +269,6 @@ def _expand_macros(block: str, macros: dict[str, str], depth: int = 5) -> str:
|
||||
return block
|
||||
|
||||
|
||||
def _find_closing_paren(source: str, start: int) -> int:
|
||||
"""Find the matching closing paren for source[start] which must be '('."""
|
||||
depth = 0
|
||||
i = start
|
||||
while i < len(source):
|
||||
ch = source[i]
|
||||
if ch == "(":
|
||||
depth += 1
|
||||
elif ch == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return i
|
||||
elif ch == '"':
|
||||
i += 1
|
||||
while i < len(source) and source[i] != '"':
|
||||
i += 1
|
||||
i += 1
|
||||
return -1
|
||||
|
||||
|
||||
def _split_macro_args(inner: str) -> list[str]:
|
||||
"""Split macro arguments respecting nested parens and strings."""
|
||||
args: list[str] = []
|
||||
depth = 0
|
||||
current: list[str] = []
|
||||
|
||||
i = 0
|
||||
while i < len(inner):
|
||||
ch = inner[i]
|
||||
if ch == '"':
|
||||
current.append(ch)
|
||||
i += 1
|
||||
while i < len(inner) and inner[i] != '"':
|
||||
current.append(inner[i])
|
||||
i += 1
|
||||
if i < len(inner):
|
||||
current.append(inner[i])
|
||||
elif ch == "(":
|
||||
depth += 1
|
||||
current.append(ch)
|
||||
elif ch == ")":
|
||||
if depth == 0:
|
||||
args.append("".join(current))
|
||||
break
|
||||
depth -= 1
|
||||
current.append(ch)
|
||||
elif ch == "," and depth == 0:
|
||||
args.append("".join(current))
|
||||
current = []
|
||||
else:
|
||||
current.append(ch)
|
||||
i += 1
|
||||
|
||||
if current:
|
||||
remaining = "".join(current).strip()
|
||||
if remaining:
|
||||
args.append(remaining)
|
||||
|
||||
return args
|
||||
|
||||
|
||||
def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]:
|
||||
"""Parse ROM entries from a ROM block (content between ROM_START and ROM_END).
|
||||
|
||||
@@ -417,10 +306,11 @@ def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]:
|
||||
context_start = m.start()
|
||||
# Find the opening paren of the ROM_LOAD macro
|
||||
paren_pos = block.find("(", context_start)
|
||||
if paren_pos != -1:
|
||||
close_pos = _find_closing_paren(block, paren_pos)
|
||||
context_end = close_pos + 1 if close_pos != -1 else m.end() + 200
|
||||
else:
|
||||
try:
|
||||
if paren_pos == -1:
|
||||
raise DriverSourceError("no call")
|
||||
context_end = call_span(block, paren_pos + 1)[1]
|
||||
except DriverSourceError:
|
||||
context_end = m.end() + 200
|
||||
context = block[context_start : min(context_end, len(block))]
|
||||
|
||||
|
||||
@@ -403,5 +403,25 @@ class TestParseMameSourceTree(unittest.TestCase):
|
||||
self.assertEqual(results, {})
|
||||
|
||||
|
||||
class TestCSourceLexer(unittest.TestCase):
|
||||
"""One reader of C comments and macro calls for every driver scraper."""
|
||||
|
||||
def test_a_char_literal_quote_opens_no_string(self) -> None:
|
||||
from scripts.scraper.clex import blank_comments
|
||||
|
||||
text = "c = '\"'; /* ROM_START( fake ) */\nx"
|
||||
self.assertNotIn("ROM_START", blank_comments(text))
|
||||
self.assertEqual(len(blank_comments(text)), len(text))
|
||||
self.assertEqual(blank_comments("a/*x\ny*/b", keep_lines=False), "a b")
|
||||
|
||||
def test_an_escaped_quote_does_not_end_the_call(self) -> None:
|
||||
from scripts.scraper.clex import call_span
|
||||
|
||||
text = 'GAME(1990, foo, "a\\"b)", 0) tail'
|
||||
self.assertEqual(call_span(text, 5), (["1990", "foo", '"a\\"b)"', "0"], 27))
|
||||
root = 'GAME(1990, foo, 0, m, i, d, ROT0, "a\\"b)", "n", MACHINE_IS_BIOS_ROOT)'
|
||||
self.assertIn("foo", find_bios_root_sets(root, "x.cpp"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user