Skip to content

keep libclang diagnostics going past clang's default error limit - #19393

Merged
kevinushey merged 17 commits into
mainfrom
bugfix/19367-clang-error-limit
Nov 5, 2026
Merged

kevinushey merged 17 commits into
mainfrom
bugfix/19367-clang-error-limit

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

C and C++ diagnostics (and completions) silently stop once a file has 20 or more errors. RStudio never passes -ferror-limit to libclang, so clang's default limit of 19 applies, emits fatal error: too many errors emitted, stopping now, and halts the parse. The fatal diagnostic has no file location, so it is filtered out before reaching the editor and the user sees nothing about why.

Fixes #19367.

Approach

  • Pass -ferror-limit=0 in baseCompilationArgs(), which covers both the package path and the sourceCpp path, and bump kCompilationDatabaseVersion so existing cached compilation-database/config.json files are rebuilt.
  • Allow a per-project override by honoring a compile_flags.txt (the clangd convention: one argument per line, blank lines ignored). It is looked up in the source file's directory and its parents, stopping at the project directory (or at the file's own directory when there is no project). The flags are appended last, after the generated arguments and any precompiled-header arguments, so they take precedence (clang uses the last -ferror-limit it sees). Note this differs from clangd, where the file replaces the compile command; here it appends, since our arguments come from R CMD SHLIB.
  • The flags are read when arguments are assembled for a translation unit rather than cached in the compilation database, so edits to compile_flags.txt take effect on the next lint without a rebuild.

Automated Tests

Adds a testthat test to src/cpp/tests/testthat/test-cpp.R that lints a .cpp file with 25 errors and expects all 25 (previously 19), then writes -ferror-limit=5 to a sibling compile_flags.txt and expects 5. It skips when Rcpp or libclang is unavailable. Verified failing against an unfixed rsession and passing with this change (rstudio-tests --scope r --filter cpp).

Also verified by hand with a package project: 26 diagnostics by default, 3 with -ferror-limit=3 in a package-root compile_flags.txt.

QA Notes

  1. Open an R package project with C or C++ sources and add a file with 20 or more errors (e.g. 25 lines of undeclared_N = N;). Diagnostics should be reported for every error, not just the first 19.
  2. Add a compile_flags.txt in the project root containing -ferror-limit=5 and re-lint (edit the file). Only 5 errors should be reported.
  3. .rs.setClangDiagnostics(1) in the console prints the flags file and arguments being used.

Documentation

Adds a "C / C++ diagnostics" section to the User Guide's Code Diagnostics page (docs/user/rstudio/ide/guide/code/diagnostics.qmd), which is the page the Using Code Diagnostics help link in Global Options > Code > Diagnostics opens. It explains where the flags come from, compile_flags.txt, and the clang_verbose preference for seeing the flags in use.

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

clang stops parsing after 19 errors unless -ferror-limit is set, which
silently ended diagnostics and completions for the rest of a file. Pass
-ferror-limit=0 in the base compilation args, bump the compilation
database version so cached configs rebuild, and honor a compile_flags.txt
(clangd convention, one argument per line) found in the source file's
directory or any parent up to the project directory, appended last so a
project can override the generated flags.

Addresses #19367
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 2, 2026
@kevinushey
kevinushey requested a review from gtritchie November 2, 2026 18:43

@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.

Requesting changes. The -ferror-limit=0 fix looks right, and bumping kCompilationDatabaseVersion is needed so cached config.json files are rebuilt. The comments are about the new compile_flags.txt support:

  • Must fix: some flags make libclang reject the precompiled header, leaving the file with no diagnostics at all.
  • Should fix: relative paths don't resolve the way clangd's do, and bad flags fail silently.
  • The rest: docs corrections, a reuse note, caching, and test coverage.

I checked the PCH, relative-path and bad-flag behavior against libclang directly, not in a full RStudio build.

}

// append any user-provided flags last so they take precedence
std::vector<std::string> userFlags = compileFlagsFromFile(filePath);

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.

Some flags in compile_flags.txt make libclang reject the precompiled header, which leaves the file with no diagnostics or completions at all.

The flags are appended after -include-pch, but precompiledHeaderArgs() builds the PCH from config.args only. I checked this against libclang directly, using a PCH built with -std=c++17 -DNDEBUG. With any of these appended, clang_parseTranslationUnit returned NULL:

  • -std=c++20
  • -std=gnu++17
  • -UNDEBUG
  • -DNDEBUG=0

In RStudio that shows up only as "Error parsing translation unit" in the log. Adding a new -D, -ferror-limit=N, -W... or -fopenmp was fine.

Package builds pass -DNDEBUG, so -UNDEBUG (to turn asserts back on) is a likely thing to put in this file. Possible fixes: include the user flags when building the PCH (and in its cache key), or skip the PCH when user flags are present.

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 0cd4c45. The user flags now feed into the PCH build (and -std= is extracted from the combined list), and the PCH filename includes a hash of them so different flag sets do not share one. Verified with PCH enabled that -std=c++20 + -UNDEBUG in compile_flags.txt builds a second PCH and parses cleanly.

args.push_back("c++");
}

// append any user-provided flags last so they take precedence

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.

If a flag in compile_flags.txt is bad, the user gets no sign of it.

  • Unknown arguments and misspelled warning flags (--bogus-flag, -Wno-unused-paramter): libclang reports these with no source location, and getCppDiagnosticsJson drops anything outside the file (Diagnostics.cpp:155). The file lints as if the line weren't there.
  • An invalid value like -std=c++99: libclang returns a NULL translation unit, so the file gets no diagnostics at all.

That is the same silent failure #19367 set out to fix. One option is to show diagnostics that have no location, or at least those reported against the command line, when user flags are in play.

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 0cd4c45. When a compile_flags.txt is in play, diagnostics with no location are anchored at line 1 of the file, and a null translation unit produces an error at line 1 pointing at the flags file. Both are gated on the flags file so default-flag users see nothing new. The testthat test covers -Wno-unused-paramter, --bogus-flag and -std=c++99. One bonus: with -ferror-limit=5 in the file, clang's "too many errors emitted" fatal is now visible too.

}

std::vector<std::string> flags;
for (std::string line : core::algorithm::split(contents, "\n"))

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.

Relative paths here resolve against rsession's working directory (whatever R's getwd() is), not against the folder containing compile_flags.txt.

clangd's loader (FixedCompilationDatabase::loadFromFile) uses parent_path of the flags file as the compile command's working directory. Since the docs describe this as the clangd format, -Iinst/include in a package-root compile_flags.txt would be expected to work. In practice it only works while R's working directory happens to be the package root.

I checked with libclang: -Iinc found the header when run from the project directory, and gave fatal error: 'x.h' file not found when run from /. Suggest resolving relative -I/-isystem/-include (etc.) paths against flagsFile.getParent().

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 0cd4c45. Rather than rewriting each path-taking flag, a -working-directory=<dir of compile_flags.txt> is prepended to the user flags, which makes clang resolve every relative path against it. The generated args are already absolute (-I./-I.. get substituted), so they are unaffected. Covered by a testthat test that uses -Iinc while rsession's cwd is elsewhere.

return {};

std::string contents;
Error error = core::readStringFromFile(flagsFile, &contents);

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.

core::readStringVectorFromFile(flagsFile, &flags) (FileSerializer.hpp:414) already trims each line and skips blank ones; trimAndIgnoreBlankLines defaults to true. It could replace the read/split/trim loop below.

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 0cd4c45, thanks.

// convention of one argument per line. We look in the source file's directory
// and its parents, up to the project directory, so a project can append to or
// override the flags we generate (the last occurrence of a flag wins).
std::vector<std::string> compileFlagsFromFile(const FilePath& srcFile)

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 walks up the directories and reads the file on every compileArgsForTranslationUnit call. That includes every diagnostics and completion request (through SourceIndex::getTranslationUnit), include-path discovery, and every file indexed by DefinitionIndex/FindReferences.

At clang_verbose >= 1 it also prints the # COMPILE FLAGS FROM block on every lint. Caching the result per directory, keyed on the file's modification time, would avoid 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.

Partly done in 0cd4c45: the file is re-read, and the verbose block printed, only when its mtime changes. I kept the directory walk itself since it is a few stats per call and is what notices a file being added or removed; caching it would need its own invalidation for little gain next to a TU parse.


Changes to `compile_flags.txt` take effect the next time diagnostics run; no restart is required.

To see the flags being passed to `libclang`, set the `clang_verbose` preference to `1` in [`rstudio-prefs.json`](../productivity/custom-settings.qmd) and restart the R session. The flags are then printed to the session log whenever a file is indexed.

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.

At clang_verbose = 1 this doesn't print the flags passed to libclang. The full list (# COMPILATION ARGUMENTS) is only printed when verbose_ > 1 (SourceIndex.cpp:280). Level 1 shows only the compile_flags.txt contents and, for packages, the config JSON when it is saved or restored.

Suggest 2 here, or pointing to .rs.setClangDiagnostics(2), which also restarts R. Also, this output goes to rsession's stderr, which may not be what users think of as the session log.

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 94fdff5: the docs now point at .rs.setClangDiagnostics(2) or clang_verbose = 2, and say the output goes to the R session's stderr rather than "the session log".


RStudio derives the compiler flags for a file from the way it would normally be built. For sources in an R package, the flags come from `R CMD SHLIB`, so the package's `src/Makevars` and `LinkingTo` dependencies are respected. For standalone files, they come from `Rcpp::sourceCpp()` or `cpp11::cpp_source()`. All errors in a file are reported; RStudio does not stop after clang's default error limit.

To add or override flags, create a `compile_flags.txt` file containing one argument per line, in the same format used by [clangd](https://clangd.llvm.org/design/compile-commands#compile_flagstxt). RStudio looks for this file in the source file's directory and its parent directories, up to the project directory, and appends its contents to the generated flags. Because they come last, they take precedence over the flags RStudio generates. For example, to stop reporting after 50 errors and silence a warning:

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 search only reaches "up to the project directory" when the file is inside an open project. With no project open, or for a file outside the project, only the file's own directory is checked (stopDir = dir at CompilationDatabase.cpp:178). Worth saying so here.

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 94fdff5; the docs (and NEWS) now say the parent search only applies to files inside the current project.


RStudio derives the compiler flags for a file from the way it would normally be built. For sources in an R package, the flags come from `R CMD SHLIB`, so the package's `src/Makevars` and `LinkingTo` dependencies are respected. For standalone files, they come from `Rcpp::sourceCpp()` or `cpp11::cpp_source()`. All errors in a file are reported; RStudio does not stop after clang's default error limit.

To add or override flags, create a `compile_flags.txt` file containing one argument per line, in the same format used by [clangd](https://clangd.llvm.org/design/compile-commands#compile_flagstxt). RStudio looks for this file in the source file's directory and its parent directories, up to the project directory, and appends its contents to the generated flags. Because they come last, they take precedence over the flags RStudio generates. For example, to stop reporting after 50 errors and silence a warning:

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 this (and the QA notes) points package authors at a package-root compile_flags.txt, it should mention adding it to .Rbuildignore. Otherwise R CMD build ships it, and R CMD check flags it as a non-standard top-level file.

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 94fdff5, with a pointer to usethis::use_build_ignore().

expect_equal(countErrors(), 25L)

# flags from compile_flags.txt are appended, so they can override ours
writeLines("-ferror-limit=5", file.path(dir, "compile_flags.txt"))

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 only covers a compile_flags.txt next to the source file. Not covered:

  • finding it in a parent directory
  • stopping at the project directory, and not using a file above it
  • blank lines and CRLF line endings

A regression in the while (true) walk, such as dir == stopDir failing on a trailing slash or a symlinked project path, would still pass.

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 0cd4c45. The lookup and parsing are split into findCompileFlagsFile() / readCompileFlags() and covered by gtests (parent lookup, nearest wins, stop at the project dir, nothing above it, trailing slash on the stop dir, CRLF/blank/whitespace). The stop comparison also uses isEquivalentTo() now, which is what makes the trailing-slash case pass. The testthat tests cover CRLF/blank lines end to end alongside the relative-path case.

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

3 test(s) failed

###################- 99% pass rate

Passed Failed Skipped Flaky
4788 3 321 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
❌ desktop-linux 1194 1 70 0
❌ desktop-macos 1188 1 75 2
❌ desktop-windows 1193 1 77 0
✅ server-linux 1161 0 51 0
✅ setup 48 0 32 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit d78d35dd8fb25c8784cf25efe5efda4c37f1df10 - Run #1971

…port bad flags

- the precompiled header is now built from the generated args plus the
  user flags (and named by a hash of them), since libclang rejects a PCH
  whose language options or macros differ from the translation unit's
- a -working-directory pointing at the flags file's directory is prepended,
  so relative -I and friends resolve as they do in clangd
- diagnostics clang reports against the command line (no location), and a
  parse that fails outright, are surfaced at the top of the file when a
  compile_flags.txt is in play instead of being dropped
- flags are re-read only when the file's mtime changes; the lookup and
  parsing are split out and covered by gtests, and the testthat tests
  cover relative paths, CRLF/blank lines, and bad flags
@kevinushey
kevinushey requested a review from gtritchie November 2, 2026 20:37

@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 for the quick turnaround. The round-1 fixes work: I checked the PCH change, the -working-directory change, and the bad-flag reporting against libclang, and the docs and tests look good.

The new code adds a few smaller issues, mostly at the edges of the PCH and diagnostics changes. The PCH wipe from a C-only -std is the one worth fixing before merge. The others are lower priority.

// now create the PCH if we need to
std::string stdArg = extractStdArg(config.args);
FilePath pchPath = platformPath.completeChildPath(pkgName + stdArg + ".pch");
std::string stdArg = extractStdArg(baseArgs);

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 PCH build takes the last -std from config plus user flags, but unlike SourceIndex::getTranslationUnit it doesn't drop C-only -std flags for C++. A C-only or invalid -std in compile_flags.txt therefore makes the PCH build return a NULL TU. That deletes the package's whole PCH directory (precompiledDir.removeIfExists()), and the build is retried on every lint because the .pch never gets created.

I checked this with the CommandLineTools libclang that RStudio loads on macOS: building the PCH .cpp with -std=c11 returns NULL. -std=c11 is plausible in a mixed C/C++ package's flags file.

For the C++ file itself, SourceIndex drops -std=c11, so the file still parses, just without the PCH. The user sees no error; lints are slower, every lint makes a failed PCH build, and the default Rcpp PCH is gone.

Applying the same C/C++ -std filtering to baseArgs before extractStdArg would fix the -std=c11 case. (A flag that only causes errors inside the header doesn't trigger this; libclang still saved the PCH in that test.)

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.

Good catch, and confirmed: -std=c11 in the flags file made the PCH parse return NULL, which wiped the package's PCH directory and was retried on every lint. Fixed in 6f81f13: the PCH build now drops C-only -std flags the same way SourceIndex does for the C++ sources, and a PCH failure with user flags in play removes only that attempt's files rather than the whole directory, so the default Rcpp PCH survives an invalid -std=c++99 too. Verified both cases against the CommandLineTools libclang.

TranslationUnit tu = sourceIndex().getTranslationUnit(filename, true);
if (tu.empty())
{
bool indexable = !clangCompilationDatabase().compileArgsForTranslationUnit(filename, true).empty();

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.

With an invalid value like -std=c++99, the file's own parse fails too. This call then runs compileArgsForTranslationUnit again, and with it a second failed PCH build (and directory wipe) in the same lint.

This line also runs when there's no flags file, since it's evaluated before the hasUserFlags check. It's cheap in that case, but moving it inside the check skips the work entirely.

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 6f81f13. The NULL-TU check now asks for the args without the PCH (compileArgsForTranslationUnit(filename, false)), so a bad flag no longer triggers a second failed PCH build, and the whole check lives inside the user-flags branch so it's skipped when there's no flags file.

{
diagnosticsJson.push_back(diagnosticToJson(tu, *pDiag));
}
else if (hasUserFlags && location.empty())

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 also picks up location-less diagnostics caused by RStudio's generated flags, which were dropped before. Once any compile_flags.txt exists, they show up on line 1, even though the user's flags didn't cause them.

Concrete case: a macOS user sets up OpenMP the way data.table's install guide describes (SHLIB_OPENMP_CXXFLAGS = -Xclang -fopenmp in ~/.R/Makevars), and the package's Makevars uses $(SHLIB_OPENMP_CXXFLAGS). extractCompileArgs keeps -fopenmp but drops the -Xclang before it. The CommandLineTools libclang then reports error: unsupported option '-fopenmp' with no location. Adding just -ferror-limit=50 to compile_flags.txt now puts that error on line 1. CRAN macOS R's default flags don't trigger this.

Possible fix: diagnose the generated args once without the user flags, and only surface location-less diagnostics that don't appear there.

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.

Agreed this was a regression in visibility. I went with a cheaper rule than a second parse (6f81f13 + 87f9915): a location-less diagnostic is surfaced only when its message quotes one of the lines in compile_flags.txt, or when it's fatal. Clang quotes the offending argument in its driver errors, and the only location-less fatal we can get is the "too many errors emitted" stop, which can only come from a user's -ferror-limit since we pass -ferror-limit=0 ourselves. Checked your OpenMP case: with PKG_CXXFLAGS = -Xclang -fopenmp in Makevars and only -ferror-limit=50 in the flags file, the -fopenmp error stays hidden; add -fopenmp to the flags file and it shows on line 1. Happy to switch to the parse-once baseline if you'd rather have it exact.

std::string stdArg = extractStdArg(baseArgs);
std::string pchName = pkgName + stdArg;
if (!userFlags.empty())
pchName += "-" + core::hash::crc32HexHash(core::algorithm::join(userFlags, "\n"));

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.

Old PCHs are only removed when the platform directory changes or a build fails, so every distinct set of flags leaves a full PCH in R's tempdir until the session ends. One built for just <vector>/<string> was 12.5 MB in testing; the comment above estimates about 25 MB for Rcpp. Someone iterating on compile_flags.txt collects one per version.

Also, an empty (or all-blank) compile_flags.txt still produces {-working-directory=...}, so it gets its own PCH instead of reusing the default one.

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 6f81f13 and 87f9915. A blank flags file is now treated as no file, so it shares the default PCH. User-flag PCHs are named <pkg><std>-flags-<hash>.pch, and building a new one removes the previous -flags- variants for that package, so iterating on compile_flags.txt keeps at most one user PCH beside the default. A forced rebuild (compilation database changed) now clears every variant too. The one trade-off: two directories in a package with different flags files would rebuild each other's PCH on each switch.


// re-read only when the file changes on disk
std::string key = flagsFile.getAbsolutePath();
std::time_t lastWriteTime = flagsFile.getLastWriteTime();

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.

Minor: getLastWriteTime() returns whole seconds, so a second write in the same second as a cached read is never picked up. The old flags stay in use until the file changes again. That's unlikely when editing by hand, more likely when a script writes the file. Also comparing the file size, or using a sub-second timestamp, would close the gap.

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 6f81f13 by removing the timestamp altogether: the file is tiny, so it's re-read on every lookup and compared by content. The cache only remains to log changes at clang_verbose 1.

…r pchs

Round-2 review fixes for #19393:

- drop C-only -std flags before building the (C++) PCH, matching what
  SourceIndex does for the sources, so '-std=c11' in a flags file no
  longer makes the PCH build fail
- when the PCH build fails with user flags in play, remove just that
  attempt's files instead of wiping the package's PCH directory
- diagnose a NULL translation unit without the PCH, so a bad flag does
  not trigger a second failed PCH build in the same lint
- only surface location-less diagnostics whose message mentions one of
  the user's flags, so errors from the generated flags (an unsupported
  '-fopenmp' from Makevars, say) stay hidden as before
- remove the previous user-flag PCHs when building a new one, and treat
  a blank compile_flags.txt as no file
- re-read compile_flags.txt on every lookup and compare its contents,
  rather than relying on the one-second mtime resolution
…ebuild

A location-less fatal (clang's "too many errors emitted" stop) can only
come from a user's -ferror-limit since we pass -ferror-limit=0 ourselves,
so it is surfaced even though its message doesn't quote the flag. And a
forced PCH rebuild now removes all of the package's PCH variants, not
just the one requested first, so the other variant can't go stale.
@kevinushey
kevinushey requested a review from gtritchie November 3, 2026 00:03
…ng it fails

Prepending -working-directory made clang rebase every relative path, including
ones from Makevars that RStudio's generated flags carry, and header completion
(which only reads -I<dir> arguments) never saw it. Resolve the user's path
operands against the flags file's directory instead.

A failed saveTranslationUnit now returns no PCH args rather than -include-pch
for a file that was just removed. The docs also said the clang_verbose output
lands in server logs or a terminal; rsession routes its stderr to the R console.
…ch path

'-isystem-after' and the '--include-directory=' family were read as a shorter
option plus a garbled operand, or left relative. Each option now carries how
clang accepts its operand, and a testthat test exercises compile_flags.txt
with precompiled headers enabled.
…fter

Header completion only reads -I arguments, so '--include-directory=inc' never
reached it.
…t -I

A directory added with -isystem, -iquote, -idirafter or -isystem-after (which
is how the long include spellings in compile_flags.txt come out) was searched
by clang but never by header completion.
clang searches them for #include "..." alone, so suggesting their headers for
#include <...> produces an include it cannot resolve.

@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.

The round-2 fixes all look right, and CI is green. The PCH filtering and cleanup, the indexable check, the content-based re-read, and the generated-flag filtering all check out.

Two things left on the new code. The main one: the "quotes a flag" rule still hides typos in flags whose errors quote the value separately, such as -march=haswel. The other is minor: a few clang path options aren't on the resolution list.

std::string message = diagnostic.spelling();
for (const std::string& flag : userFlags)
{
if (message.find(flag) != std::string::npos)

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.

Matching the whole line misses clang's errors for a bad value, which quote the option and the value separately. A typo in one of those flags is silently dropped again, and the file still parses, so nothing tells the user.

I ran this check against CommandLineTools libclang output:

Flag in compile_flags.txt Message Shown?
-march=haswel unsupported argument 'haswel' to option '-march=' no
-fsanitize=bogus unsupported argument 'bogus' to option '-fsanitize=' no
-isysrootnosuch no such sysroot directory: '/abs/.../nosuch' (quotes the resolved path) no
--bogus-flag, -Wno-unused-paramter, -stdlib=libc++x quote the whole line yes

One option is to also match the part before = together with the part after it, and the resolved operand of path options. The other is the baseline parse you offered: run without the user flags and show only diagnostics the baseline doesn't have. I'd lean toward the baseline, since it doesn't depend on how clang words each message.

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.

Switched to the baseline in 4ad81f9, in a cheap form: SourceIndex::commandLineDiagnostics() parses an empty copy of the file with just the generated flags and collects the location-less diagnostics, cached per distinct set of generated flags, and we show only the location-less diagnostics from the real parse that aren't in it. The fatal special case is gone since the baseline can never contain the "too many errors" stop. All three of your hidden cases now surface (-march=haswel, -fsanitize=bogus as a new test, -isysrootnosuch with the resolved path), and a generated -fopenmp stays hidden with only -ferror-limit=50 in the file. One consequence: clang collapses repeated identical driver diagnostics, so re-adding a flag the generated args already carry is now hidden too, which I think is the right reading of "nothing beyond the baseline".

// which is the spelling header completion looks for.
enum OperandStyle { Joined, Equals, Separate };
struct PathOption { const char* spelling; OperandStyle style; const char* alias; };
static const PathOption kPathOptions[] = {

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.

Minor: now that -working-directory is gone, these path options aren't on this list, so their relative paths still resolve against R's working directory:

  • -iframework
  • -cxx-isystem
  • -ivfsoverlay
  • -fmodule-map-file=
  • --gcc-toolchain=

Meanwhile the docs say "Relative paths, such as -Iinst/include, are resolved against the directory containing compile_flags.txt" without qualification. These options are rare in R packages, so either adding them or narrowing that sentence to the include options is fine.

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.

Added all five in 764d6bb with a gtest, and narrowed the docs sentence to "relative paths in include and other path options".

kevinushey and others added 5 commits November 4, 2026 12:59
A location-less diagnostic was only surfaced when its message quoted a
line of compile_flags.txt verbatim, which missed clang's bad-value
errors ("unsupported argument 'haswel' to option '-march='") and
anything quoting a resolved path. Replace the substring rule with a
baseline: parse an empty copy of the file with just the generated flags,
collect the diagnostics clang reports against that command line, and
show the ones from the real parse that are not in it. The baseline is
cached per distinct set of generated flags.

Addresses #19367
-iframework, -cxx-isystem, -ivfsoverlay, -fmodule-map-file= and
--gcc-toolchain= now resolve against the compile_flags.txt directory
like the include options do, and the user guide says which paths this
applies to.

Addresses #19367
…gs file is gone

resolveCompileFlagPaths() rebased every non-absolute operand against the flags
file directory, including clang's '=' and '$SYSROOT' sysroot prefixes, which
turned '-I=/usr/include/foo' into a path that doesn't exist.

A PCH built with flags from a compile_flags.txt was only pruned when another
user-flags PCH was built, so deleting the file left the ~25MB variant behind
until the next forced rebuild. The variants built from any flags file we have
read that has since been removed or emptied are now dropped whenever the PCH
directory is consulted.
@kevinushey
kevinushey merged commit 1cfdcdd into main Nov 5, 2026
1 of 7 checks passed
@kevinushey
kevinushey deleted the bugfix/19367-clang-error-limit branch November 5, 2026 17:38
kevinushey added a commit that referenced this pull request Nov 18, 2026
* limit compile_flags.txt to an allow-list of parsing flags

Only flags that shape how a file is parsed and diagnosed (macros, include
paths, language and target, warnings, common -f features) are passed on to
libclang; the rest are dropped and reported as warnings at the top of the
file. The allow-list and the relative-path resolution share one option table.

Follow-up to #19393.

* say why a compile_flags.txt entry was ignored, and only warn on indexed files

Also allows -msse4, bare -W and -fno-sanitize=, rejects -I-, and only reports
the next line along with a rejected option that takes a value.

* let common code generation flags through compile_flags.txt

* report common link options in compile_flags.txt with their values

-framework, -rpath, -undefined and the like read the next argument as their
value, so a pasted link line reports '-framework Foo' as one ignored entry
rather than two.

* drop compile_flags.txt flags that stop libclang from parsing the file

Some allowed flags keep clang from setting up the target at all, such as
-mtune=haswell or -mfpmath=sse on arm64, or an invalid -std= value. libclang
then returns no translation unit and no diagnostics, so the file loses every
diagnostic. We now check the flags with a parse of an empty file, and when
they fail, add them one at a time (target-picking flags first) to find the
ones at fault. Those are dropped and reported on line 1 like any other
ignored entry, and the rest still apply. The result is cached per set of
flags.

* drop the empty-file parse check for compile_flags.txt flags

This reverts db27482. A flag that stops libclang from parsing the file is
reported by the existing line-1 error instead.

* stop allowing -mfpmath= in compile_flags.txt

It doesn't change the parse, and an x86 build's -mfpmath=sse stops libclang
from parsing the file at all on arm64.
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.

Setting -ferror-limit in .Rproj.user compilation-database/config.json file

2 participants