Skip to content

fix(cpp): blank an export macro leading a function or variable declaration (#5550) - #5558

Closed
Deepjyoti-Sarmah wants to merge 2 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5550-cpp-export-decl-macro
Closed

Deepjyoti-Sarmah wants to merge 2 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5550-cpp-export-decl-macro

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5550. An export macro in front of a free function or variable
declaration breaks the C++ parse:

MYLIB_EXPORT uint64_t compute(int x);

tree-sitter-cpp has no rule for a bare macro before a return type. It reads
the macro as the type and the real type as an ERROR:

declaration  type: MYLIB_EXPORT  (ERROR: uint64_t)  declarator: compute(...)

That one misreading gives both symptoms from the issue. A prototype reports
had syntax errors ... no symbols extracted, and a definition gains a phantom
MYLIB_EXPORT node, because the macro became the return type.

_normalize_cpp_export_macros already blanks a macro between class/struct
and the type name (#3648/#3661). This adds a second pattern for the
declaration case and blanks the macro with spaces, so offsets, lines and
columns stay unchanged.

Why match by name

The parse tree cannot say which of two adjacent words is the macro.
DWORD WINAPI run(void*); gives the same tree, but there the second word is
the macro. So the pattern goes by the usual spelling, as the issue proposed:
an ALL-CAPS name ending in EXPORT or _API with a non-empty prefix,
followed by another identifier.

It is not limited to the start of a line. These shapes give the same broken
tree, and the line-start sketch in the issue missed them:

extern MYLIB_API int counter;
static MYLIB_API ... / inline MYLIB_API ...
namespace n {            (macro, type and name on separate lines)
MYLIB_EXPORT
uint64_t
compute(int x);
}

Left alone:

#define MYLIB_API __declspec(dllexport)   preprocessor line
class MODULE_API var2{1};                 word after class/struct/union/enum is a type name
DWORD WINAPI run(void*);                  neither word matches
EXPORT int g();                           no prefix

The class/struct/union/enum guard keeps
test_cpp_export_macro_does_not_break_variables passing. Without it the new
pattern blanked MODULE_API in class MODULE_API var2{1};, where it names
the type.

Two commits

30aa0c1c  fix(5550): blank a C++ export macro leading a function or variable declaration
410aa912  test(5550): pin C++ export macros on function and variable declarations

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

The invariant: a C++ export macro the compiler would remove adds no node and
no parse error, and normalization keeps every byte offset of the file.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Merge Danger

Door: two-way. _AST_CACHE_SCHEMA goes from 57 to 58, so cached
extractions re-run once after upgrade.

Blast radius: C++ files (.cpp/.cc/.cxx/.hpp) only. A definition
behind an export macro loses its phantom macro node. A file of such
prototypes loses its false syntax-error warning.

Limitations

  • Only names ending in EXPORT or _API. A project that spells its macro
    differently (FOO_DLL, FOO_PUBLIC) is not covered.
  • A real type named like FOO_API before a variable would be blanked. I
    found no such type in practice.
  • .h files go to the C extractor, so the same declaration in a .h still
    reports the syntax error. Out of scope, as the issue notes.
  • Prototypes without a body still produce no symbols, on v8 and here.
  • Paren macros (__declspec(dllexport), __attribute__((...))) stay
    unsupported, as before.

How was this tested?

The issue's reproduction script, with PYTHONPATH set to the worktree:

                 v8 (0f22ae76)                               this branch
a.hpp            syntax-error warning, 1 node                no warning, 1 node
b.cpp            4 nodes (incl. MYLIB_EXPORT)                3 nodes
b_control.cpp    3 nodes                                     3 nodes

Three new tests in tests/test_cpp_nested_and_cli.py: no ERROR for three
declaration shapes, no phantom node on a definition, and offsets kept with
#define, WINAPI and a bare EXPORT untouched.

.venv/bin/python -m pytest -q tests/test_cpp_nested_and_cli.py
    v8 code      -> 5 failed (the new tests), 31 passed
    this branch  -> 36 passed
.venv/bin/python -m pytest -q tests
    this branch  -> 95 failed, 12049 passed, 122 skipped, 1 xfailed
    the 95 are in 15 hook/CLI test files and fail the same on v8
    (those files on v8: 95 failed, 174 passed); none are C++
.venv/bin/python -m ruff check <changed files>
    -> All checks passed

Not tested: Windows, MSVC-only headers.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. (No trailer in the commit messages.)

…claration

tree-sitter-cpp reads `MYLIB_EXPORT uint64_t f(int);` as a declaration of
type MYLIB_EXPORT with uint64_t as an ERROR. A prototype then reports a
false syntax error, and a definition gains a phantom MYLIB_EXPORT node.

The parse tree cannot tell which of two adjacent words is the macro
(`DWORD WINAPI run()` has the same shape reversed), so match the
conventional spellings only: a name ending in EXPORT or _API with a
non-empty prefix, followed by another identifier. Blank it with spaces so
offsets stay unchanged. Preprocessor lines and the word after
class/struct/union/enum are left alone. Bump the AST cache schema to 58.
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify review View in Graphify

Review before merging · Merge confidence 4/5

1 bug · 4 possible issues to check · High impact

The C++ normalizer blanks selected uppercase names before parsing, using their spelling and nearby bytes to identify export macros.

P2  A legitimate type name ending in _API gets erased · extract.py:3670

4 possible issues we couldn't confirm

They don't change the score.

What this review covered
  • A changed file's diff was too long to show in full, so the review may not have seen every changed line in it.
  • One review pass used all of its turns for reading code, so it reported from what it had already read.
  • 3 of 3 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 5635 functions depend on this change
  • 1 function became more coupled. extract_cpp() (46 callers).
  • 406 of 642 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed 410aa91

Comment thread graphify/extract.py
Comment on lines +3667 to +3670
# the conventional spellings are matched: a name ending in ``EXPORT`` or
# ``_API`` with a non-empty prefix, followed by another identifier.
_CPP_EXPORT_DECL_MACRO_RE = re.compile(
rb"(?<![A-Za-z0-9_])[A-Z][A-Z0-9_]*(?:EXPORT|_API)(?![A-Za-z0-9_])"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2  A legitimate type name ending in _API gets erased

A C++ type alias whose name ends in _API can be removed from a declaration, causing the declaration to be misparsed and omitted from extraction.

Refine _CPP_EXPORT_DECL_MACRO_RE in graphify/extract.py to preserve legitimate _API type aliases.

Evidence · checked against the code

Expected: The alias remains in the source passed to the parser, allowing the declaration to be parsed and extracted.
Actually: The normalizer replaces the alias name with spaces before parsing.

  • Independent source review: The alias definition itself is not blanked because = does not satisfy the regex lookahead. The later alias use is blanked; the helper's guards only preserve preprocessor-line matches and names following an elaborated type keyword, neither of which applies to FOO_API value;. Existing tests cover intended export-macro normalization and those guards, but do not check this alias-use case.
  • No execution of a reproducer or additional source lookups was performed.
  • The precise extracted result depends on the C++ parser's recovery for the remaining declaration.
Prompt to fix with AI
In graphify/extract.py, _CPP_EXPORT_DECL_MACRO_RE (lines 3667-3670):
Problem: A legitimate type name ending in `_API` gets erased
Expected: The alias remains in the source passed to the parser, allowing the declaration to be parsed and extracted.
Actually: The normalizer replaces the alias name with spaces before parsing.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.122 (authorship-preserving cherry-pick). Byte-length-preserving and fails safe. One small follow-up worth considering: the macro blanking is a raw-byte regex that doesn't skip string literals / comments (unlike #5556's lexer approach) — harmless and consistent with the existing _CPP_EXPORT_MACRO_RE, but reusing #5556's lexer would tighten it. Thanks @Deepjyoti-Sarmah!

@safishamsi safishamsi closed this Nov 28, 2026
safishamsi pushed a commit that referenced this pull request Nov 28, 2026
The class/struct export-macro rule allows a newline after the keyword,
so a `// ... class` comment acted as the keyword for the next line and
`DWORD Widget::run()` lost its return type and its references edge.
Both export-macro rules also rewrote bytes inside strings and comments.

Collect comment and string/char/raw-string spans with the #5556 lexer
regexes, as suggested on #5558, and leave matches that start inside
them alone. Directive lines are scanned for their own comments, a block
comment opened on a directive line runs to its close, and a quote that
crosses an unspliced newline is not treated as a literal. Bump the AST
cache schema to 59 so cached C++ extractions re-run.

Fixes #5581

Co-Authored-By: Codex <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit a94fc47)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: C++: an export macro in front of a function or variable declaration is a syntax error, and on a definition it becomes a phantom node

2 participants