1189 Commits

Author SHA1 Message Date
Ilya Biryukov
5723fce088
[Format] Fix isStartOfName to recognize attributes (#76804)
This addresses a problem with formatting attributes. Some context:
- eaff083035c8 changed `isStartOfName` to fix problems inside
`#pragma`s, but this behavior changed formatting of attribute macros in
an undesirable way.
- efeb546865c233dfa7706ee0316c676de9f69897 changed Google format style
to fix some widely used attributes.

Instead of changing the format style, this commit specializes behavior
introduced in eaff083035c8 to `#pragma`s. This seems to work well in
both cases.

Also update the test with two `GUARDED_BY` directives. While the
formatting after efeb546865c233dfa7706ee0316c676de9f69897 seems better,
this case is rare enough to not warrant the extra complexity. We are
reverting it back to the state it had before
efeb546865c233dfa7706ee0316c676de9f69897.

---------

Co-authored-by: Owen Pan <owenpiano@gmail.com>
2024-01-15 14:57:05 +01:00
rmarker
60a9874f54
[clang-format] Add PenaltyBreakScopeResolution option. (#78015)
Resolves #78014
2024-01-14 20:55:44 +01:00
Gedare Bloom
b2c0c6f3f2
[clang-format]: Split alignment of declarations around assignment (#69340)
Function pointers are detected as a type of declaration using
FunctionTypeLParen. They are aligned based on rules for
AlignConsecutiveDeclarations. When a function pointer is on the
right-hand side of an assignment, the alignment of the function pointer
can result in excessive whitespace padding due to the ordering of
alignment, as the alignment processes a line from left-to-right and
first aligns the declarations before and after the assignment operator,
and then aligns the assignment operator. Injection of whitespace by
alignment of declarations after the equal sign followed by alignment of
the equal sign results in the excessive whitespace.

Fixes #68079.
2024-01-10 19:35:03 -08:00
Ilya Biryukov
efeb546865
[clang-format] Add common attribute macros to Google style (#76239)
We have found that 199fc973ced20016b04ba540cf63a1d4914fa513 regresses
formatting of our codebases because we do not properly configure the
names of attribute macros.

`GUARDED_BY` and `ABSL_GUARDED_BY` are very commoon in Google codebases
so it is reasonable to include them by default to avoid the need for
extra configuration in every Google repository.
2023-12-22 15:07:43 +01:00
Owen Pan
401f0396c3
[clang-format] Fix a bug in IndentExternBlock: NoIndent (#75731)
Fixes #36620.
Fixes #75719.
2023-12-17 15:07:11 -08:00
Kazu Hirata
f3dcc2351c
[clang] Use StringRef::{starts,ends}_with (NFC) (#75149)
This patch replaces uses of StringRef::{starts,ends}with with
StringRef::{starts,ends}_with for consistency with
std::{string,string_view}::{starts,ends}_with in C++20.

I'm planning to deprecate and eventually remove
StringRef::{starts,ends}with.
2023-12-13 08:54:13 -08:00
Owen Pan
3791b3fca6
[clang-format][NFC] Clean up the driver and getStyle() in Format.cpp (#74794) 2023-12-08 15:23:01 -08:00
Jared Grubb
c45a66ecd4 [clang-format] ObjCPropertyAttributeOrder to sort ObjC property attributes
Add a style option to specify the order that property attributes should
appear in ObjC property declarations (property attributes are things like
`nonatomic, strong, nullable`).

Closes #71323.

Differential Revision: https://reviews.llvm.org/D150083
2023-12-01 17:41:30 -08:00
Owen Pan
39faf13dde
[clang-format] Add BreakAdjacentStringLiterals option (#73432)
Closes #70451.
2023-11-27 13:01:16 -08:00
Vlad Serebrennikov
497b2ebb9e
[clang-format] Change LLVM style to BreakAfterAttributes == ABS_Leave (#70360)
This patch addresses some examples of bad formatting in Clang. The following commit contains only changes suggested by clang-format: 21689b56d1.
I believe it's a net negative on readability, with a couple of particularly bad cases. Highlights:
```diff
-    [[clang::preferred_type(bool)]]
-    mutable unsigned CachedLocalOrUnnamed : 1;
+    [[clang::preferred_type(bool)]] mutable unsigned CachedLocalOrUnnamed : 1;
```
```diff
-    [[clang::preferred_type(TypeDependence)]]
-    unsigned Dependence : llvm::BitWidth<TypeDependence>;
+    [[clang::preferred_type(TypeDependence)]] unsigned Dependence
+        : llvm::BitWidth<TypeDependence>;
```
```diff
-    [[clang::preferred_type(ExceptionSpecificationType)]]
-    unsigned ExceptionSpecType : 4;
+    [[clang::preferred_type(
+        ExceptionSpecificationType)]] unsigned ExceptionSpecType : 4;
```
Style guides doesn't appear to have an opinion on this matter.
2023-10-28 16:02:03 +04:00
Backl1ght
69209e30a7 [clang-format] AllowShortCompoundRequirementOnASingleLine
clang-format brace wrapping did not take requires into consideration,
compound requirements will be affected by BraceWrapping.AfterFunction.

Closes #59412.

Differential Revision: https://reviews.llvm.org/D139834
2023-10-25 05:13:50 -07:00
Owen Pan
0374bbba4c
[clang-format] Add a new style for the clang-format source code (#69814) 2023-10-22 23:01:27 -07:00
Omar Ahmed
7c15dd60ec [clang-format] Add space in placement new expression
Add AfterPlacementNew option to SpaceBeforeParensOptions to have more
control on placement new expressions.

Fixes #41501
Relates to #54703

Differential Revision: https://reviews.llvm.org/D127270
2023-10-20 03:16:28 -07:00
Owen Pan
84cbd9f4ff [clang-format] Fix an error message 2023-10-05 19:24:08 -07:00
Owen Pan
7db211bda7 [clang-format][NFC] Remove the unused separateDefinitionBlocks()
Also, fixed a formatting error introduced in 84e3fdfc6523.
2023-09-24 19:25:23 -07:00
Björn Schäpers
84e3fdfc65
[clang-format] BreakBeforeNoexceptSpecifier option added (#65808)
It really bugs me that it breaks to
``` c++
...) noexcept(
    noexcept(condition)...
```

This is a fix for people like me.
2023-09-09 22:31:58 +02:00
Owen Pan
91c4db0061 [clang-format][NFC] Replace !is() with isNot()
Differential Revision: https://reviews.llvm.org/D158571
2023-08-24 01:27:24 -07:00
Björn Schäpers
f274ffc303 [clang-format][NFC] Resort IO Mapping 2023-08-02 11:50:14 +02:00
Gedare Bloom
c669541c96 [clang-format] Add SpacesInParens with SpacesInParensOptions
This is a refactoring of:
- SpacesInConditionalStatement
- SpacesInCStyleCastParentheses
- SpaceInEmptyParentheses
- SpacesInParentheses

These are now options under the new Style Option: SpacesInParens. The
existing options are maintained for backward compatibility.

Within SpacesInParens, there are currently options for:
- Never
- Custom

The currently available options for Custom are:
- InConditionalStatements
- InCStyleCasts
- InEmptyParentheses
- Other

Setting InConditionalStatements and Other to true enables the same space
additions as SpacesInParentheses.

This refactoring does not add or remove any existing features, but it makes
it possible to more easily extend and maintain the addition of spaces within
parentheses.

Related to #55428.

Differential Revision: https://reviews.llvm.org/D155239
2023-07-24 19:27:23 -07:00
Galen Elias
74720d1b33 [clang-format] Add AlignConsecutiveShortCaseStatements
This adds a new AlignConsecutiveShortCaseStatements option in line with the
existing AlignConsecutive* options , which when
AllowShortCaseLabelsOnASingleLine is enabled will align the tokens after the
case statement's colon. This also adds a AlignCaseColons option to allow
aligning the case label colon itself rather than the token after it.

Fixes #55475.

Differential Revision: https://reviews.llvm.org/D151761
2023-07-24 18:39:25 -07:00
Owen Pan
87ad34ffdc Revert "[clang-format] Add AlignConsecutiveShortCaseStatements"
This reverts commit 4ba00844174db562d2bd8b15dab6aac605eddf57.
2023-07-24 18:37:42 -07:00
Owen Pan
ac6e55146f Revert "Revert "[clang-format] Add AlignConsecutiveShortCaseStatements""
This reverts commit 4f093b31669a4f8e417259583141159586a05b28.
2023-07-24 18:24:30 -07:00
Owen Pan
4f093b3166 Revert "[clang-format] Add AlignConsecutiveShortCaseStatements"
This reverts commit 4ba00844174db562d2bd8b15dab6aac605eddf57 due to missing
authorship.
2023-07-24 18:19:38 -07:00
Owen Pan
4ba0084417 [clang-format] Add AlignConsecutiveShortCaseStatements
This adds a new AlignConsecutiveShortCaseStatements option in line with the
existing AlignConsecutive* options , which when
AllowShortCaseLabelsOnASingleLine is enabled will align the tokens after the
case statement's colon. This also adds a AlignCaseColons option to allow
aligning the case label colon itself rather than the token after it.

Fixes #55475.

Differential Revision: https://reviews.llvm.org/D151761
2023-07-24 18:16:21 -07:00
Owen Pan
5c106f7b94 [clang-format] Add TypeNames option to disambiguate types/objects
If a non-keyword identifier is found in TypeNames, then a *, &, or && that
follows it is annotated as TT_PointerOrReference.

Differential Revision: https://reviews.llvm.org/D155273
2023-07-18 14:18:40 -07:00
Owen Pan
3a6a0702c2 [clang-format] Add an option to remove redundant parentheses
Differential Revision: https://reviews.llvm.org/D154484
2023-07-11 16:33:19 -07:00
Sedenion
899c867794 [clang-format] Fixed bad performance with enabled qualifier fixer.
This fixes github issue #57117: If the "QualifierAlignment"
option of clang-format is set to anything else but "Leave", the
"QualifierAlignmentFixer" pass gets enabled. This pass scales
quadratically with the number of preprocessor branches, i.e.
with the number of elements in TokenAnalyzer::UnwrappedLines.
The reason is that QualifierAlignmentFixer::process() generates
the UnwrappedLines, but then QualifierAlignmentFixer::analyze()
calls LeftRightQualifierAlignmentFixer::process() several times
(once for each qualifier) which again each time generates the
UnwrappedLines.

This commit gets rid of this double loop by registering the
individual LeftRightQualifierAlignmentFixer passes directly in
the top most container of passes (local variable "Passes" in
reformat()).
With this change, the original example in the github issue #57117
now takes only around 3s instead of >300s to format.

Since QualifierAlignmentFixer::analyze() got deleted, we also
no longer have the code with the NonNoOpFixes. This causes
replacements that end up not changing anything to appear in the
list of final replacements. There is a unit test to check that
this does not happen: QualifierFixerTest.NoOpQualifierReplacements.
However, it got broken at some point in time. So this commit
fixes the test. To keep the behavior that no no-op replacements
should appear from the qualifier fixer, the corresponding code
from QualifierAlignmentFixer::analyze() was moved to the top
reformat() function. Thus, is now done for **every** replacement
of every formatting pass. If no-op replacements are a problem
for the qualifier fixer, then it seems to be a good idea to
filter them out always.

See
https://github.com/llvm/llvm-project/issues/57117#issuecomment-1546716934
for some more details.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D153228
2023-07-03 11:54:33 +01:00
Owen Pan
829ed96b77 Reland [clang-format] Add the KeepEmptyLinesAtEOF option 2023-06-13 10:02:10 -07:00
Paul Kirth
b6a718016c [clang-format] Add test case for issue 63170
After https://reviews.llvm.org/D151954 we've noticed some issues w/
clang-format behavior, as outlined in
https://github.com/llvm/llvm-project/issues/63170.

Valid C/C++ files, that were previously accepted, are now rejected by
clang-format, emitting the message:

"The new replacement overlaps with an existing replacement."

This reverts commit 4b9764959dc4b8783e18747c1742ab164e4bc4ee and
d2627cf88d2553a4c2e850430bdb908a4b7d2e52, which depends on it.

Reviewed By: phosek

Differential Revision: https://reviews.llvm.org/D152473
2023-06-09 20:10:19 +00:00
Owen Pan
d2627cf88d [clang-format] Add the KeepEmptyLinesAtEOF option
Adds an option KeepEmptyLinesAtEOF to keep empty lines (up to
MaxEmptyLinesToKeep) before EOF. This remedies the probably unintentional
change in behavior introduced in 3d3ea84a4f8f, which started to always
remove empty lines before EOF.

Fixes #56054.
Fixes #63150.

Differential Revision: https://reviews.llvm.org/D152305
2023-06-07 14:17:58 -07:00
sstwcw
24231df9b8 [clang-format] Parse the Verilog language option in configuration
Reviewed By: HazardyKnusperkeks, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D151632
2023-06-02 14:59:27 +00:00
Ben Hamilton
85670ac868 [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in ObjC language guesser
This adds to the ObjC language guesser a few more common macros used
in ObjC headers. These can help distinguish ObjC headers which
otherwise lack ObjC types from C++ headers.

Contributed by danblakemore.

Tested: New tests included. Ran unit tests with:
  ```
  % cmake -S llvm -B build -G Ninja && \
    ninja -C build FormatTests && \
    ./build/tools/clang/unittests/Format/FormatTests --gtest_filter="*FormatTestObjC*"

  (snip)
  [----------] 24 tests from FormatTestObjC (265 ms total)

  [----------] Global test environment tear-down
  [==========] 26 tests from 2 test suites ran. (270 ms total)
  [  PASSED  ] 26 tests.
  ```

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D151578
2023-05-30 11:12:03 -06:00
Kazu Hirata
ed1539c6ad Migrate {starts,ends}with_insensitive to {starts,ends}_with_insensitive (NFC)
This patch migrates uses of StringRef::{starts,ends}with_insensitive
to StringRef::{starts,ends}_with_insensitive so that we can use names
similar to those used in std::string_view.

Note that the llvm/ directory has migrated in commit
6c3ea866e93003e16fc55d3b5cedd3bc371d1fde.

I'll post a separate patch to deprecate
StringRef::{starts,ends}with_insensitive.

Differential Revision: https://reviews.llvm.org/D150506
2023-05-16 10:12:42 -07:00
Manna, Soumi
babe8629d7 [NFC][Clang] Fix static analyzer tool remarks about large copies by values in Format.cpp file
Reported by Static Analyzer Tool, Coverity:

Inside "Format.cpp" file, in clang::format::internal::reformat(clang::format::FormatStyle const &, llvm::StringRef, llvm::ArrayRef<clang::tooling::Range>, unsigned int, unsigned int, unsigned int, llvm::StringRef, clang::format::FormattingAttemptStatus *)::[lambda(clang::format::Environment const &) (instance 4)]::operator ()(clang::format::Environment const &): A very large function call parameter exceeding the high threshold is passed by value.

pass_by_value: Capturing variable S of type clang::format::FormatStyle (size 808 bytes) by value, which exceeds the high threshold of 512 bytes

This patch uses original code but with an init capture that does a move instead of a copy.

Reviewed By: tahonermann, erichkeane, MyDeveloperDay, owenpan, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D149647
2023-05-05 18:55:49 -07:00
Jon Phillips
c12aa69a0b [clang-format] Add BracedInitializerIndentWidth option
The option allows users to specify how many columns to use to indent
the contents of initializer lists.

Closes #51070.

Differential Revision: https://reviews.llvm.org/D146101
2023-04-29 00:36:19 -07:00
Manna, Soumi
38ecb9767c [NFC][clang] Fix Coverity bugs with AUTO_CAUSES_COPY
Reported by Coverity:
AUTO_CAUSES_COPY
Unnecessary object copies can affect performance.

1. Inside "ExtractAPIVisitor.h" file, in clang::extractapi::impl::ExtractAPIVisitorBase<<unnamed>::BatchExtractAPIVisitor>::VisitFunctionDecl(clang::FunctionDecl const *): Using the auto keyword without an & causes the copy of an object of type DynTypedNode.

2. Inside "NeonEmitter.cpp" file, in <unnamed>::Intrinsic::Intrinsic(llvm::Record *, llvm::StringRef, llvm::StringRef, <unnamed>::TypeSpec, <unnamed>::TypeSpec, <unnamed>::ClassKind, llvm::ListInit *, <unnamed>::NeonEmitter &, llvm::StringRef, llvm::StringRef, bool, bool): Using the auto keyword without an & causes the copy of an object of type Type.

3. Inside "MicrosoftCXXABI.cpp" file, in <unnamed>::MSRTTIBuilder::getClassHierarchyDescriptor(): Using the auto keyword without an & causes the copy of an object of type MSRTTIClass.

4. Inside "CGGPUBuiltin.cpp" file, in clang::CodeGen::CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(clang::CallExpr const *): Using the auto keyword without an & causes the copy of an object of type CallArg.

5. Inside "SemaDeclAttr.cpp" file, in threadSafetyCheckIsSmartPointer(clang::Sema &, clang::RecordType const *): Using the auto keyword without an & causes the copy of an object of type CXXBaseSpecifier.

6. Inside "ComputeDependence.cpp" file, in clang::computeDependence(clang::DesignatedInitExpr *): Using the auto keyword without an & causes the copy of an object of type Designator.

7. Inside "Format.cpp" file, In clang::format::affectsRange(llvm::ArrayRef<clang::tooling::Range>, unsigned int, unsigned int): Using the auto keyword without an & causes the copy of an object of type Range.

Reviewed By: tahonermann

Differential Revision: https://reviews.llvm.org/D149074
2023-04-24 14:52:55 -07:00
Owen Pan
51f6a16646 [clang-format] Hanlde leading whitespaces for JSON files
Fixes #62228.
Fixes #62229.

Differential Revision: https://reviews.llvm.org/D148777
2023-04-20 04:31:55 -07:00
Owen Pan
2bcfff6708 [clang-format] Fix regression with AlignTrailingComments set to true
Fixes #62161.

Differential Revision: https://reviews.llvm.org/D148447
2023-04-16 18:52:17 -07:00
Ben Hamilton
00ea679895 [Format/ObjC] Support NS_ERROR_ENUM in ObjC language guesser
Apple added a new NS_ERROR_ENUM macro to help define enums for
NSError codes.

This updates libformat's Objective-C language-guessing heuristic
to detect the new macro as well as related NSError types.

Tested: New tests added.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D147577
2023-04-07 16:10:52 -06:00
sstwcw
74cc4389f3 [clang-format] Add option for having one port per line in Verilog
We added the option `VerilogBreakBetweenInstancePorts` to put ports on
separate lines in module instantiations.  We made it default to true
because style guides mostly recommend it that way for example:

https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md#module-instantiation

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D147327
2023-04-04 14:51:22 +00:00
sstwcw
feb585e7d6 [clang-format] Handle Verilog struct literals
Previously `isVerilogIdentifier` was mistaking the apostrophe used in
struct literals as an identifier.  It is fixed.

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D147329
2023-04-01 17:10:31 +00:00
Owen Pan
253985d58c [clang-format] Add MinDigits suboptions to IntegerLiteralSeparator
Closes #61209.

Differential Revision: https://reviews.llvm.org/D147111
2023-03-31 17:14:33 -07:00
mydeveloperday
af98f3b1f4 [clang-format] JSON Add ability to add a space before the colon
I've seen a couple of request for extra Json formatting to match prettier capability.

Reviewed By: owenpan

Differential Revision: https://reviews.llvm.org/D147003
2023-03-29 21:28:40 +01:00
Manuel Klimek
01402831aa [clang-format] Add simple macro replacements in formatting.
Add configuration to specify macros.
Macros will be expanded, and the code will be parsed and annotated
in the expanded state. In a second step, the formatting decisions
in the annotated expanded code will be reconstructed onto the
original unexpanded macro call.

Eventually, this will allow to remove special-case code for
various macro options we accumulated over the years in favor of
one principled mechanism.

Differential Revision: https://reviews.llvm.org/D144170
2023-02-24 15:44:24 +00:00
Owen Pan
0ef289e5b2 [clang-format][NFC] Clean up nullptr comparison style
For example, use 'Next' instead of 'Next != nullptr',
and '!Next' instead of 'Next == nullptr'.

Differential Revision: https://reviews.llvm.org/D144355
2023-02-21 02:56:27 -08:00
Backl1ght
c24cdd58a1 [clang-format] PackConstructorInitializers support PCIS_OnlyNextLine
fixes https://github.com/llvm/llvm-project/issues/60241

Differential Revision: https://reviews.llvm.org/D143091
2023-02-06 19:39:05 +08:00
Owen Pan
25e2d0f3c8 [clang-format] Support clang-format on/off line comments as prefix
Closes #60264.

Differential Revision: https://reviews.llvm.org/D142804
2023-02-01 13:07:09 -08:00
Backl1ght
58751f943f [clang-format] SortUsingDeclarations support lexicographic order
fix https://github.com/llvm/llvm-project/issues/59930

Differential Revision: https://reviews.llvm.org/D141694
2023-01-20 21:34:57 +08:00
Kazu Hirata
6ad0788c33 [clang] Use std::optional instead of llvm::Optional (NFC)
This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to remove #include "llvm/ADT/Optional.h".

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14 12:31:01 -08:00
Owen Pan
e3eca33594 [clang-format] Replace DeriveLineEnding and UseCRLF with LineEnding
Below is the mapping:
LineEnding  DeriveLineEnding UseCRLF
LF                false       false
CRLF              false       true
DeriveLF          true        false
DeriveCRLF        true        true

Differential Revision: https://reviews.llvm.org/D141654
2023-01-13 15:46:34 -08:00