#!/usr/bin/env python3
"""Index of functions and file-scope variables of the preprocessed C sources.
Prints a markdown table; flags name collisions (static symbols defined in several files)."""
import re, sys, os, collections

root = sys.argv[1]
files = []
for d, _, fs in os.walk(root):
    for f in fs:
        if f.endswith('.c'):
            files.append(os.path.join(d, f))
files.sort()

func_re = re.compile(r'^(static\s+)?(inline\s+)?(?:const\s+)?(?:unsigned\s+|signed\s+)?[A-Za-z_]\w*[\s\*]+([A-Za-z_]\w*)\s*\(([^;]*)$')
funcs = collections.defaultdict(list)
vars_ = collections.defaultdict(list)
for path in files:
    rel = os.path.relpath(path, root)
    lines = open(path, encoding='utf-8', errors='replace').read().split('\n')
    depth = 0
    for i, line in enumerate(lines):
        stripped = line.strip()
        if depth == 0 and not line.startswith((' ', '\t', '#', '/', '*', '}')):
            m = func_re.match(line)
            nxt = lines[i + 1].strip() if i + 1 < len(lines) else ''
            if m and m.group(3) not in ('if', 'while', 'for', 'switch', 'return', 'sizeof') and (line.rstrip().endswith('{') or nxt.startswith('{') or line.rstrip().endswith(')')) and not line.rstrip().endswith(';'):
                funcs[m.group(3)].append((rel, bool(m.group(1)), i + 1))
            elif re.match(r'^(static\s+)?(volatile\s+)?(const\s+)?[A-Za-z_]\w*[\s\*]+[A-Za-z_]\w*(\s*\[[^\]]*\])*\s*(=.*)?;?\s*(//.*)?$', line) and not line.startswith(('typedef', 'return', 'extern')) and '(' not in line.split('=')[0]:
                name = re.match(r'^(?:static\s+)?(?:volatile\s+)?(?:const\s+)?[A-Za-z_]\w*[\s\*]+([A-Za-z_]\w*)', line).group(1)
                vars_[name].append((rel, line.startswith('static'), i + 1))
        depth += line.count('{') - line.count('}')
        if depth < 0:
            depth = 0

print('# Function index (C name -> file)\n')
print('| C function | file | static |')
print('|---|---|---|')
for name in sorted(funcs):
    for rel, st, ln in funcs[name]:
        print(f'| {name} | {rel}:{ln} | {"static" if st else ""} |')
print('\n# File-scope variables\n')
print('| C variable | file | static |')
print('|---|---|---|')
for name in sorted(vars_):
    for rel, st, ln in vars_[name]:
        print(f'| {name} | {rel}:{ln} | {"static" if st else ""} |')
print('\n# Collisions\n')
for name, defs in sorted(list(funcs.items()) + list(vars_.items())):
    fs = sorted(set(d[0] for d in defs))
    if len(fs) > 1:
        print(f'- {name}: {", ".join(fs)}')
