#!/usr/bin/env python3
"""Build a {string literal -> libpng function name} map from libpng sources.

Only literals that appear in exactly one function are kept, so a hit in the
firmware identifies that function unambiguously.
"""
import json
import re
import sys
from pathlib import Path

FUNC_HEAD = re.compile(r'^([A-Za-z_][A-Za-z0-9_]*)\s*\(')
DECL_NAME = re.compile(r'([A-Za-z_][A-Za-z0-9_]*)\s*\($')
STR_LIT = re.compile(r'"((?:[^"\\]|\\.)*)"')

def functions(path):
    """Yield (function_name, body_text) for each top-level definition."""
    lines = path.read_text(errors="replace").splitlines()
    pending = None
    name = None
    body = []
    depth = 0
    for line in lines:
        if depth == 0:
            m = FUNC_HEAD.match(line) or DECL_NAME.search(line.strip())
            if m:
                pending = m.group(1)
            if line.startswith("{") and pending:
                name, body, depth = pending, [], 1
                continue
        if depth:
            depth += line.count("{") - line.count("}")
            if depth <= 0:
                yield name, "\n".join(body)
                name, body, depth, pending = None, [], 0, None
            else:
                body.append(line)

def main(src_dir, out_json):
    owners = {}
    for c in sorted(Path(src_dir).glob("png*.c")):
        if c.name == "pngtest.c":
            continue
        for fname, body in functions(c):
            for lit in STR_LIT.findall(body):
                s = lit.encode().decode("unicode_escape")
                if len(s) < 8 or "%" == s.strip():
                    continue
                owners.setdefault(s, set()).add(fname)
    unique = {s: next(iter(f)) for s, f in owners.items() if len(f) == 1}
    Path(out_json).write_text(json.dumps(unique, indent=1, sort_keys=True))
    print(f"{len(owners)} literals, {len(unique)} unique to one function -> {out_json}")

if __name__ == "__main__":
    main(*sys.argv[1:])
