Skip to content

fix c++ completion with c++20 and upstream libclang - #19563

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/19559-cpp-completion-pch-options
Nov 11, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/19559-cpp-completion-pch-options

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Fixes #19559.

C/C++ completion, diagnostics, and navigation returned nothing for Rcpp and cpp11 source files compiled as C++20 or newer, which is R 4.6's default. The issue reports it for libclang 18 on Ubuntu 24.04, but it reproduces with upstream libclang 18, 19, 20, and 23; Apple's libclang doesn't enforce the check involved, which is why macOS was unaffected.

Approach

The Rcpp precompiled header was built with CXTranslationUnit_ForSerialization only, while source files are parsed with CXTranslationUnit_DetailedPreprocessingRecord. With modules enabled (C++20 and newer), libclang rejects that combination:

error: command line contains '-detailed-preprocessing-record' but precompiled header was not built with it

and clang_parseTranslationUnit returns null (CXError_ASTReadError), so every libclang-backed feature for the file goes dead.

  • The precompiled header is now built with precompiledHeaderOptions(), which takes the detailed-preprocessing-record option from parseTranslationUnitOptions(), so the two can't drift apart.
  • The precompiled header cache directory carries a version (kPrecompiledHeaderVersion), so headers built by an older RStudio are discarded instead of reused. The existing cleanup removes the old directory.
  • A parse that fails with -include-pch in its arguments is repeated without the precompiled header. parseWithPrecompiledHeaderFallback() does this for the source index, the definition index, and Find Usages alike. It logs a warning when a header is first rejected, and only if the parse then works without it, since libclang reports a bad flag the same way as a bad header.
  • A rejected precompiled header that RStudio built is rebuilt on the next request for it. This covers a header it was built from changing mid-session (say, Rcpp reinstalled at the same version). It happens once per header per session: if the rebuilt one is rejected as well, it is dropped and files are parsed without one, rather than rebuilding it for every parse. A precompiled header named in the user's own compile_flags.txt is never touched.
  • A translation unit's arguments are stored as fetched rather than as adjusted for the parse, so that later requests can match them and reparse instead of parsing from scratch. They never matched for a C++ file whose flags carried a C-only -std: six diagnostics requests for such a file went from six full parses to one.

Automated Tests

test-cpp.R gains a test that asks for C++20 through compile_flags.txt (so it doesn't depend on R's default standard), force-includes a header of its own, and then:

  1. parses an Rcpp file, expecting a diagnostic back and the precompiled header loaded rather than parsed around;
  2. changes the mtime of the force-included header, so libclang rejects the precompiled header, and expects the next file to be parsed anyway;
  3. expects the precompiled header to be rebuilt and loaded for the file after that;
  4. rejects it a second time, and expects it to be dropped rather than rebuilt again.

A file parsed around its precompiled header reports the same diagnostics as one parsed with it, so the test reads the rejected headers through a small .Call seam, rs_clangRejectedPrecompiledHeaders. The existing precompiled header test couldn't catch the original bug, because a file that fails to parse reports no diagnostics, which is what it expected.

Checked locally on macOS with R 4.6.1, against Apple's libclang and against Homebrew's libclang 23 (RSTUDIO_LIBCLANG_PATH), which behaves like the Linux ones:

Build New test
old header options, fallback only (Homebrew libclang) fails at step 1: the header was parsed around
fallback disabled fails at step 2: no diagnostics
rebuild disabled fails at step 3: the header is rejected again
second-rejection check disabled fails at step 4: the header is rebuilt again
this PR passes with both libclangs

Also built and run on Linux, in an arm64 Ubuntu 22.04 container with g++ 11, R 4.6.1, Rcpp 1.1.2, and libclang 18.1.8 from apt.llvm.org (not the Ubuntu 24.04 x86_64 setup from the issue, but the same R default standard and an upstream libclang 18). All 40 expectations in test-cpp.R pass there. One of them belonged to an existing test that expected libclang to call --bogus-flag an "unknown argument"; that libclang says "unsupported option '--bogus-flag'", so the test failed there with or without this PR, and it now accepts either wording. An earlier revision of this PR, with the original version of the test, was also run there with the C++ changes reverted; the test failed, logging Error parsing translation unit as in the issue.

The underlying failure and the header-option fix were also confirmed with a standalone libclang 18/19/20 harness in an Ubuntu 24.04 x86_64 container.

test-cpp.R:69 (the -ferror-limit=5 count) fails with Homebrew's libclang 23 on macOS with or without this change; it passes with Apple's libclang. That is a separate problem, fixed in #19565. The two PRs edit adjacent lines in CompilationDatabase.cpp, so whichever merges second needs a trivial conflict resolved.

The C++ case in #19549's completion_popup_aria.test.ts is limited to macOS because of this bug and can be enabled for Linux once both are merged.

QA Notes

On Ubuntu 24.04 with R 4.6 and Rcpp installed, follow the steps in #19559: typing s. after std::string s; in an Rcpp source file should list the members of std::string.

Documentation

None needed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

…parsed with

libclang refuses a precompiled header built without the detailed
preprocessing record when the including translation unit asks for one
and modules are enabled, which C++20 (R 4.6's default) does. The parse
then failed outright, so completions, diagnostics, and navigation went
dead for Rcpp and cpp11 sources. Build the header with the same option,
version the header cache so stale ones are discarded, and parse without
the header when libclang can't load it.

Addresses #19559

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Read through, with the call sites in DefinitionIndex.cpp, FindReferences.cpp, and CompilationDatabase.cpp. Nothing here is a blocker for the C++20 fix itself. The header-options change looks right. The comments are mostly about the fallback: it covers only one of the three places that parse with the PCH args, it never heals a bad PCH, and the new test can't tell the fallback apart from the actual fix.

One comment (stored args vs. fetched args) concerns a bug that predates this PR. I raised it because the new comment depends on it.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
// The original arguments are what's stored, so that later requests
// reparse this translation unit rather than repeating the failure.
std::vector<std::string> pchFreeArgs = args;
if (tu == nullptr && removePrecompiledHeaderArgs(&pchFreeArgs))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The retry only covers SourceIndex::getTranslationUnit. DefinitionIndex.cpp:258 and FindReferences.cpp:386 call parseTranslationUnit directly with the same compileArgsForTranslationUnit(file, true) args, so they still carry -include-pch and get no retry.

The header-options change fixes those paths too for the C++20 case. But for any other PCH that libclang can't load, the definition index behind Go to File/Function (SessionCodeSearch.cpp:1935) and the Go To Definition fallback (GoToDefinition.cpp:51) silently come back empty. So does Find Usages across unopened package files. The NEWS line ("If a precompiled header can't be loaded, RStudio now parses the file without it") claims more than that.

Moving the retry into a shared libclang helper that all three call sites use would cover them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14502b5. The retry moved into parseWithPrecompiledHeaderFallback() in core/libclang/SourceIndex.cpp, and the source index, the definition index, and Find Usages all parse through it, so the NEWS line now holds for all three.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
std::vector<std::string> pchFreeArgs = args;
if (tu == nullptr && removePrecompiledHeaderArgs(&pchFreeArgs))
{
LOG_ERROR_MESSAGE("Error parsing translation unit " + filename + " with its precompiled header; parsing without it");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nothing marks the PCH as bad once this fires. precompiledHeaderArgs rebuilds only when the file is missing or forceRebuildPrecompiledHeaders_ is set (CompilationDatabase.cpp:1851). That flag is set only when a package's compilation database is rebuilt (CompilationDatabase.cpp:868).

So an unloadable PCH stays unloadable, and every later full parse fails once, retries, and logs this error. One way it could happen, which I haven't reproduced: reinstalling the same Rcpp version (from source, or via renv) changes the header mtimes. The PCH path key (package version, platform, svn rev, libclang version, package path hash) stays the same, so the old PCH would be reused and rejected as modified.

Would it make sense to delete the PCH (or otherwise mark it rejected) on the first failure, so it gets rebuilt?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in e8e4ed0. The scenario is real: a header whose mtime changed after the PCH was built makes libclang fail the parse ("has been modified since the precompiled header was built") on Apple's libclang, upstream 18, and upstream 23, and the new test uses exactly that to get a rejected PCH. One thing bounds it: the PCH lives under R's session temp dir (precompiledHeaderDir() -> R_TempDir), so a stale one never outlived the session.

I didn't delete it from the fallback itself, for two reasons: -include-pch can also come from a user's compile_flags.txt, which isn't ours to delete, and a PCH that is rejected again after a rebuild (as every C++20 one was before this fix) would be rebuilt on every full parse. Instead the fallback records the rejected PCH, and precompiledHeaderArgs takes its own from that record and rebuilds it on the next request. That happens once per PCH per session; if the rebuilt one is rejected as well, it is removed and files are parsed without one. The test covers both the rebuild and the second rejection.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
// header (e.g. one built with other options, or by another libclang).
// Parse without it in that case: slower, but everything still works.
// The original arguments are what's stored, so that later requests
// reparse this translation unit rather than repeating the failure.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This holds only when the args aren't modified before they're stored. Lines 323 and 325 (-v and removeMismatchedStdArgs, from #19393) change args before it's stored at line 377. The freshly fetched args compared against it at the top of the function haven't been through either step.

compileArgsForTranslationUnit appends compile_flags.txt flags as-is (CompilationDatabase.cpp:1422). In a mixed C/C++ package whose flags file has -std=c11 (the case precompiledHeaderArgs' own comment describes), every C++ file is stored without that flag. args == stored.compileArgs is then never true, and every request does a full parse. With an unloadable PCH, that also means a failed parse and an error log on each request.

This predates the PR, but the new comment depends on it. Storing the args as fetched, before the two steps, would fix both.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14502b5: the parse uses a separate parseArgs copy, and the args are stored as fetched. With -std=c11 in compile_flags.txt, six diagnostics requests for a .cpp file went from six full parses to one.

Comment thread src/cpp/tests/testthat/test-cpp.R Outdated
expect_length(messages(), 0L)
})

test_that("files are parsed with the default precompiled header", {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

By the table in the PR description, this test passes with "old header options, retry only". So it checks that the file gets parsed, but not that precompiledHeaderOptions() produces a PCH libclang accepts. If the options regress, every C++20 parse quietly takes the slower PCH-free path and this still passes. Once the header fix is in, nothing exercises the retry either.

Could the test fail when the retry runs, and a second test use a deliberately unusable PCH to check that the retry succeeds?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14502b5, extended in e8e4ed0. The test now fails if the PCH is parsed around (checked against a build with the old header options). It then bumps the mtime of a header the PCH was built from, so libclang rejects it, and expects the file to be parsed anyway (fails with the fallback disabled). A file parsed around its PCH reports the same diagnostics as one parsed with it, so there's a small .Call seam, rs_clangRejectedPrecompiledHeaders, to tell them apart. It's one test_that with several steps rather than separate tests, to share the PCH builds.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
// The original arguments are what's stored, so that later requests
// reparse this translation unit rather than repeating the failure.
std::vector<std::string> pchFreeArgs = args;
if (tu == nullptr && removePrecompiledHeaderArgs(&pchFreeArgs))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This retries whenever the parse returns null and the args include -include-pch, whatever the cause. A failure unrelated to the PCH (say, bad user flags) gets parsed twice and logs a message blaming the PCH.

Retrying only on CXError_ASTReadError would need clang_parseTranslationUnit2 added to the LibClang wrapper, which only exposes parseTranslationUnit (LibClang.hpp:239). So this may not be worth it; mentioning it in case.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I tried clang_parseTranslationUnit2: it returns CXError_ASTReadError for a garbage PCH, for a missing PCH, and for -std=c++99 with no PCH at all (Apple's libclang 21 and upstream 23), so the code doesn't separate the cases. In 14502b5 the PCH is only recorded as rejected, and the warning only logged, once the parse succeeds without it. An unrelated failure is still parsed twice, but it's no longer blamed on the PCH.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
std::vector<std::string> pchFreeArgs = args;
if (tu == nullptr && removePrecompiledHeaderArgs(&pchFreeArgs))
{
LOG_ERROR_MESSAGE("Error parsing translation unit " + filename + " with its precompiled header; parsing without it");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since the parse recovers here, LOG_WARNING_MESSAGE (core/Log.hpp:66) seems like a better fit than an error. Logging it once per PCH, rather than on every full parse, would also help.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14502b5: LOG_WARNING_MESSAGE, logged when a PCH is first rejected rather than on every parse. With e8e4ed0 a PCH of ours can be logged at most twice a session (once before its rebuild, once if the rebuilt one is rejected too).

// header that wasn't built with the detailed preprocessing record when the
// translation unit including it asks for one, so this must stay in step
// with parseTranslationUnitOptions().
unsigned precompiledHeaderOptions()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Only the comment keeps this in step with parseTranslationUnitOptions(). Deriving it would let the code enforce that:

return CXTranslationUnit_ForSerialization |
       (parseTranslationUnitOptions() & CXTranslationUnit_DetailedPreprocessingRecord);

Given the retry and the test above, a mismatch here would otherwise go unnoticed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14502b5.

Comment thread src/cpp/tests/testthat/test-cpp.R Outdated
expect_length(messages(), 0L)
})

test_that("files are parsed with the default precompiled header", {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This depends on R's default standard being C++20. On R older than 4.6 the PCH is never rejected, and the test passes with or without the fix. Writing -std=c++20 to a compile_flags.txt in dir would exercise the bug on any R version. That builds the user-flags PCH rather than the default one, so the test name would need adjusting.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14502b5: the test writes -std=c++20 to compile_flags.txt and is renamed.

Comment thread src/cpp/core/libclang/SourceIndex.cpp Outdated
// Parse without it in that case: slower, but everything still works.
// The original arguments are what's stored, so that later requests
// reparse this translation unit rather than repeating the failure.
std::vector<std::string> pchFreeArgs = args;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: this copies the args on every full parse, including the common case where the parse succeeded. It could move inside the failure branch:

if (tu == nullptr)
{
   std::vector<std::string> pchFreeArgs = args;
   if (removePrecompiledHeaderArgs(&pchFreeArgs))
   ...

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14502b5; the copy is only made after a failed parse.

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
5484 0 245 4
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1373 0 46 1
✅ desktop-macos 1379 0 40 2
✅ desktop-windows 1368 0 57 1
✅ server-linux 1312 0 54 0
✅ setup 48 0 32 0

View report online


All platforms - commit f75e336c6429e1b4fb06dff35e9f51b6c1084797 - Run #2187

The retry without a precompiled header only covered the source index;
the definition index and find usages parsed with the same arguments and
got none. Move it into a helper all three use. It now warns once per
header, and only when the parse works without it, since libclang reports
a bad flag the same way as a bad header.

Also store a translation unit's arguments as fetched rather than as
adjusted for the parse, so that a later request's arguments can match
them and a reparse will do (they never matched for a C++ file whose
flags carry a C-only -std), and derive the header's options from the
ones its includers are parsed with.

The test asks for C++20 itself rather than relying on R's default, fails
if the header is parsed around, and covers the fallback with a header
libclang rejects.

Addresses #19559
A header the precompiled header was built from can change during a
session (say, Rcpp reinstalled at the same version), after which
libclang rejects it for the rest of the session and every full parse
fails once before falling back. The compilation database now takes a
rejected header of its own and rebuilds it on the next request. That
happens once per header: if the rebuilt one is rejected too, it is
dropped and files are parsed without one, rather than rebuilding it
for every parse. A precompiled header named by the user's own flags
is left alone.

Addresses #19559
@kevinushey
kevinushey requested a review from gtritchie November 11, 2026 01:10
libclang 18 on Linux reports '--bogus-flag' as an "unsupported option",
where Apple's and newer ones say "unknown argument", so the expectation
failed there.

Addresses #19559

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, all addressed. I checked each fix against the code. One optional note inline, which needn't hold this up.

// every parse.
std::string pch = pchPath.getAbsolutePath();
bool rejected = takeRejectedPrecompiledHeader(pch);
if (rejected && !rebuiltPrecompiledHeaders_.insert(pch).second)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional, non-blocking: the "only once" rule can't tell a PCH that libclang can never load from one that went stale a second time after a rebuild that worked.

Say a user edits a header force-included through compile_flags.txt (the pattern the new test uses) twice in a session, or reinstalls Rcpp twice. The first change rebuilds the PCH. The second lands here and marks it unusable, and files then parse without a PCH until the next package compilation-database rebuild (line 1856) or, for sourceCpp files, a restart. It's only slower, so fine to leave. If it's worth doing, clearing the rebuiltPrecompiledHeaders_ entry once a rebuilt PCH has loaded successfully would limit "unusable" to PCHs rejected straight after their rebuild.

@kevinushey
kevinushey merged commit ac6e86f into main Nov 11, 2026
33 of 36 checks passed
@kevinushey
kevinushey deleted the bugfix/19559-cpp-completion-pch-options branch November 11, 2026 01:35
ronblum added a commit that referenced this pull request Nov 16, 2026
Conflicts: keep the rig --arch option with main's converted install
folder; take main's precompiled header options (#19563) in place of ours;
keep the ARM64 R home check and the failure page's warning label; keep
both sides' new tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C++ completion returns nothing with libclang 18 on Ubuntu 24.04

2 participants