From ef06203a105f2852cede7df01bd936808ad6cdbf Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:07 +0200 Subject: [PATCH 1/7] feat(backend): add shared C-family tree-sitter helpers Declarator names, parameters, comment blocks above a node and #include resolution read the same way in C and C++, so they live in one module the C plugin uses now and a C++ plugin can reuse later. --- backend/languages/cfamily.py | 346 +++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 backend/languages/cfamily.py diff --git a/backend/languages/cfamily.py b/backend/languages/cfamily.py new file mode 100644 index 0000000..4b6d0eb --- /dev/null +++ b/backend/languages/cfamily.py @@ -0,0 +1,346 @@ +"""tree-sitter helpers shared by the C and C++ language plugins. + +C and C++ are separate plugins (separate Languages, badges and highlighting), +but they read the same declarator syntax, the same comment conventions and +the same `#include` directives. Everything here works on a plain tree-sitter +tree and knows nothing about either plugin's resolution rules, so the C++ +plugin can reuse it unchanged. +""" + +from __future__ import annotations + +import posixpath +import re +from collections.abc import Iterator + +from tree_sitter import Node + +# Nodes a top-level walk looks through to reach more top-level items: every +# preprocessor conditional branch is read (nothing is preprocessed), and +# `extern "C" { ... }` is just a wrapper around declarations. A plugin that +# also reads namespaces extends this set. +TRANSPARENT_TYPES = frozenset( + { + "preproc_if", + "preproc_ifdef", + "preproc_else", + "preproc_elif", + "preproc_elifdef", + "linkage_specification", + "declaration_list", + } +) + +# A declarator that names the thing declared (as opposed to wrapping another declarator). +_NAME_TYPES = frozenset({"identifier", "field_identifier", "qualified_identifier", "destructor_name", "operator_name"}) +_WRAPPER_TYPES = frozenset( + { + "pointer_declarator", + "reference_declarator", + "array_declarator", + "function_declarator", + "parenthesized_declarator", + "attributed_declarator", + "init_declarator", + } +) + + +def node_text(node: Node | None, source: bytes) -> str: + if node is None: + return "" + return source[node.start_byte : node.end_byte].decode("utf-8", "replace") + + +def prepare_source(source: str) -> str: + """Drops a leading byte-order mark, which would otherwise be parsed as part of the first token, and + ends the file with a newline, without which a last-line `#include` is reported as a parse error. + """ + source = source[1:] if source.startswith("\ufeff") else source + return source if source.endswith("\n") else source + "\n" + + +def split_lines(source: str) -> list[str]: + """Lines indexed the way tree-sitter rows are: split on "\\n" only. + + `str.splitlines()` would also split on form feeds (common in GNU C + sources) and shift every later row off by one. + """ + return [line[:-1] if line.endswith("\r") else line for line in source.split("\n")] + + +def walk_top_level(node: Node, transparent: frozenset[str] = TRANSPARENT_TYPES) -> Iterator[Node]: + """Every top-level item under `node`, looking through preprocessor branches and linkage blocks.""" + for child in node.children: + if child.type in transparent: + yield from walk_top_level(child, transparent) + else: + yield child + + +# -- declarators -- + + +def declarator_name_node(declarator: Node | None) -> Node | None: + """The identifier a declarator declares: `*dup(...)` -> `dup`, `(*cb)(int)` -> `cb`, `a[10]` -> `a`.""" + while declarator is not None: + if declarator.type in _NAME_TYPES: + return declarator + if declarator.type not in _WRAPPER_TYPES: + return None + inner = declarator.child_by_field_name("declarator") + if inner is None: + # attributed_declarator and parenthesized_declarator carry the inner one as an unnamed child + inner = next((c for c in declarator.named_children if c.type in _NAME_TYPES or c.type in _WRAPPER_TYPES), None) + declarator = inner + return None + + +def declarator_name(declarator: Node | None, source: bytes) -> str | None: + return node_text(declarator_name_node(declarator), source) or None + + +def function_declarator_of(declarator: Node | None) -> Node | None: + """The `function_declarator` in a definition's declarator chain (`*dup(...)` wraps one in a pointer).""" + while declarator is not None: + if declarator.type == "function_declarator": + return declarator + if declarator.type not in _WRAPPER_TYPES: + return None + declarator = declarator.child_by_field_name("declarator") + return None + + +def declares_function(declarator: Node | None) -> bool: + """Whether a declarator declares a function (`int foo(int)`) rather than a variable that holds one + (`int (*foo)(int)`): the function declarator sits directly on the name, not on a parenthesized pointer. + """ + fn_declarator = function_declarator_of(declarator) + if fn_declarator is None: + return False + inner = fn_declarator.child_by_field_name("declarator") + return inner is not None and inner.type in _NAME_TYPES + + +def pointer_depth(declarator: Node | None) -> int: + """How many `*` wrap the function declarator in a definition's declarator (`char *f()` -> 1).""" + depth = 0 + while declarator is not None and declarator.type != "function_declarator": + if declarator.type == "pointer_declarator": + depth += 1 + elif declarator.type not in _WRAPPER_TYPES: + break + declarator = declarator.child_by_field_name("declarator") + return depth + + +# -- signatures -- + + +def _collapse(text: str) -> str: + return re.sub(r"\s+", " ", text).strip() + + +def extract_params(fn_declarator: Node | None, source: bytes) -> list[dict]: + """A function declarator's parameters as {"name", "annotation", "default"}, with the C type as the annotation. + + `(void)` is no parameters; `...` is a parameter named `...`; an old-style `f(a, b)` name list is kept as names. + """ + params_node = fn_declarator.child_by_field_name("parameters") if fn_declarator is not None else None + params: list[dict] = [] + if params_node is None: + return params + for child in params_node.named_children: + if child.type == "parameter_declaration": + name_node = declarator_name_node(child.child_by_field_name("declarator")) + if name_node is None: + text = _collapse(node_text(child, source)) + if text == "void" and len(params_node.named_children) == 1: + continue + params.append({"name": text, "annotation": None, "default": None}) + continue + # the type is everything in the parameter except the name itself + start = name_node.start_byte - child.start_byte + end = name_node.end_byte - child.start_byte + raw = source[child.start_byte : child.end_byte] + annotation = _collapse((raw[:start] + raw[end:]).decode("utf-8", "replace")) + params.append({"name": node_text(name_node, source), "annotation": annotation or None, "default": None}) + elif child.type == "variadic_parameter": + params.append({"name": "...", "annotation": None, "default": None}) + elif child.type == "identifier": + params.append({"name": node_text(child, source), "annotation": None, "default": None}) + return params + + +def param_names(fn_declarator: Node | None, source: bytes) -> set[str]: + """The names a function's parameters bind (for telling an indirect call from a direct one).""" + return {p["name"] for p in extract_params(fn_declarator, source) if p["name"] != "..."} + + +def return_type(fn_node: Node, source: bytes) -> str | None: + """A definition's return type as written: qualifiers, the type, then one `*` per pointer level.""" + type_node = fn_node.child_by_field_name("type") + if type_node is None: + return None + qualifiers = [node_text(c, source) for c in fn_node.children if c.type == "type_qualifier"] + text = _collapse(" ".join([*qualifiers, node_text(type_node, source)])) + stars = pointer_depth(fn_node.child_by_field_name("declarator")) + return f"{text} {'*' * stars}" if stars else text + + +def is_static(fn_node: Node, source: bytes) -> bool: + return any(c.type == "storage_class_specifier" and node_text(c, source) == "static" for c in fn_node.children) + + +def local_names(body: Node, source: bytes) -> set[str]: + """Every variable a function body declares, in any block: `int n`, `void (*cb)(int) = f`, `for (int i...)`. + + A prototype declared inside the body (`int helper(int);`) names a function, not a variable, so it is left out. + """ + names: set[str] = set() + stack = [body] + while stack: + node = stack.pop() + if node.type == "declaration": + for declarator in node.children_by_field_name("declarator"): + inner = declarator.child_by_field_name("declarator") if declarator.type == "init_declarator" else declarator + if inner is None or declares_function(inner): + continue + name = declarator_name(inner, source) + if name: + names.add(name) + stack.extend(node.children) + return names + + +# -- comments -- + + +def _strip_line_comment(text: str) -> str: + text = text.strip() + for marker in ("///", "//!", "//"): + if text.startswith(marker): + return text[len(marker) :].strip() + return text + + +def _strip_block_comment(text: str) -> str: + text = text.strip() + if text.startswith("/*"): + text = text[2:] + if text.endswith("*/"): + text = text[:-2] + if text[:1] in ("*", "!"): # the second marker character of /** and /*! + text = text[1:] + lines = [] + for line in text.split("\n"): + line = line.strip() + if line.startswith("*"): # the decoration column of a block comment + line = line[1:] + lines.append(line.strip()) + return "\n".join(lines).strip() + + +def strip_comment_markers(text: str) -> str: + """A comment's text with `//`, `///`, `/*`, `/**`, `*/` and a block's leading `*` column removed.""" + return _strip_block_comment(text) if text.lstrip().startswith("/*") else _strip_line_comment(text) + + +def comment_block_above(node: Node, source: bytes, source_lines: list[str]) -> str | None: + """The contiguous block of own-line comments directly above `node`, markers stripped, or None. + + "Directly above" means no blank line, preprocessor line or code between the comment and the node; "own-line" + means nothing else shares the comment's first line, so `int x; // note` never documents what follows it. + """ + comments: list[Node] = [] + expected_row = node.start_point[0] - 1 + sibling = node.prev_sibling + while sibling is not None and sibling.type == "comment": + row = sibling.start_point[0] + own_line = source_lines[row][: sibling.start_point[1]].strip() == "" + if sibling.end_point[0] != expected_row or not own_line: + break + comments.append(sibling) + expected_row = row - 1 + sibling = sibling.prev_sibling + if not comments: + return None + comments.reverse() + text = "\n".join(strip_comment_markers(node_text(c, source)) for c in comments).strip() + return text or None + + +# -- #include -- + + +def quoted_includes(root: Node, source: bytes) -> list[str]: + """The paths of every `#include "..."` in a file, in order; `` and macro includes are skipped.""" + paths: list[str] = [] + for node in walk_top_level(root): + if node.type != "preproc_include": + continue + path = node.child_by_field_name("path") + if path is not None and path.type == "string_literal": + paths.append(node_text(path, source).strip('"').replace("\\", "/")) + return paths + + +def resolve_include(includer: str, include: str, loaded: set[str], by_suffix: dict[str, list[str]]) -> str | None: + """Maps a quoted include to a loaded file, or None. + + The path is tried against the including file's directory first, as a compiler does, then against the + picked root; failing that, a path suffix that exactly one loaded file ends with stands in for the `-I` + directories (which are not read). + """ + if include.startswith("/"): + return None + relative = posixpath.normpath(posixpath.join(posixpath.dirname(includer), include)) + if relative in loaded: + return relative + normalized = posixpath.normpath(include) + if normalized in loaded: + return normalized + matches = by_suffix.get(normalized, []) + return matches[0] if len(matches) == 1 else None + + +def suffix_index(paths: set[str]) -> dict[str, list[str]]: + """Every trailing path of every file ("a/b/c.h" -> "c.h", "b/c.h", "a/b/c.h") -> the files that end that way.""" + index: dict[str, list[str]] = {} + for path in paths: + parts = path.split("/") + for i in range(len(parts)): + index.setdefault("/".join(parts[i:]), []).append(path) + return index + + +def reached_files(start: str, direct_includes: dict[str, list[str]]) -> list[str]: + """Every file reachable from `start` through quoted includes, transitively, nearest first. + + `start` itself is left out, even when an include cycle leads back to it. + """ + seen = {start} + order: list[str] = [] + queue = [start] + while queue: + current = queue.pop(0) + for included in direct_includes.get(current, []): + if included not in seen: + seen.add(included) + order.append(included) + queue.append(included) + return order + + +# -- code body -- + + +def make_code_lines(source_lines: list[str], start_line: int, end_line: int) -> list[dict]: + """A function's source lines (1-based, inclusive) as card lines, de-indented by the first line's indent.""" + raw = source_lines[start_line - 1 : end_line] + indent = len(raw[0]) - len(raw[0].lstrip()) if raw else 0 + code_lines = [] + for i, line in enumerate(raw): + text = line[indent:] if line[:indent].strip() == "" else line + code_lines.append({"lineno": start_line + i, "text": text, "calls": []}) + return code_lines From efa35362d73644dee45bd861900c90964666cf07 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:07 +0200 Subject: [PATCH 2/7] feat(backend): add C language plugin Reads .c and .h with tree-sitter-c. Only definitions are Functions. Calls resolve by name in C's own visibility order (same file, quoted #include chain and the implementing .c file, then the one non-static definition), and two or more candidates mean no wire rather than a guess. --- backend/languages/__init__.py | 3 +- backend/languages/c.py | 300 ++++++++++++++++++++++++++++++++++ backend/requirements.txt | 1 + 3 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 backend/languages/c.py diff --git a/backend/languages/__init__.py b/backend/languages/__init__.py index 6ae33ed..cb60bfe 100644 --- a/backend/languages/__init__.py +++ b/backend/languages/__init__.py @@ -9,11 +9,12 @@ from __future__ import annotations from .base import SKIP_DIRS, LanguagePlugin +from .c import CLanguage from .python import PythonLanguage from .rust import RustLanguage from .typescript import TypeScriptLanguage -LANGUAGES: list[LanguagePlugin] = [PythonLanguage(), RustLanguage(), TypeScriptLanguage()] +LANGUAGES: list[LanguagePlugin] = [PythonLanguage(), RustLanguage(), TypeScriptLanguage(), CLanguage()] EXTENSION_TO_LANGUAGE: dict[str, LanguagePlugin] = {ext: lang for lang in LANGUAGES for ext in lang.extensions} diff --git a/backend/languages/c.py b/backend/languages/c.py new file mode 100644 index 0000000..25bee87 --- /dev/null +++ b/backend/languages/c.py @@ -0,0 +1,300 @@ +"""C language plugin: tree-sitter-based analysis of C source trees. + +Owns `.c` and `.h` (until C++ lands, a header is always C). Nothing is +preprocessed or compiled: the plugin reads the text of each file as written, +and resolves calls by name, following the way a C program's names are +actually visible. + +Functions are definitions only, a function with a body. A prototype in a +header is not a Function, though its comment can document one (below). +`qualname` is the function name, `module` is the file path without its +extension, and the id is `::`, with `#2`, `#3` appended to +further same-named definitions in one file (the branches of an `#ifdef`). + +The contiguous own-line comment block directly above a definition (`//`, +`///`, `/* */`, `/** */`) is its docstring, markers stripped, and is not part +of its code body. A definition with no such comment takes the one above its +prototype in a quoted-included header instead. + +A call `foo()` resolves in this order, and stops at the first step that finds +any candidate: (1) a definition in the same file, static or not; (2) a +definition in a file reached through quoted `#include "..."` (transitively), +or in the `.c` file implementing one of those headers (same file stem, the +header's own directory first; non-static only); (3) the one non-static +definition of the name anywhere in the picked root. Two or more candidates at +the step that finds them mean no edge: the plugin never picks arbitrarily. +`` includes are ignored. An include path is tried against the +including file's directory, then the picked root, then by a path suffix that +exactly one loaded file ends with (standing in for the unread `-I` paths). +A `static` function is visible only in its own file, except one defined in an +included header (`static inline`), which the including files can call. A call +whose name is a parameter or a local variable is an indirect call and is +never linked, even when a function of that name is loaded. + +Real limits: nothing is preprocessed, so a function defined by a macro is not +a Function and a call hidden in a macro body is invisible; every `#ifdef` +branch is parsed, whether or not it would be compiled; function-pointer calls +(`cb(x)`, `s->handler(x)`, `tbl[i](x)`) are not linked; and a file tree-sitter +cannot fully parse (macro-heavy code such as zlib's) is flagged with an error +but keeps whatever functions were recovered from it. +""" + +from __future__ import annotations + +import posixpath +import tree_sitter_c +from dataclasses import dataclass, field +from tree_sitter import Language, Node, Parser + +from .base import FunctionInfo, LanguagePlugin, build_edges, dedupe_calls +from .cfamily import ( + comment_block_above, + declarator_name, + declares_function, + extract_params, + function_declarator_of, + is_static, + local_names, + make_code_lines, + node_text, + param_names, + prepare_source, + quoted_includes, + reached_files, + resolve_include, + return_type, + split_lines, + suffix_index, + walk_top_level, +) + +_C_LANGUAGE = Language(tree_sitter_c.language()) + + +@dataclass +class _CFile: + rel_path: str # forward slashes + module: str # the path without its extension + source: bytes + lines: list[str] + include_paths: list[str] = field(default_factory=list) # the quoted paths as written + definitions: dict[str, list[str]] = field(default_factory=dict) # name -> function ids, in file order + prototype_docs: dict[str, str] = field(default_factory=dict) # name -> the comment above its first documented prototype + + +@dataclass +class _Pending: + node: Node + file: _CFile + ignored: set[str] # parameters and locals: a call through one of these is indirect + + +class _CAnalyzer: + def __init__(self, sources: dict[str, str]): + self.sources = sources + self.files: dict[str, _CFile] = {} + self.functions: dict[str, FunctionInfo] = {} + self.file_errors: dict[str, str] = {} + self.file_functions: dict[str, list[str]] = {} + self.static_ids: set[str] = set() + self.global_defs: dict[str, list[str]] = {} # name -> ids of its non-static definitions + self._pending: dict[str, _Pending] = {} # func id -> what pass 2 needs + self._reached: dict[str, list[str]] = {} + self._implementations: dict[str, list[str]] = {} # header path -> the .c files implementing it + self._resolved: dict[tuple[str, str], str | None] = {} + + def analyze(self) -> dict: + self._parse_files() + self._link_includes() + self._fill_missing_docstrings() + self._resolve_calls() + return self._to_response() + + # -- pass 1: parse everything, register definitions -- + + def _parse_files(self) -> None: + parser = Parser(_C_LANGUAGE) + for rel_path, raw in sorted(self.sources.items()): + self.file_functions.setdefault(rel_path, []) + source = prepare_source(raw) + source_bytes = source.encode("utf-8") + tree = parser.parse(source_bytes) + if tree.root_node.has_error: + self.file_errors[rel_path] = "SyntaxError: C source has one or more parse errors" + + module = posixpath.splitext(rel_path)[0] + cfile = _CFile(rel_path, module, source_bytes, split_lines(source)) + cfile.include_paths = quoted_includes(tree.root_node, source_bytes) + self.files[rel_path] = cfile + for node in walk_top_level(tree.root_node): + if node.type == "function_definition": + self._register_function(cfile, node) + elif node.type == "declaration": + self._register_prototypes(cfile, node) + + def _register_function(self, cfile: _CFile, fn_node: Node) -> None: + source = cfile.source + declarator = fn_node.child_by_field_name("declarator") + fn_declarator = function_declarator_of(declarator) + name = declarator_name(declarator, source) + if fn_declarator is None or name is None: + return # tree-sitter's recovery of something that is not a plain definition + + defined = cfile.definitions.setdefault(name, []) + func_id = f"{cfile.rel_path}::{name}" + if defined: + func_id += f"#{len(defined) + 1}" + defined.append(func_id) + + start_line = fn_node.start_point[0] + 1 + end_line = fn_node.end_point[0] + 1 + body = fn_node.child_by_field_name("body") + info = FunctionInfo( + id=func_id, + name=name, + qualname=name, + file=cfile.rel_path, + module=cfile.module, + class_name=None, + lineno=start_line, + end_lineno=end_line, + params=extract_params(fn_declarator, source), + returns=return_type(fn_node, source), + docstring=comment_block_above(fn_node, source, cfile.lines), + is_async=False, + code_lines=make_code_lines(cfile.lines, start_line, end_line), + ) + self.functions[func_id] = info + self.file_functions[cfile.rel_path].append(func_id) + if is_static(fn_node, source): + self.static_ids.add(func_id) + else: + self.global_defs.setdefault(name, []).append(func_id) + + ignored = param_names(fn_declarator, source) + if body is not None: + ignored |= local_names(body, source) + self._pending[func_id] = _Pending(fn_node, cfile, ignored) + + def _register_prototypes(self, cfile: _CFile, node: Node) -> None: + """Remembers the comment above each function prototype, to document a definition elsewhere.""" + doc = None + for declarator in node.children_by_field_name("declarator"): + if not declares_function(declarator): + continue + name = declarator_name(declarator, cfile.source) + if name is None or name in cfile.prototype_docs: + continue + doc = doc or comment_block_above(node, cfile.source, cfile.lines) + if doc: + cfile.prototype_docs[name] = doc + + # -- between the passes: what each file can see -- + + def _link_includes(self) -> None: + loaded = set(self.files) + by_suffix = suffix_index(loaded) + direct: dict[str, list[str]] = {} + for rel_path, cfile in self.files.items(): + resolved = (resolve_include(rel_path, path, loaded, by_suffix) for path in cfile.include_paths) + direct[rel_path] = [target for target in resolved if target is not None and target != rel_path] + self._reached = {rel_path: reached_files(rel_path, direct) for rel_path in self.files} + + stems = {rel_path: posixpath.splitext(posixpath.basename(rel_path)) for rel_path in self.files} + by_stem: dict[str, list[str]] = {} + for rel_path, (stem, ext) in stems.items(): + if ext == ".c": + by_stem.setdefault(stem, []).append(rel_path) + for rel_path, (stem, ext) in stems.items(): + if ext != ".h": + continue + candidates = by_stem.get(stem, []) + beside = [c for c in candidates if posixpath.dirname(c) == posixpath.dirname(rel_path)] + self._implementations[rel_path] = beside or candidates + + def _fill_missing_docstrings(self) -> None: + for info in self.functions.values(): + if info.docstring is not None: + continue + for included in self._reached[info.file]: + doc = self.files[included].prototype_docs.get(info.name) + if doc: + info.docstring = doc + break + + # -- pass 2: resolve calls -- + + def _resolve_calls(self) -> None: + for func_id, info in self.functions.items(): + pending = self._pending.pop(func_id) + body = pending.node.child_by_field_name("body") + found: list[tuple[int, str]] = [] + if body is not None: + stack = [body] + while stack: + node = stack.pop() + if node.type == "call_expression": + target = self._resolve_call(pending, node) + if target: + found.append((node.start_point[0] + 1, target)) + stack.extend(node.children) + dedupe_calls(info, found) + + def _resolve_call(self, pending: _Pending, call: Node) -> str | None: + func = call.child_by_field_name("function") + if func is None or func.type != "identifier": + return None # s->handler(x), tbl[i](x), (*fp)(x): function-pointer calls are not linked + name = node_text(func, pending.file.source) + if name in pending.ignored: + return None + return self._resolve_name(pending.file.rel_path, name) + + def _resolve_name(self, rel_path: str, name: str) -> str | None: + key = (rel_path, name) + if key not in self._resolved: + self._resolved[key] = self._lookup(rel_path, name) + return self._resolved[key] + + def _lookup(self, rel_path: str, name: str) -> str | None: + # (1) a definition in the same file, static or not + candidates = self.files[rel_path].definitions.get(name, []) + if candidates: + return candidates[0] if len(candidates) == 1 else None + + # (2) a definition in an included file, or non-static in the .c file implementing an included header + reached = self._reached[rel_path] + found: set[str] = set() + for included in reached: + found.update(self.files[included].definitions.get(name, [])) + for implementation in self._implementations.get(included, []): + if implementation != rel_path: + found.update(fid for fid in self.files[implementation].definitions.get(name, []) if fid not in self.static_ids) + if found: + return next(iter(found)) if len(found) == 1 else None + + # (3) the one non-static definition anywhere + candidates = self.global_defs.get(name, []) + return candidates[0] if len(candidates) == 1 else None + + # -- output -- + + def _to_response(self) -> dict: + edges = build_edges(self.functions) + files = [ + {"path": rel_path, "functions": ids, "error": self.file_errors.get(rel_path)} + for rel_path, ids in sorted(self.file_functions.items()) + ] + return { + "files": files, + "functions": {fid: info.to_dict() for fid, info in self.functions.items()}, + "edges": edges, + } + + +class CLanguage(LanguagePlugin): + id = "c" + label = "C" + extensions = frozenset({".c", ".h"}) + + def analyze(self, sources: dict[str, str]) -> dict: + return _CAnalyzer(sources).analyze() diff --git a/backend/requirements.txt b/backend/requirements.txt index 99c471b..586678e 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -3,3 +3,4 @@ uvicorn[standard]>=0.29 tree-sitter>=0.23 tree-sitter-rust>=0.23 tree-sitter-typescript>=0.23 +tree-sitter-c>=0.23 From ad8a537976082a6ae2a4b83c48e0e91995391191 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:07 +0200 Subject: [PATCH 3/7] feat(frontend): add C to the language registry and highlighting --- frontend/src/components/FunctionNode.tsx | 1 + frontend/src/languages.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/frontend/src/components/FunctionNode.tsx b/frontend/src/components/FunctionNode.tsx index 83fd8ed..939009e 100644 --- a/frontend/src/components/FunctionNode.tsx +++ b/frontend/src/components/FunctionNode.tsx @@ -3,6 +3,7 @@ import { Handle, Position, type NodeProps, type Node } from "@xyflow/react"; import Prism from "prismjs"; import "prismjs/components/prism-python"; import "prismjs/components/prism-rust"; +import "prismjs/components/prism-c"; import "prismjs/components/prism-typescript"; import "prismjs/components/prism-jsx"; import "prismjs/components/prism-tsx"; diff --git a/frontend/src/languages.ts b/frontend/src/languages.ts index 312d953..ff721d6 100644 --- a/frontend/src/languages.ts +++ b/frontend/src/languages.ts @@ -14,6 +14,8 @@ export interface LanguageDef { export const LANGUAGES: LanguageDef[] = [ { id: "python", label: "Python", extensions: [".py"], color: "#3776ab", mono: "PY" }, { id: "rust", label: "Rust", extensions: [".rs"], color: "#dea584", mono: "RS" }, + // A C definition always states its return type, so there is no "unannotated" case to show as None. + { id: "c", label: "C", extensions: [".c", ".h"], color: "#a8b9cc", mono: "C", unannotatedReturn: null }, // The superset grammars: they also cover JSX/TSX markup, and highlight plain code the same. // A missing return annotation there means "not stated", not "returns nothing". { From 3f514b616e31876c0d47e084c9d596714d210953 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:07 +0200 Subject: [PATCH 4/7] chore(frontend): name every supported language in the empty-state hints The hints still listed only Python and Rust, so TypeScript and JavaScript were missing before C joined them. --- frontend/src/components/GraphCanvas.tsx | 2 +- frontend/src/components/Sidebar.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/GraphCanvas.tsx b/frontend/src/components/GraphCanvas.tsx index 6ed4bd2..55d7ec6 100644 --- a/frontend/src/components/GraphCanvas.tsx +++ b/frontend/src/components/GraphCanvas.tsx @@ -348,7 +348,7 @@ export function GraphCanvas() {
⬡
Function Viewer
-
Load a Python or Rust file or folder from the sidebar to draw its call graph.
+
Load a Python, Rust, TypeScript, JavaScript or C file or folder from the sidebar to draw its call graph.
)} {error &&
{error}
} {!graph && !error && ( -
Pick a Python or Rust file or a folder from your computer, every function inside is analyzed and its calls to other loaded functions become wires.
+
Pick a Python, Rust, TypeScript, JavaScript or C file or a folder from your computer, every function inside is analyzed and its calls to other loaded functions become wires.
)} From 4fbfd40a26a7980e38ea2b9c595b448a90d1ff73 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:07 +0200 Subject: [PATCH 5/7] chore: add sample_c_project fixture Headers with prototypes and doc comments, a static helper, and a function-pointer parameter that must not draw a wire. --- sample_c_project/main.c | 27 +++++++++++++++++++++++++++ sample_c_project/models.c | 11 +++++++++++ sample_c_project/models.h | 18 ++++++++++++++++++ sample_c_project/processing.c | 30 ++++++++++++++++++++++++++++++ sample_c_project/processing.h | 13 +++++++++++++ sample_c_project/storage.c | 18 ++++++++++++++++++ sample_c_project/storage.h | 9 +++++++++ 7 files changed, 126 insertions(+) create mode 100644 sample_c_project/main.c create mode 100644 sample_c_project/models.c create mode 100644 sample_c_project/models.h create mode 100644 sample_c_project/processing.c create mode 100644 sample_c_project/processing.h create mode 100644 sample_c_project/storage.c create mode 100644 sample_c_project/storage.h diff --git a/sample_c_project/main.c b/sample_c_project/main.c new file mode 100644 index 0000000..9484f5b --- /dev/null +++ b/sample_c_project/main.c @@ -0,0 +1,27 @@ +#include +#include "models.h" +#include "processing.h" +#include "storage.h" + +static double square(double value) { + return value * value; +} + +/* Stand-in for reading a CSV; fills a fixed sample for the demo. */ +static int load_readings(double *readings) { + double sample[] = { 1.0, -2.0, 3.0, 4.0 }; + for (int i = 0; i < 4; i++) { + readings[i] = sample[i]; + } + return 4; +} + +/* Entry point of the sample pipeline. */ +int main(void) { + double readings[8]; + int count = load_readings(readings); + count = clean(readings, count); + apply(readings, count, square); + Report report = report_new("daily", aggregate(readings, count)); + return save_report(&report); +} diff --git a/sample_c_project/models.c b/sample_c_project/models.c new file mode 100644 index 0000000..069b5ae --- /dev/null +++ b/sample_c_project/models.c @@ -0,0 +1,11 @@ +#include +#include "models.h" + +Report report_new(const char *name, double mean) { + Report report = { name, mean }; + return report; +} + +void report_describe(const Report *report, char *out, int size) { + snprintf(out, size, "%s: mean=%.2f", report->name, report->mean); +} diff --git a/sample_c_project/models.h b/sample_c_project/models.h new file mode 100644 index 0000000..c4ff884 --- /dev/null +++ b/sample_c_project/models.h @@ -0,0 +1,18 @@ +#ifndef MODELS_H +#define MODELS_H + +typedef struct { + const char *name; + double mean; +} Report; + +/* Builds a report for a named series of readings. */ +Report report_new(const char *name, double mean); + +/** + * Renders a report as a single line of text. + * The result is written into `out`. + */ +void report_describe(const Report *report, char *out, int size); + +#endif diff --git a/sample_c_project/processing.c b/sample_c_project/processing.c new file mode 100644 index 0000000..3047d62 --- /dev/null +++ b/sample_c_project/processing.c @@ -0,0 +1,30 @@ +#include "processing.h" + +// Readings above this are treated as sensor glitches. +static double clamp(double value) { + return value > 1000.0 ? 1000.0 : value; +} + +int clean(double *readings, int count) { + int kept = 0; + for (int i = 0; i < count; i++) { + if (readings[i] >= 0.0) { + readings[kept++] = clamp(readings[i]); + } + } + return kept; +} + +double aggregate(const double *readings, int count) { + double total = 0.0; + for (int i = 0; i < count; i++) { + total += readings[i]; + } + return count ? total / count : 0.0; +} + +void apply(double *readings, int count, double (*transform)(double)) { + for (int i = 0; i < count; i++) { + readings[i] = transform(readings[i]); + } +} diff --git a/sample_c_project/processing.h b/sample_c_project/processing.h new file mode 100644 index 0000000..f26643f --- /dev/null +++ b/sample_c_project/processing.h @@ -0,0 +1,13 @@ +#ifndef PROCESSING_H +#define PROCESSING_H + +/// Drops negative readings in place and returns how many are left. +int clean(double *readings, int count); + +// Arithmetic mean of the readings; 0 when there are none. +double aggregate(const double *readings, int count); + +/* Applies `transform` to every reading. Calls made through the pointer are not wired. */ +void apply(double *readings, int count, double (*transform)(double)); + +#endif diff --git a/sample_c_project/storage.c b/sample_c_project/storage.c new file mode 100644 index 0000000..bb73fbc --- /dev/null +++ b/sample_c_project/storage.c @@ -0,0 +1,18 @@ +#include +#include "storage.h" + +static const char *output_path(void) { + return "report.txt"; +} + +int save_report(const Report *report) { + char line[128]; + FILE *file = fopen(output_path(), "w"); + if (file == NULL) { + return -1; + } + report_describe(report, line, sizeof line); + fprintf(file, "%s\n", line); + fclose(file); + return 0; +} diff --git a/sample_c_project/storage.h b/sample_c_project/storage.h new file mode 100644 index 0000000..c1f6d5d --- /dev/null +++ b/sample_c_project/storage.h @@ -0,0 +1,9 @@ +#ifndef STORAGE_H +#define STORAGE_H + +#include "models.h" + +/* Writes a report to the sample output file. */ +int save_report(const Report *report); + +#endif From 541a458d2369d3722bf870b4f5c39d11c66d4ff3 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sat, 10 Oct 2026 10:55:08 +0200 Subject: [PATCH 6/7] docs: document C support in the README and verification steps Closes #33 --- CLAUDE.md | 2 +- README.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4ae5a9e..8c75eea 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ There is **no test suite**. Verify by hand: - Frontend: `docker compose exec frontend npm run build` and `docker compose exec frontend npm run lint` (or run them in `frontend/` without Docker). - Backend: with `docker compose up` running, `GET localhost:8000/api/health`. -- Analyzer or language-plugin changes: `docker compose exec backend python -m backend.analyzer ` on `sample_project`, `sample_rust_project` and `sample_typescript_project` before and after, and compare function and edge counts. An unexplained drop in edges is a regression. +- Analyzer or language-plugin changes: `docker compose exec backend python -m backend.analyzer ` on `sample_project`, `sample_rust_project`, `sample_typescript_project` and `sample_c_project` before and after, and compare function and edge counts. An unexplained drop in edges is a regression. CI (`.github/workflows/pr-checks.yml`) only runs the frontend build and the backend health check. It does not lint and does not exercise the analyzer, so green CI says little about analysis correctness. diff --git a/README.md b/README.md index 2ace2b2..7b5284d 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ The goal is to make the flow of a codebase visible instead of jumping between fi | Rust | `.rs` | | TypeScript | `.ts`, `.tsx`, `.mts`, `.cts` | | JavaScript | `.js`, `.jsx`, `.mjs`, `.cjs` | +| C | `.c`, `.h` | More languages can be added without touching the frontend - see [Backend](#backend) below. @@ -45,7 +46,7 @@ npm install npm run dev ``` -Open http://localhost:5173 and load a folder or file from the sidebar. Try `sample_project` (Python), `sample_rust_project` (Rust) or `sample_typescript_project` (TypeScript and JavaScript) for a quick demo. +Open http://localhost:5173 and load a folder or file from the sidebar. Try `sample_project` (Python), `sample_rust_project` (Rust), `sample_typescript_project` (TypeScript and JavaScript) or `sample_c_project` (C) for a quick demo. ## Codebase @@ -55,6 +56,7 @@ frontend/src/ React 19 + React Flow + Zustand, the UI sample_project/ Python demo fixture used for manual testing sample_rust_project/ Rust demo fixture used for manual testing sample_typescript_project/ TypeScript + JavaScript demo fixture used for manual testing +sample_c_project/ C demo fixture used for manual testing ``` ### Backend @@ -64,6 +66,7 @@ sample_typescript_project/ TypeScript + JavaScript demo fixture used for manual - `python.py`: parses with the stdlib `ast`. - `rust.py`: parses with `tree-sitter` + `tree-sitter-rust` (functions, `impl` methods, `use`-based and bare-path module resolution). Calls made inside a macro invocation (`println!`, `format!`, ...) aren't visible to it - macro arguments are an opaque token stream, not parsed expressions. - `typescript.py`: one plugin for TypeScript and JavaScript, parsed with `tree-sitter` + `tree-sitter-typescript` (the `typescript` grammar for `.ts`, `.tsx` for everything else). It stamps each file with its own language, so a `.ts` file and a `.js` file get their own badge but can call each other. Reads ESM and basic CommonJS imports, resolves relative specifiers and (by unique path suffix) aliases, and ignores `.d.ts` and minified files. There's no separate "JS mode": a missing annotation is just a missing annotation. Its docstring lists exactly what it resolves and what it can't (JSX elements, inheritance, dynamic calls, ...). + - `c.py` (with `cfamily.py`, tree-sitter helpers meant to be shared with a C++ plugin): parses with `tree-sitter` + `tree-sitter-c` and owns `.c` and `.h`. Only definitions are Functions; a prototype in a header never is, but its comment documents a definition that has none. Calls are resolved by name in C's own visibility order: the same file, then files reached through quoted `#include "..."` (and the `.c` file implementing an included header), then the one non-static definition anywhere in the picked folder. A `static` function is visible only in its own file, and two or more candidates mean no wire rather than a guess. Nothing is preprocessed or compiled, so functions defined by macros aren't Functions, calls hidden in macro bodies are invisible, every `#ifdef` branch is parsed, and function-pointer calls (`cb(x)`, `s->handler(x)`) aren't linked, including a call through a parameter or local variable named like a loaded function. A file tree-sitter can't fully parse is flagged but keeps the functions it recovered. - `main.py`: the FastAPI app. `GET /api/browse` powers the server-side folder picker, `POST /api/analyze` runs the analyzer and returns the graph as JSON. Also serves the built frontend in production. ### Frontend From 715922ffa760c5b215c8504ba33c45d2531702b9 Mon Sep 17 00:00:00 2001 From: MCR-3 Date: Sun, 11 Oct 2026 09:59:31 +0200 Subject: [PATCH 7/7] fix(backend): list C calls in source order The call collector walked each body with a stack and popped children last-first, so a function's calls came out in reverse source order. The canvas stacks callee cards in that order, which put them upside down and made every wire from a caller cross the others. Push children reversed so the walk visits them in source order, as the Rust plugin's recursion does. --- backend/languages/c.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/languages/c.py b/backend/languages/c.py index 25bee87..b7d65df 100644 --- a/backend/languages/c.py +++ b/backend/languages/c.py @@ -237,7 +237,7 @@ def _resolve_calls(self) -> None: target = self._resolve_call(pending, node) if target: found.append((node.start_point[0] + 1, target)) - stack.extend(node.children) + stack.extend(reversed(node.children)) # so calls come out in source order dedupe_calls(info, found) def _resolve_call(self, pending: _Pending, call: Node) -> str | None: