Repository navigation
Description
Summary
tree-sitter-cpp does not parse a macro sitting between class/struct and the type name, which is how module and DLL-export headers usually spell a type:
class MODULE_API Widget : public BaseWidgetThe ERROR node lands on the type header and dissolves the whole class body. graphify emits no class node, no inherits edge and no defines edge for any field or method of that type. Recovery also invents a phantom node named after the base class, so the loss is silent: the file is not reported as a syntax error and the graph merely looks small.
For a codebase where every public type carries such a macro, that means almost the entire C++ layer is missing while the graph still looks healthy.
Minimal repro
Two files, identical except for the macro. b.h is the control.
a.h:
#pragma once
class MODULE_API Widget : public BaseWidget
{
public:
float Threshold = 0.2f;
void Apply();
};b.h: the same file with MODULE_API replaced by the same number of spaces.
from pathlib import Path
from graphify.extract import extract_cpp
for name in ("a.h", "b.h"):
out = extract_cpp(Path(name))
print(name, len(out["nodes"]), "nodes", len(out["edges"]), "edges")Result on 0.9.62 and 0.9.63:
a.h 2 nodes 2 edges <- no Widget, no inherits, no members; one phantom node named BaseWidget
b.h 5 nodes 5 edges <- Widget, inherits BaseWidget, Threshold, Apply
How general is it
Measured with the same pair of files, varying one thing at a time:
| variant | affected |
|---|---|
class MODULE_API Widget : public BaseWidget |
yes |
class ANYTHING_EXPORT Widget : public BaseWidget (any all-caps macro, _API suffix not required) |
yes |
struct MODULE_API Payload |
yes |
| base clause on the following line | yes |
the same class defined in a .cpp file |
yes |
class MODULE_API Widget; (forward declaration) |
one mislabelled node, class body unaffected |
Environment
- graphify 0.9.62 and 0.9.63 (latest at the time of writing) behave identically. The C++/CLI normalization region of
extract.pyis byte-identical between them, neither release note mentions C++ parsing or export macros, and neither ships any export-macro handling, so upgrading does not help. - Python 3.11, tree-sitter 0.25.2, tree-sitter-cpp 0.23.4.
Proposed fix
One regex, in the style of the existing _normalize_cpp_cli hook and under the same byte-length-preserving contract: the macro is overwritten with spaces rather than deleted, so every offset, line and column still points at the same place in the file on disk and reported source locations stay accurate.
The lookahead requires the type header to continue into a base clause or a body (: or {, possibly after a newline). That is what keeps the rewrite safe against class MYTYPE globalThing; — an elaborated-type-specifier variable declaration in which the all-caps token really is the type name; verified unchanged with the patch applied.
--- a/graphify/extract.py
+++ b/graphify/extract.py
@@ -2506,6 +2506,32 @@
return _CPP_CLI_ATTR_RE.sub(_blank_keeping_newlines, out)
+# -- Export macros in type headers -------------------------------------------
+# `class MODULE_API Foo : public Bar` (module/DLL export macros) is not in
+# tree-sitter-cpp's grammar: the ERROR lands on the type header and dissolves
+# the whole class body, so the class, its `inherits` edge and every member are
+# lost, and recovery invents a phantom node named after the base class.
+#
+# The macro is an ALL-CAPS identifier between `class`/`struct` and the type
+# name. The lookahead requires the header to continue into a base clause or a
+# body, which is what separates a macro from `class MYTYPE globalThing;` -- an
+# elaborated-type variable declaration where the ALL-CAPS token is the type.
+# Blanked with spaces, never deleted, the same contract as _normalize_cpp_cli
+# above, so offsets, lines and columns all stay accurate.
+_CPP_EXPORT_MACRO_RE = re.compile(
+ rb"(\b(?:class|struct)[ \t]+)([A-Z][A-Z0-9_]*)"
+ rb"(?=[ \t]+[A-Za-z_][A-Za-z0-9_]*[ \t\r\n]*[:{])"
+)
+
+
+def _normalize_cpp_export_macros(source: bytes) -> bytes:
+ """Blank an export macro between ``class``/``struct`` and the type name."""
+ return _CPP_EXPORT_MACRO_RE.sub(
+ lambda m: m.group(1) + b" " * len(m.group(2)), source
+ )
+
+
def extract_cpp(path: Path) -> dict:
"""Extract functions, classes, and includes from a .cpp/.cc/.cxx/.hpp file.
@@ -2521,7 +2547,11 @@
# Let _extract_generic report the read failure in its usual shape.
return _augment_cpp_string_tests(path, _extract_generic(path, _CPP_CONFIG))
result = _extract_generic(
- path, _CPP_CONFIG, source_override=_normalize_cpp_cli(source) or source
+ path,
+ _CPP_CONFIG,
+ source_override=_normalize_cpp_export_macros(
+ _normalize_cpp_cli(source) or source
+ ),
)
return _augment_cpp_string_tests(path, result)Known limitation, deliberately left out: a forward declaration class MODULE_API Widget; has no : or {, so it is not matched and still produces one node mislabelled after the macro. class MODULE_API Widget; and class MYTYPE var; are lexically identical, so no parser without a preprocessor can tell them apart. If you want that case covered, the safe form is a second, narrower pattern restricted to export-shaped names, e.g. [A-Z][A-Z0-9_]*(?:_API|_EXPORT|_EXPORTS|_DLL|_IMPORT)\b followed by an identifier. Getting a forward declaration wrong costs one junk node; the definition case above loses an entire type layer, which is why the minimal fix targets definitions only.
Secondary issue found in the same pass: a long reflection-macro payload swallows the declaration after it
Reflection frameworks put an annotation macro in front of each member. When its argument list grows past a certain size, the member declaration behind it disappears too.
Minimal repro, one member per variant:
ANNOTATE(meta=(A="a",B="b",C="c")) float X=1.f; // X missing
ANNOTATE(meta=(A="a",B="b")) float X=1.f; // X presenttree-sitter-cpp parses the annotation as a function_declarator and must error-recover. With a small payload it inserts MISSING ";" after the macro and float X=1.f; parses as a field_declaration. With a larger payload the cheaper recovery is MISSING ")" inside the nested meta=(; the remaining pairs are absorbed as macro parameters and the declaration lands in an ERROR node, so no field node is emitted.
Because the recovery choice is cost-driven, the flip point is not a fixed length (observed between roughly 450 and 1400 characters of line), so two neighbouring, near-identical declarations can differ in outcome — which makes the gap look random rather than systematic.
Not the cause: the member type, the specifier set, display-name keys, leading-dot float literals (=.20f), parentheses or apostrophes inside quoted text, preceding comments, or a preceding failing declaration. Numeric payload values (meta=(A=1,B=2,C=3)) parse fine.
Candidate fix, same contract as above: blank the entire annotation argument list with spaces before parsing, using string-aware parenthesis matching, since quoted help text commonly contains unbalanced parentheses. The payload carries no graph information. Tried locally alongside the export-macro fix, this recovered every affected declaration except one that fails for an unrelated reason (a templated container field), and changed nothing else in the graph.
Impact, in general terms
On a mid-size C++ module where every public type carries an export macro and members carry annotation macros, the two fixes together took the extracted header symbols up roughly fivefold, multiplied the recorded field relationships by about four and nearly doubled the call relationships — from a graph that looked complete but held almost no C++ structure. A regression check against the previous graph found nothing that had become unfindable.
Happy to open a PR with either fix plus fixtures for class/struct, .h/.cpp, the multi-line base clause and the class MYTYPE globalThing; negative case, if that shape of fix is what you want.
Activity
nikhilsaxena04 commentedon Sep 18, 2026
Hi! 👋 I just opened a PR to address the primary export macro issue.
I used the exact _CPP_EXPORT_MACRO_RE regex proposed here to pad the macros with spaces before passing the code to tree-sitter-cpp. The fix is fully tested and cleanly prevents the class/inherits drops without altering byte-offsets.
(Note: I held off on implementing the secondary reflection macro fix for now. During testing, I noticed that naively stripping all-caps macros can cause severe regressions by dropping valid method calls like EXPECT_EQ(...) in the AST, so I wanted to keep this PR safe and focused on the core export macro bug.)
Let me know what you think of the approach!
nikhilsaxena04 commentedon Sep 18, 2026
Just pushed a clean update to address the two advisory findings flagged by the Graphify Bot verifier!
Unicode IDs: I replaced the
[^a-z0-9]+regex with[^\w]+in_id_prefixesinsidededup.py. Since\win Python 3 natively matches Unicode characters, this correctly preserves international characters (likeéorö) in node IDs while still slugifying punctuation as intended.C++ False Positives: I tightened the
_CPP_EXPORT_MACRO_REregex inextract.pyso that it only matches standard export macros (e.g., ending in_API,_EXPORT,_MACRO, or strictly matchingEXPORT/DLLAPI). This prevents it from accidentally blanking valid variable declarations that use ALL-CAPS types (likefor (class MYTYPE var: container)).Tests: Added regression tests in
test_cpp_nested_and_cli.pyto ensure variable declarations are no longer corrupted by the regex.fix(extract): preserve C++ classes behind export macros (#3661, #3648)
safishamsi commentedon Oct 6, 2026
Fixed by #3661 (thanks @nikhilsaxena04), shipped in v0.9.78. Closing as resolved.