"""Gera docs/referencia-api.md: cada header publico, seus tipos e funcoes, com o comentario que esta no proprio header (acima ou na mesma linha).""" import re, sys, os root, out_path = sys.argv[1], sys.argv[2] sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from api_desc import D def key_of(kind, decl): """Nome usado no mapa de descricoes.""" if kind == "func": m = re.search(r"([A-Za-z_][A-Za-z0-9_]*)\s*\((?!\*)", decl) return m.group(1) if m else decl if kind == "macro": return decl if "(" in decl and decl.startswith("COLA") else decl.split("(")[0] m = re.search(r"\(\*\s*([A-Za-z_][A-Za-z0-9_]*)\)", decl) if m: return m.group(1) return decl.split()[-1] def fill(kind, decl, doc): if doc: return doc k = key_of(kind, decl) if k in D: return D[k] if k.endswith("_get_library"): return "Descritor da library (para `tb_library_register`)." if k.endswith("_last_error"): return "Mensagem do último erro desta library." if k.startswith("tt_"): return "Implementação interna da tinyblocks-tensor (tensor.c / ops.c). Outras libraries usam o mesmo pela `TbTensorApi`." if k.startswith("COL_"): return "Cor do tema do editor." if re.search(r"_(X|Y|W|H)$", k): return "Geometria do layout do editor (px)." return "" def headers(): hs = [] for base in ("include", "libraries"): for d, _, fs in os.walk(os.path.join(root, base)): if "/build" in d: continue for f in sorted(fs): if f.endswith(".h"): hs.append(os.path.relpath(os.path.join(d, f), root)) core = sorted(h for h in hs if h.startswith("include/")) libs = sorted(h for h in hs if not h.startswith("include/")) return core + libs def clean_comment(c): c = re.sub(r"^/\*+|\*+/$", "", c.strip()) lines = [re.sub(r"^\s*\*\s?", "", l).rstrip() for l in c.split("\n")] text = " ".join(l.strip() for l in lines if l.strip()) text = re.sub(r"^[-=]+\s*|\s*[-=]{2,}$", "", text).strip() return text def top_comment(src): m = re.match(r"\s*(/\*.*?\*/)", src, re.S) if not m: return "" lines = [re.sub(r"^\s*\*\s?", "", l).rstrip() for l in m.group(1).strip("/*").split("\n")] body = [l for l in lines if l.strip()] if body and re.match(r"^\s*TinyBlocks\s*-", body[0]): body = body[1:] return "\n".join(body).strip() DECL_START = re.compile(r"^\s*(TB_API|TB_MCP_API|TB_PYTHON_API|TB_ED_API|extern\s|typedef|" r"[A-Za-z_][A-Za-z0-9_ \*]*\s[\*\s]*[A-Za-z_][A-Za-z0-9_]*\s*\()") def parse(src): """Itens em ordem: ('section', titulo) | ('func', assinatura, doc) | ('type', nome, doc).""" items, comment = [], "" i, n = 0, len(src) lines = src.split("\n") k = 0 depth = 0 pending_type = None buf, buf_doc = None, "" in_comment, cbuf = False, [] while k < len(lines): line = lines[k] k += 1 s = line.strip() if in_comment: cbuf.append(line) if "*/" in line: in_comment = False c = "\n".join(cbuf) cc = clean_comment(c) if re.match(r"^/\*\s*(--|==)", c.strip()): items.append(("section", cc)) comment = "" else: comment = cc continue if s.startswith("#") or not s: if not s: comment = comment # comentario solto continua valendo ate a declaracao if s.startswith("#define") and depth == 0: m = re.match(r"#define\s+([A-Z][A-Z0-9_]+)(\([^)]*\))?\s*(.*)", s) if m and not m.group(1).endswith("_H") and m.group(1) not in ("TB_API", "TB_MCP_API", "TB_PYTHON_API", "TB_ED_API"): trail = re.search(r"/\*(.*?)\*/", m.group(3) or "") val = re.sub(r"/\*.*?\*/", "", m.group(3) or "").strip() items.append(("macro", m.group(1) + (m.group(2) or ""), val, clean_comment("/*" + trail.group(1) + "*/") if trail else comment)) comment = "" continue if s.startswith("/*") and depth == 0 and buf is None: if "*/" in s and not s.endswith("*/"): pass # comentario seguido de codigo na mesma linha: raro if "*/" in s: cc = clean_comment(s[: s.index("*/") + 2]) if re.match(r"^/\*\s*(--|==)", s): items.append(("section", cc)); comment = "" else: comment = cc continue in_comment, cbuf = True, [line] continue if s.startswith("//"): continue # dentro de struct/enum: so acompanha as chaves if depth > 0 or (buf is None and ("{" in s) and not "(" in s.split("{")[0]): if depth == 0 and buf is None: m = re.match(r"(typedef\s+)?(struct|enum|union)\s*([A-Za-z_][A-Za-z0-9_]*)?", s) pending_type = (m.group(2), m.group(3)) if m else ("bloco", None) pending_doc = comment comment = "" depth += s.count("{") - s.count("}") if depth <= 0: depth = 0 m = re.search(r"\}\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;", s) if pending_type: name = (m.group(1) if m and m.group(1) else None) or pending_type[1] if name and name not in ("extern",): items.append(("type", "%s %s" % (pending_type[0], name), pending_doc)) pending_type = None continue if s.startswith("extern \"C\"") or s == "}": continue if buf is None: if not DECL_START.match(line): comment = "" continue buf, buf_doc = s, comment comment = "" else: buf += " " + s if ";" in s or s.endswith("}"): decl = buf buf = None trail = re.search(r"/\*(.*?)\*/", decl) doc = buf_doc if trail: t = clean_comment("/*" + trail.group(1) + "*/") doc = (doc + " " + t).strip() if doc else t decl = re.sub(r"/\*.*?\*/", "", decl) decl = re.sub(r"\s+", " ", decl).strip() decl = re.sub(r"\b(TB_API|TB_MCP_API|TB_PYTHON_API|TB_ED_API)\s+", "", decl) decl = decl.replace("__attribute__((weak))", "").strip() if decl.startswith("typedef") and "(" not in decl: m = re.match(r"typedef\s+(struct|enum|union)\s+(\w+)\s+(\w+);", decl) if m: items.append(("type", "%s %s" % (m.group(1), m.group(3)), doc)) else: items.append(("type", decl.rstrip(";"), doc)) continue if decl.startswith("typedef"): items.append(("type", decl.rstrip(";"), doc)) continue if "(" in decl: items.append(("func", decl.rstrip(";").strip(), doc)) return items def esc(s): return s.replace("|", "\\|") out = [] w = out.append w("# Referência da API (métodos)") w("") w("Gerada a partir dos headers: cada função, tipo e constante pública, com o") w("comentário que está no próprio header. As seções seguem os comentários de") w("seção dos headers (`/* -- ... --- */`). Para entender como as peças se") w("encaixam, leia antes [arquitetura.md](arquitetura.md), [tipos.md](tipos.md)") w("e [libraries.md](libraries.md).") w("") w("Convenções que valem para toda a API:") w("") w("- `TB_API` marca o que é exportado (`visibility(\"default\")`); as libraries") w(" compilam com `-fvisibility=hidden`, então só isso aparece no `.so`.") w("- Funções que devolvem `char*` alocam com `malloc`: libere com `free`, salvo") w(" quando o comentário diz \"estático\" ou \"emprestado\".") w("- `*_last_error()` devolve a mensagem do último erro daquela library.") w("- Regras de posse dos valores: [tipos.md](tipos.md#regras-de-posse-ownership).") w("- Headers marcados **privado** só compilam com a macro indicada (API interna).") w("") hs = headers() w("## Índice") w("") for h in hs: w("- [`%s`](#%s)" % (h, re.sub(r"[^a-z0-9 _-]", "", h.lower()).replace(" ", "-"))) w("") nf = nt = 0 for h in hs: src = open(os.path.join(root, h), encoding="utf-8").read() w("## %s" % h) w("") priv = re.search(r"#ifndef (TB_[A-Z_]*PRIVATE_API)", src) if priv: w("**Privado**: compile com `-D%s`." % priv.group(1)) w("") tc = top_comment(src) if tc: w("```text") w(tc) w("```") w("") items = parse(src) funcs_open = False def close(): global funcs_open if funcs_open: w("") funcs_open = False for it in items: if it[0] == "section": if funcs_open: w("") funcs_open = False w("### %s" % it[1]) w("") continue if not funcs_open: w("| Declaração | Descrição |") w("|---|---|") funcs_open = True if it[0] == "func": nf += 1 w("| `%s` | %s |" % (esc(it[1]), esc(fill("func", it[1], it[2])))) elif it[0] == "type": nt += 1 w("| tipo `%s` | %s |" % (esc(it[1]), esc(fill("type", it[1], it[2])))) elif it[0] == "macro": val = (" = `%s`" % esc(it[2])) if it[2] and len(it[2]) < 60 else "" w("| `#define %s`%s | %s |" % (esc(it[1]), val, esc(fill("macro", it[1], it[3])))) if funcs_open: w("") open(out_path, "w", encoding="utf-8").write("\n".join(out) + "\n") print(len(hs), "headers,", nf, "funcoes,", nt, "tipos")