[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

Nathan Ridge via cfe-commits cfe-commits at lists.llvm.org
Sat Feb 24 23:19:04 PST 2024


HighCommander4 wrote:

> I thought the `GuessObjC` flag would allow clangd to skip the guessing ObjC part for those "users who merely use these libraries (and so may open them in the editor to look at the header, but will not try to format it)".

Ok, I see what you're getting at.

Clangd calls into `guessLanguage()` via `format::getStyle()` which [calls `guessLanguage()`](https://searchfox.org/llvm/rev/60a904b2ad9842b93cc5fa0ad5bda5e22c550b7e/clang/lib/Format/Format.cpp#3956).

I audited clangd's code to see what it uses the returned `FormatStyle` for:

 1. When hovering over a symbol, we call `format::reformat()` on the code snippet shown in the hover (e.g. definition of the variable whose use you are hovering over).
 2. Formatting edits (via `format::cleanupAroundReplacements()` and `format::formatReplacements()`) made by various clangd operations (e.g. accepting a code completion proposal, performing a rename or other code action, etc.)
 3. Inserting new `#include` directives (e.g. associated with a code completion proposal, or a quick-fix for a diagnostic). For this one, clangd inspects `IncludeStyle` manually to choose an insertion point.
 4. Formatting the whole file (or a selected range of text) using `format::reformat()`.

Of these, (1) is the only one that can be triggered without modifying the file.

So, if `format::getStyle()` had a `GuessObjC` parameter (which it propagated into `guessLanguage()`), I think we could refactor things such that (1) used `GuessObjC=false` and the others used `GuessObjC=true`. (We may even be able to use `GuessObjC=false` for (2) and (3), since those are just formatting a small amount of code.)

@owenca if you're ok in principle with this libFormat API extension (adding an optional `GuessObjC` parameter to `format::getStyle()`), I'm happy to try prototyping these changes in clangd.

https://github.com/llvm/llvm-project/pull/78925


More information about the cfe-commits mailing list