Repository navigation
fix c++ completion with c++20 and upstream libclang - #19563
Conversation
…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
left a comment
There was a problem hiding this comment.
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.
| // 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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"); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| // 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| expect_length(messages(), 0L) | ||
| }) | ||
|
|
||
| test_that("files are parsed with the default precompiled header", { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| // 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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"); |
There was a problem hiding this comment.
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.
| // 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() |
There was a problem hiding this comment.
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.
| expect_length(messages(), 0L) | ||
| }) | ||
|
|
||
| test_that("files are parsed with the default precompiled header", { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done in 14502b5: the test writes -std=c++20 to compile_flags.txt and is renamed.
| // 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; |
There was a problem hiding this comment.
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))
...There was a problem hiding this comment.
Done in 14502b5; the copy is only made after a failed parse.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
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
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
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
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.
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_ForSerializationonly, while source files are parsed withCXTranslationUnit_DetailedPreprocessingRecord. With modules enabled (C++20 and newer), libclang rejects that combination:and
clang_parseTranslationUnitreturns null (CXError_ASTReadError), so every libclang-backed feature for the file goes dead.precompiledHeaderOptions(), which takes the detailed-preprocessing-record option fromparseTranslationUnitOptions(), so the two can't drift apart.kPrecompiledHeaderVersion), so headers built by an older RStudio are discarded instead of reused. The existing cleanup removes the old directory.-include-pchin 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.compile_flags.txtis never touched.-std: six diagnostics requests for such a file went from six full parses to one.Automated Tests
test-cpp.Rgains a test that asks for C++20 throughcompile_flags.txt(so it doesn't depend on R's default standard), force-includes a header of its own, and then: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
.Callseam,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: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.Rpass there. One of them belonged to an existing test that expected libclang to call--bogus-flagan "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, loggingError parsing translation unitas 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=5count) 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 inCompilationDatabase.cpp, so whichever merges second needs a trivial conflict resolved.The C++ case in #19549's
completion_popup_aria.test.tsis 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.afterstd::string s;in an Rcpp source file should list the members ofstd::string.Documentation
None needed.
Checklist
NEWS.md