Repository navigation
limit compile_flags.txt to an allow-list of parsing flags - #19667
Conversation
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.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
gtritchie
left a comment
There was a problem hiding this comment.
Feedback posted inline. Nothing here is blocking: the comments are about warning text, a few allowlist gaps, and tests for them.
| { | ||
| std::string message = | ||
| "'" + flag + "' in " + module_context::createAliasedPath(flagsFile) + | ||
| " was ignored; only flags that affect how files are parsed are supported"; |
There was a problem hiding this comment.
This message goes out for every rejected entry, including supported options that are rejected only because of their value: a trailing -D, -I followed by a line starting with -, -x ast, -std c++17 (no =), or --gcc-toolchain gcc. The docs list -D, -I, -x, -std= and --gcc-toolchain= as supported, so being told only parse-affecting flags are supported doesn't point at the actual problem (a missing value, a value starting with -, an unsupported language, a missing =).
Could filterCompileFlags record why an entry was rejected, so these get their own message, such as "'-I' needs a value on the next line"?
There was a problem hiding this comment.
Fixed in 71c5be0. Each rejected entry now carries its own reason: a missing value ('-D' needs a value), a next-line value that begins with - or @, an unsupported -x value ('-x' doesn't support the value 'ast'), a value that belongs after an = (-std c++17, -std=, --gcc-toolchain gcc), and -I-. Unsupported options keep the general message.
|
|
||
| // flags we don't pass on to libclang are reported, so they aren't | ||
| // mistaken for flags that had no effect | ||
| for (const std::string& flag : rejectedFlags) |
There was a problem hiding this comment.
These warnings are added before the TU check, so they also appear on files that never get compile args. LintManager requests get_cpp_diagnostics for any C/C++ document. Take a .cpp without an Rcpp include, outside a package's src/ or inst/include, next to a compile_flags.txt written for clangd: it has no config, so tu.empty(), and the indexable check below suppresses the "could not parse" message. But it now gets a "was ignored" warning for each rejected flag, where before this PR it showed nothing.
Emitting these only when the file is indexable (as the parse-failure message already does) would keep the two consistent.
There was a problem hiding this comment.
Fixed in 71c5be0. The warnings now appear only on a file that is indexed, the same condition the parse-failure message uses. test-cpp.R covers a plain .cpp next to a compile_flags.txt.
| if (boost::algorithm::starts_with(flag, "-W")) | ||
| return flag.size() > 2 && flag.find(',') == std::string::npos; | ||
|
|
||
| // a feature ('-fopenmp', '-fno-exceptions', '-mavx2', '-mno-sse4') |
There was a problem hiding this comment.
-mno-sse4 is given as an example here, but kTargetFeatureFlags has only sse4.1 and sse4.2, so -msse4 and -mno-sse4 are both rejected. Both are clang options; with Apple clang 21, -msse4 defines __SSE4_1__ and __SSE4_2__. Adding sse4 to the list would make the code match the example.
| // a warning ('-Wall', '-Wno-unused', '-Werror=format'); the only other | ||
| // '-W' options, '-Wa,', '-Wl,' and '-Wp,', pass arguments on to other tools | ||
| if (boost::algorithm::starts_with(flag, "-W")) | ||
| return flag.size() > 2 && flag.find(',') == std::string::npos; |
There was a problem hiding this comment.
Bare -W is rejected by the size() > 2 check, but it's a valid clang (and GCC) spelling of -Wextra: clang -### -fsyntax-only -W passes -W through to cc1 and enables warnings such as -Wunused-parameter. The comment above also implies the comma forms are the only other -W options.
There was a problem hiding this comment.
Fixed in 71c5be0. Bare -W is allowed now, and the comment says why a comma is rejected. That also turns away a list given to -Wundef-prefix=, which I've left rejected to keep the comma rule simple.
| "-fconstexpr-depth", "-fconstexpr-steps", "-fdiagnostics-color", "-ferror-limit", | ||
| "-fexec-charset", "-fgnuc-version", "-finput-charset", "-fmacro-backtrace-limit", | ||
| "-fms-compatibility-version", "-fmsc-version", "-fnew-alignment", "-fopenmp", | ||
| "-fopenmp-version", "-fsanitize", "-fspell-checking-limit", |
There was a problem hiding this comment.
-fsanitize= is allowed here, but -fno-sanitize= isn't: it's not in this set, and the -f feature path only strips no- for names in kFeatureFlags. So with -fsanitize=address,undefined and -fno-sanitize=alignment, the first is passed on and the second is dropped with a warning, which leaves a different sanitizer set from the real build. clang accepts -fno-sanitize= as usual.
| // reported (and dropped) on its own | ||
| std::string rejected = flag; | ||
| if (boost::algorithm::starts_with(flag, "-") && i + 1 < flags.size() && isPlainValue(flags[i + 1])) | ||
| rejected += " " + flags[++i]; |
There was a problem hiding this comment.
This joins the next plain argument onto any rejected flag, including flags that take no value. -ftime-trace followed by other.cpp is reported as '-ftime-trace other.cpp', and -fplugin=x.so followed by src/extra.c as '-fplugin=x.so src/extra.c', which reads as if the file were the option's value. Both are dropped either way, so only the report is affected.
There was a problem hiding this comment.
Fixed in 71c5be0. The next line is joined only after an option that takes a value: our own options, the setting options (-std then c++17), and the unsupported options clang reads that way (-o, -MF, -Xclang, ...). Otherwise it's reported on its own, as neither a flag nor the value of a supported option.
| { "-iframework", JoinedValue::Direct, true, true, nullptr, nullptr }, | ||
| { "-ivfsoverlay", JoinedValue::Direct, true, true, nullptr, nullptr }, | ||
| { "-isysroot", JoinedValue::Direct, true, true, nullptr, nullptr }, | ||
| { "-I", JoinedValue::Direct, true, true, nullptr, nullptr }, |
There was a problem hiding this comment.
-I- matches here as -I with the path -, so it's allowed, and resolveCompileFlagPaths then rewrites it to -I<flags dir>/-. clang rejects -I- itself ("'-I-' not supported, please use -iquote instead"), and that error would otherwise be shown at the top of the file. Instead the user gets a nonexistent include directory and no message. The rewrite predates this PR, but now that flags are checked here, rejecting an exact -I- would report it.
There was a problem hiding this comment.
Fixed in 71c5be0. An exact -I- is rejected with clang's own hint (use -iquote), and resolveCompileFlagPaths leaves it alone.
| std::vector<std::string> rejectedFlags; | ||
| bool hasUserFlags = | ||
| !flagsFile.isEmpty() && | ||
| !filterCompileFlags(readCompileFlags(flagsFile), &rejectedFlags).empty(); |
There was a problem hiding this comment.
Minor: this reads and filters the flags file separately from compileFlagsForSource, which getTranslationUnit calls below, and removeOrphanedUserFlagsPchs reads it again when PCHs are in use. If compileFlagsForSource (or a shared helper) returned the rejected entries along with the flags, the file would be read once, and the warnings would always describe the same version of the file the parse used.
There was a problem hiding this comment.
I looked into this, but I'd rather keep the separate read. The parse gets its arguments through the compileArgsForTranslationUnit callback in core/libclang, which can't return the rejected entries. So reading the file once would mean caching the filter result per flags file and trusting that it came from this parse. That doesn't hold for a file we don't index: another source file sharing the same flags file may have filled the cache. The reads are microseconds apart, and the next lint pass corrects any mismatch. The existing code already prefers re-reading this small file over tracking it.
| EXPECT_EQ(resolveCompileFlagPaths(flags, pkg_), flags); | ||
| } | ||
|
|
||
| TEST_F(CompileFlagsTest, AllowsFlagsThatShapeTheParse) |
There was a problem hiding this comment.
None of the cases from my other comments are covered: -msse4/-mno-sse4, bare -W, -fno-sanitize=, or a -fno-/-mno- form of a name that isn't in the lists. The only negated -m case tested is -mno-sse4.2, whose name is listed.
There was a problem hiding this comment.
Added in 71c5be0: -msse4/-mno-sse4, bare -W, -fno-sanitize=, unlisted -fno-/-mno- names, -I- (filtering and path resolution), the reason for each kind of rejection, and when a value is joined to a rejected option.
| }; | ||
|
|
||
| // Language and diagnostic features, as '-f<name>' or '-fno-<name>' | ||
| const std::set<std::string> kFeatureFlags = { |
There was a problem hiding this comment.
Not a bug, but worth a look: common build flags such as -fno-omit-frame-pointer, -ffunction-sections, -ffp-contract=, -mfpmath=, -mstackrealign and -ffile-prefix-map= aren't listed, so pasting a project's compiler flags into compile_flags.txt gives a warning per flag at the top of every file. Dropping them doesn't change the parse; the question is whether the warnings are worth the noise, or whether known-harmless flags could be dropped without one.
There was a problem hiding this comment.
Agreed, the noise isn't worth it. In b96c641 these flags are allowed: the six you listed, plus -fdata-sections (usually paired with -ffunction-sections). Each one was checked against clang. None reads a file, and they reach libclang unchanged, so a flag that doesn't fit the target (-mfpmath=sse on arm64) gets clang's own diagnostic, as -march=haswell already does. The User Guide mentions them too.
…ed 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.
gtritchie
left a comment
There was a problem hiding this comment.
Thanks for the changes. The earlier comments are addressed, and I agree with keeping the separate read. Two new comments on b96c641: allowing -mfpmath= stops libclang from parsing the file on arm64, and a minor reporting gap in kUnsupportedSeparateOptions.
| // Options that take their value only after an '=', as in '-std=c++17' | ||
| const std::set<std::string> kSettingOptions = { | ||
| "--target", "-std", "-stdlib", | ||
| "-march", "-mcpu", "-mtune", "-mabi", "-mfpu", "-mfpmath", "-mfloat-abi", |
There was a problem hiding this comment.
-mfpmath= behaves differently from -march=haswell on a non-x86 target. clang rejects -mfpmath=sse while setting up the target ("unknown FP unit 'sse'"), so libclang doesn't produce a translation unit at all. Calling the system libclang (CommandLineTools, arm64) directly:
| flag | clang_parseTranslationUnit2 |
|---|---|
-march=haswell |
parses, with "unsupported argument 'haswell' to option '-march='" |
-msse2 |
parses, with "unsupported option '-msse2' for target ..." |
-mfpmath=sse |
err=1, no translation unit |
So someone on Apple Silicon or arm64 Linux who pastes x86 build flags (-mfpmath=sse -msse2 -mstackrealign) gets only "libclang could not parse this file" and loses every other diagnostic for the file. Before b96c641 the flag was dropped with a warning and the file still parsed. Leaving -mfpmath out of this list would restore that.
There was a problem hiding this comment.
Confirmed: on arm64, -mfpmath=sse gives no translation unit, and so do -mtune=haswell, -mcpu=haswell and -mabi=sysv, as well as -march=armv8-a on x86_64. libclang only reports that it failed; the "unknown target CPU" message goes to stderr.
Rather than take these off the list, db27482 checks the flags with a parse of an empty file, cached per set of flags. When that fails, it adds them one at a time, with the flags that pick the target (--target=, -target, -arch, -m32, -m64) first, and drops and reports the ones that stop the parse:
'-mfpmath=sse' in ~/pkg/src/compile_flags.txt was ignored; libclang can't parse the file with it; check that its value is valid for this platform
So your example now loses only -mfpmath=sse. -msse2 and -mstackrealign still apply (-msse2 reports its own "unsupported option" on line 1), and the rest of the file is diagnosed. The same check covers an invalid -std=, which used to fail the whole parse; test-cpp.R now expects a warning for -std=c++99 instead.
|
|
||
| // Options we don't support that clang reads the next argument as the value | ||
| // of; only so that the report shows such a value along with its option | ||
| const std::set<std::string> kUnsupportedSeparateOptions = { |
There was a problem hiding this comment.
Minor, report-only: a few options that clang reads with a separate value aren't listed, so their value is reported on its own as "neither a flag nor the value of a supported option". Examples are -framework, -rpath, -arch_only, --config and -l; clang -### -framework Foo reports "unknown argument: '-framework Foo'". A pasted macOS link line (-framework then Foo) gets two warnings instead of one.
There was a problem hiding this comment.
Added in 4897d25: the five you listed, plus -undefined (as in R's -undefined dynamic_lookup on macOS), -weak_framework and -install_name.
To check what else was missing, I asked LLVM 23 and Apple clang 21 which spellings report "argument to '...' is missing" when given last: 182 options take a separate value. The 126 still unlisted are mostly Darwin ld options (-sectcreate, -seg1addr, ...), offload, HLSL and Windows SDK settings, and leftovers from gcj (--classpath). I've left them out, since this list only affects how the report groups entries, but can add the whole set if you'd prefer it complete.
-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.
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.
|
|
||
| s_compileFlagsCache[key] = flags; | ||
| CompileFlagsRecord record; | ||
| record.flags = flags; |
There was a problem hiding this comment.
Now that the flags passed on depend on the source (its extension and generated args), one record per flags file can't describe them all, and any caller overwrites it. That includes getCppDiagnosticsJson for a file that isn't indexed: generatedCompileArgs() is empty, so the probe is skipped and the unprobed flags are recorded.
For example, a project-root compile_flags.txt with -DFOO and -mfpmath=sse on arm64:
src/a.cppis probed to-DFOO, and its PCH variant is built withhash("-DFOO").- The user opens
tools/x.cpp, which isn't indexed. Its diagnostics record-DFOO,-mfpmath=ssewithusable = true. compile_flags.txtis deleted.removeOrphanedUserFlagsPchslooks for the suffix of the recorded flags and leaves the real variant on disk.
The same overwrite also resets usable after a.cpp found that no flag parses, so that variant is kept too.
Skipping the record when generatedArgs is empty would cover the first case. Recording the suffix used when a PCH is actually built would make the cleanup independent of which source read the file last.
There was a problem hiding this comment.
The probe is gone: 024e3fe reverts db27482, so the flags no longer depend on the source and one record per flags file describes them again. Instead, c34aab1 takes your round-2 suggestion and drops -mfpmath= from the list. Other allowed flags that stop the parse (-mtune=haswell on arm64, -std=c++99) get the existing line-1 "libclang could not parse this file; check the flags in compile_flags.txt" error.
|
|
||
| std::string filename = srcFile.getAbsolutePath(); | ||
| bool generatedArgsParse = true; | ||
| auto parses = [&](const std::vector<std::string>& trial) { |
There was a problem hiding this comment.
The empty-file probe still processes the user's -include/-imacros flags, and without the PCH, so a heavy forced include is parsed in full on every probe. With the system libclang on arm64, an empty-file parse with -include Rcpp.h (plus the R and Rcpp include paths) takes about 0.45 s, against about 0.1 s without it; both times include starting the test program.
That cost lands on the diagnostics/completion RPC at least once per edit of compile_flags.txt. When an entry stops the parse, it's paid once per entry: with -include Rcpp.h and ~20 other flags, that's roughly 9-10 s. When the generated args themselves don't parse, nothing is cached, so the two probes repeat on every compileArgsForTranslationUnit call.
A forced include can't cause the target-setup failures this is looking for, so leaving -include/-imacros out of the probe trials (while still passing them on) should avoid the cost.
There was a problem hiding this comment.
Moot after 024e3fe, which removes the probe. You were right about the cost: on arm64 I measured about 400 ms per empty-file parse with -include Rcpp.h, against about 5 ms without.
| { | ||
| RejectedCompileFlag rejected; | ||
| rejected.flag = core::algorithm::join(entries[i], " "); | ||
| rejected.reason = "libclang can't parse the file with it; check that its value is valid for this platform"; |
There was a problem hiding this comment.
Nit: this wording also goes to entries that aren't platform-specific, such as -std=c++99, which test-cpp.R now exercises: "'-std=c++99' ... was ignored; libclang can't parse the file with it; check that its value is valid for this platform". Just "check that its value is valid" would be accurate for every entry.
There was a problem hiding this comment.
This message went with the probe in 024e3fe. -std=c++99 is back to the generic parse-failure error, which test-cpp.R checks.
This reverts db27482. A flag that stops libclang from parsing the file is reported by the existing line-1 error instead.
It doesn't change the parse, and an x86 build's -mfpmath=sse stops libclang from parsing the file at all on arm64.
gtritchie
left a comment
There was a problem hiding this comment.
Thanks, all comments are addressed.
Intent
Follow-up to #19393 (#19367), which added support for a clangd-style
compile_flags.txt. Flags from that file were passed to libclang as-is. This PR restricts them to the flags that shape how a file is parsed and diagnosed: macro definitions, include paths and forced includes, the language and target, warnings, and common-flanguage and diagnostic features, plus a few common code generation flags (such as-fno-omit-frame-pointer) that don't affect the parse but are accepted so that a build's flags can be pasted in. Other flags, such as output options, response files, or options that pass arguments on to other tools, are dropped and reported as warnings at the top of the file.Approach
filterCompileFlags()inCompilationDatabase.cppchecks each argument against one table of supported options that take a value.resolveCompileFlagPaths()uses the same table, so the two always agree on how an option takes its value. For the forms without a separate value, it uses explicit sets: standalone flags,-<option>=<value>settings, and-f/-fno-and-m/-mno-feature names.-Woptions are accepted as long as they contain no comma, since-Wa,,-Wl,and-Wp,pass arguments on to other tools (this also turns away a list given to-Wundef-prefix=).-fand-muse name lists rather than prefix rules, because those prefixes also cover options that aren't language or target settings, such as-module-dependency-dir. Every listed name was checked against clang's option list (Apple clang 21, LLVM 23).-include-pchand-iframeworkwithsysrootaren't mistaken for-includeand-iframeworkwith a value.-or@. Each argument passed on is then either a flag that was checked or a plain value, whatever clang makes of the arguments around it.-or@, an unsupported-xlanguage, a value that belongs after an=, or clang's unsupported-I-).-mfpmath=isn't supported. It doesn't change the parse, and an x86 build's-mfpmath=ssestops libclang from parsing anything on arm64. An allowed flag can still do that when its value is invalid or names a CPU for another architecture (-std=c++99, or-mtune=haswellon arm64). That case is reported by the existing line-1 error, "libclang could not parse this file; check the flags in compile_flags.txt".'-o out.o' ... was ignored). After any other rejected flag, it's reported on its own.compile_flags.txtnext to it.--gcc-toolchainand-fmodule-map-filetake the next argument as their value. clang rejects both bare forms, and they are now rejected here as well.-include-pchis no longer supported. It conflicts with the precompiled header RStudio builds for Rcpp.Automated Tests
CompilationDatabaseTests.cppcover allowed and rejected flags, values given on the next line, how rejected options and their values are reported and the reason given for each, and removal of the precompiled-header variant once no allowed flags are left.test-cpp.Rnow expects RStudio to report the unknown--bogus-flagitself, and adds a libclang test showing that rejected flags never reach libclang while allowed flags around them still apply. It also checks that a reason reaches the warning, and that a plain.cppthat isn't indexed gets no warnings.--scope r --filter 'cpp|linter'133/133.QA Notes
In a package, create
src/compile_flags.txtwith:Open a
.cppfile insrc/that has#ifndef FROM_FLAGS/#error/#endif. Expect no error from the#error, and warnings on line 1 for'-o out.o'and'-Xclang'.-ferror-limit=1stays in effect.Documentation
The User Guide's C / C++ diagnostics section (
diagnostics.qmd) now lists the supported flags. The unreleased #19367 entry inNEWS.mdnow says that the supported flags are those that affect parsing.Checklist
NEWS.md(not required: this changes an unreleased feature; its existing entry was updated)