Commit Graph

5516 Commits

Author SHA1 Message Date
Fangrui Song a996cc217c Remove unused #include "llvm/ADT/Optional.h" 2022-12-05 06:31:11 +00:00
Owen Pan e33243c950 [clang-format] Link the braces of a block in UnwrappedLineParser
This includes TT_MacroBlockBegin and TT_MacroBlockEnd as well.

We can no longer use MatchingParen of FormatToken as an indicator
to mark optional braces. Instead, we directly set Optional of an
l_brace first and reset it later if it turns out that the braces
are not optional.

Also added a test case for deeply nested loops.

Differential Revision: https://reviews.llvm.org/D139257
2022-12-04 12:01:26 -08:00
Kazu Hirata a41fbb1fc2 [clang/unittests] Use std::nullopt instead of None (NFC)
This patch mechanically replaces None with std::nullopt where the
compiler would warn if None were deprecated.  The intent is to reduce
the amount of manual work required in migrating from Optional to
std::optional.

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
2022-12-03 12:14:19 -08:00
Vassil Vassilev dc4889357a [clang-repl] Support statements on global scope in incremental mode.
This patch teaches clang to parse statements on the global scope to allow:
```
./bin/clang-repl
clang-repl> int i = 12;
clang-repl> ++i;
clang-repl> extern "C" int printf(const char*,...);
clang-repl> printf("%d\n", i);
13
clang-repl> %quit
```

Generally, disambiguating between statements and declarations is a non-trivial
task for a C++ parser. The challenge is to allow both standard C++ to be
translated as if this patch does not exist and in the cases where the user typed
a statement to be executed as if it were in a function body.

Clang's Parser does pretty well in disambiguating between declarations and
expressions. We have added DisambiguatingWithExpression flag which allows us to
preserve the existing and optimized behavior where needed and implement the
extra rules for disambiguating. Only few cases require additional attention:
  * Constructors/destructors -- Parser::isConstructorDeclarator was used in to
    disambiguate between ctor-looking declarations and statements on the global
    scope(eg. `Ns::f()`).
  * The template keyword -- the template keyword can appear in both declarations
    and statements. This patch considers the template keyword to be a declaration
    starter which breaks a few cases in incremental mode which will be tackled
    later.
  * The inline (and similar) keyword -- looking at the first token in many cases
    allows us to classify what is a declaration.
  * Other language keywords and specifiers -- ObjC/ObjC++/OpenCL/OpenMP rely on
    pragmas or special tokens which will be handled in subsequent patches.

The patch conceptually models a "top-level" statement into a TopLevelStmtDecl.
The TopLevelStmtDecl is lowered into a void function with no arguments.
We attach this function to the global initializer list to execute the statement
blocks in the correct order.

Differential revision: https://reviews.llvm.org/D127284
2022-12-03 07:18:07 +00:00
Maíra Canal ad83bead3d [clang-format] Don't move comments if AlignTrailingComments: Leave
For comments that start after a new line, currently, the comments are
being indented. This happens because the OriginalWhitespaceRange
considers newlines on the range. Therefore, when AlignTrailingComments:
Kind: Leave, deduct the number of newlines before the token to calculate
the number of spaces for trailing comments.

Fixes #59203.

Differential Revision: https://reviews.llvm.org/D139029
2022-12-01 16:07:06 -08:00
Alex Richardson a602f76a24 [clang][TargetInfo] Use LangAS for getPointer{Width,Align}()
Mixing LLVM and Clang address spaces can result in subtle bugs, and there
is no need for this hook to use the LLVM IR level address spaces.
Most of this change is just replacing zero with LangAS::Default,
but it also allows us to remove a few calls to getTargetAddressSpace().

This also removes a stale comment+workaround in
CGDebugInfo::CreatePointerLikeType(): ASTContext::getTypeSize() does
return the expected size for ReferenceType (and handles address spaces).

Differential Revision: https://reviews.llvm.org/D138295
2022-11-30 20:24:01 +00:00
Sam McCall 99b5ec1fd1 [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions
Based on include-cleaner's version, but:

- remove assert that can fail for input `/\<newline>* */`
- assert was also checking the wrong condition: that the prefix *differed* from
  either `//` or from `/*`. Avoid use of strncmp where we can.
- add a comment that the brittleness of the text matching is intentional

Differential Revision: https://reviews.llvm.org/D138780
2022-11-28 13:20:09 +01:00
Sam McCall 2c1fa73459 Reland "[Lex] Fix suggested spelling of /usr/bin/../include/foo"
This reverts commit 1dc0a1e5d2.

Failures were caused by unintentional conversion to native slashes by
remove_dots, so undo that: we always suggest posix slashes for includes.

This could potentially be a change in behavior on windows if people were
spelling headers with backslashes and headermaps contained backslashes,
but that's all underspecified and I don't think anyone uses headermaps
on windows.

Differential Revision: https://reviews.llvm.org/D138709
2022-11-28 10:09:13 +01:00
Kazu Hirata e2138ecc72 [clang] Use std::size (NFC)
std::size, introduced in C++17, allows us to directly obtain the
number of elements of an array.
2022-11-26 13:58:48 -08:00
Manuel Klimek ca8c6156f2 Fix test output regression from ee88c0cf09.
The unused variable fix also remove the test output of the tokens
that do not match, making debugging tests harder. Undo the semantic
changes of the build fix.
2022-11-25 13:53:34 +00:00
Sam McCall 1dc0a1e5d2 Revert "[Lex] Fix suggested spelling of /usr/bin/../include/foo"
This reverts commit 8bed59c7e7.

Breaks bots e.g. https://lab.llvm.org/buildbot/#/builders/216/builds/13282
2022-11-25 14:01:39 +01:00
Sam McCall 8bed59c7e7 [Lex] Fix suggested spelling of /usr/bin/../include/foo
Since D60873 we remove dotdots from the search path entries, but not the
filenames we're matching against, so do the latter too.

Since this also removes (single) dots, drop the logic to skip over them.
(Some of this was already dead, some is newly dead).

See D138676 for motivation.

Differential Revision: https://reviews.llvm.org/D138677
2022-11-25 11:01:22 +01:00
Sam McCall a72609cabe [Format] Don't crash on mismatched brackets 2022-11-24 15:14:06 +01:00
Nathan James 15e76eed0c
[clang] Add [is|set]Nested methods to NamespaceDecl
Adds support for NamespaceDecl to inform if its part of a nested namespace.
This flag only corresponds to the inner namespaces in a nested namespace declaration.
In this example:
namespace <X>::<Y>::<Z> {}
Only <Y> and <Z> will be classified as nested.

This flag isn't meant for assisting in building the AST, more for static analysis and refactorings.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D90568
2022-11-24 12:44:35 +00:00
Yitzhak Mandelbaum 84dd12b290 [clang][dataflow] Add widening API and implement it for built-in boolean model.
* Adds API support for widening of lattice elements and environments,
* Updates the algorithm to apply widening where appropriate,
* Implements widening for boolean values. In the process, moves the unsoundness
  of comparison from the default implementation of
  `Environment::ValueModel::compare` to model-specific handling inside
  `DataflowEnvironment::equivalentTo`. This change is intended to clarify
  the source and location of unsoundess.

This patch is a replacement for, and was based substantially on, https://reviews.llvm.org/D131645.

Differential Revision: https://reviews.llvm.org/D137948
2022-11-22 16:09:28 +00:00
Saleem Abdulrasool b78d5380da parse: process GNU and standard attributes on top-level decls
We would previously reject valid input where GNU attributes preceded the
standard attributes on top-level declarations. A previous attribute
handling change had begun rejecting this whilst GCC does honour this
layout. In practice, this breaks use of `extern "C"` attributed
functions which use both standard and GNU attributes as experienced by
the Swift runtime.

Objective-C deserves an honourable mention for requiring some additional
special casing. Because attributes on declarations and definitions
differ in semantics, we need to replicate some of the logic for
detecting attributes to declarations to which they appertain cannot be
attributed. This should match the existing case for the application of
GNU attributes to interfaces, protocols, and implementations.

Take the opportunity to split out the tooling tests into two cases: ones
which process macros and ones which do not.

Special thanks to Aaron Ballman for the many hints and extensive rubber
ducking that was involved in identifying the various places where we
accidentally dropped attributes.

Differential Revision: https://reviews.llvm.org/D137979
Fixes: #58229
Reviewed By: aaron.ballman, arphaman
2022-11-21 22:34:50 +00:00
Owen Pan 4daeb8c733 [clang-format] Fix a crash due to dereferencing null MatchingParen
Fixes #59089.

Differential Revision: https://reviews.llvm.org/D138371
2022-11-21 12:33:51 -08:00
Björn Schäpers 5ba5f7c46c [clang-format][NFC] Removed unused include 2022-11-21 13:24:19 +01:00
Noah Goldstein 92bccf5d3d [clang-format] Don't use PPIndentWidth inside multi-line macros
Differential Revision: https://reviews.llvm.org/D137181
2022-11-19 23:53:48 -08:00
Vaibhav Yenamandra 7b6fe711b2 Refactor StaticAnalyzer to use `clang::SarifDocumentWriter`
Refactor StaticAnalyzer to use clang::SarifDocumentWriter for
serializing sarif diagnostics.

Uses clang::SarifDocumentWriter to generate SARIF output in the
StaticAnalyzer.

Various bugfixes are also made to clang::SarifDocumentWriter.

Summary of changes:

clang/lib/Basic/Sarif.cpp:
  * Fix bug in adjustColumnPos introduced from prev move, it now uses
    FullSourceLoc::getDecomposedExpansionLoc which provides the correct
    location (in the presence of macros) instead of
    FullSourceLoc::getDecomposedLoc.
  * Fix createTextRegion so that it handles caret ranges correctly,
    this should bring it to parity with the previous implementation.

clang/test/Analysis/diagnostics/Inputs/expected-sarif:
  * Update the schema URL to the offical website
  * Add the emitted defaultConfiguration sections to all rules
  * Annotate results with the "level" property

clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp:
  * Update SarifDiagnostics class to hold a clang::SarifDocumentWriter
    that it uses to convert diagnostics to SARIF.
2022-11-17 14:47:02 -05:00
Emilia Dreamer 48a932e13e
[clang-format] Remove special case for kw_operator when aligning decls
This change breaks no existing tests but does fix the linked issue.
Declarations of operator overloads are annotated with
`TT_FunctionDeclarationName` on the `operator` keyword, which is already
being checked for when aligning, so the extra `kw_operator` doesn't seem
to be necessary. (just for reference, it was added in
rG92b397fb9d55ccdf4632c2b1b15b4a0ee417cf74 / 92b397fb9d)

Fixes https://github.com/llvm/llvm-project/issues/55733

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D137223
2022-11-17 11:38:28 +02:00
Emilia Dreamer df6f4b8513
[clang-format] Defer formatting of operator< to honor paren spacing
I'm not exactly sure what the intent of that section of
`spaceRequiredBetween` is doing, it seems to handle templates and <<,
but the part which adds spaces before parens is way later, as part
of `spaceRequiredBeforeParens`.

Fixes https://github.com/llvm/llvm-project/issues/58821

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D137474
2022-11-17 11:38:21 +02:00
Tom Praschan 0e00611cbc [clangd] Add heuristic for dropping snippet when completing member function pointer
This implements the 1st heuristic mentioned in https://github.com/clangd/clangd/issues/968#issuecomment-1002242704:

When completing a function that names a non-static member of a class, and we are not inside that class's scope, assume the reference will not be a call (and thus don't add the snippetSuffix)

Reviewed By: nridge

Differential Revision: https://reviews.llvm.org/D137040
2022-11-17 00:37:16 +01:00
Serge Pavlov 1f67dc8b7c [Driver] Enable nested configuration files
Users may partition parameters specified by configuration file and put
different groups into separate files. These files are inserted into the
main file using constructs `@file`. Relative file names in it are
resolved relative to the including configuration file and this is not
convenient in some cases. A configuration file, which resides in system
directory, may need to include a file with user-defined parameters and
still provide default definitions if such file is absent.

To solve such problems, the option `--config=` is allowed inside
configuration files. Like `@file` it results in insertion of
command-line arguments but the algorithm of file search is different and
allows overriding system definitions with user ones.

Differential Revision: https://reviews.llvm.org/D136354
2022-11-16 13:32:27 +07:00
Björn Schäpers 617277e7cb [clang-format][NFC] Moved configuration parsing tests in own file
I want to reduce the size of ForatTest.cpp with its still wopping 25k
lines it is a burden on the compiler and editor (mine is clangd
powered).

This are tests which are really serving a different purpose than
formatting.

I've copied the code and made the following changes:
- Dropped the ; at the end of some macros, all macro "invocations"
  already have their own ;.
- Dropped the _F, we don't need a fxiture here.

Differential Revisison: https://reviews.llvm.org/D137823
2022-11-16 07:02:09 +01:00
Kadir Cetinkaya eed1f337a1
[clang][Tooling] Sort filenames in test 2022-11-15 13:31:40 +01:00
Kadir Cetinkaya ae59131d3e
[clang][Tooling] Make the filename behaviour consistent
Dotdots were removed only when converting a relative path to absolute
one. This patch makes the behaviour consistent for absolute file paths by
removing them in that case as well. Also updates the documentation to mention
the behaviour.

Fixes https://github.com/clangd/clangd/issues/1317

Differential Revision: https://reviews.llvm.org/D137962
2022-11-15 10:47:52 +01:00
Chuanqi Xu cb2289f392 [C++20] [Modules] Attach implicitly declared allocation funcitons to
global module fragment

[basic.stc.dynamic.general]p2 says:
> The library provides default definitions for the global allocation
> and deallocation functions. Some global allocation and
> deallocation
> functions are replaceable ([new.delete]); these are attached to
> the global module ([module.unit]).

But we didn't take this before and the implicitly generated functions
will live in the module purview if we're compiling a module unit. This
is bad since the owning module will affect the linkage of the
declarations. This patch addresses this.

Closes https://github.com/llvm/llvm-project/issues/58560
2022-11-15 17:21:48 +08:00
Haojian Wu 5c4ae8a86a Update the wrong isSelfContainedHeader API usage in the test. 2022-11-14 11:10:55 +01:00
Haojian Wu dd46a08008 Move the isSelfContainedHeader function from clangd to libtooling.
We plan to reuse it in the include-cleaner library, this patch moves
this functionality from clangd to libtooling, so that this piece of code can be
shared among all clang tools.

Differential Revision: https://reviews.llvm.org/D137697
2022-11-14 09:40:45 +01:00
Micah Weston e864ac6945 [clang-format] Treats &/&& as reference when followed by ',' or ')'
Ran into an issue where function declarations inside function
scopes or uses of sizeof inside a function would treat the && in
'sizeof(Type &&)' as a binary operator.

Attempt to fix this by assuming reference when followed by ',' or
')'. Also adds tests for these.

Also hit an edge case in another test that treated "and" the same
as "&&" since it parses as C++. Changed the "and" to "also" so it
is no longer a keyword.

Fixes #58923.

Differential Revision: https://reviews.llvm.org/D137755
2022-11-12 00:58:58 -08:00
Owen Pan 96e23906b5 [clang-format] Correctly annotate function names before attributes
Fixes #58827.

Differential Revision: https://reviews.llvm.org/D137486
2022-11-12 00:40:46 -08:00
Anastasiia Lukianenko f6b252978c [clang-format] Add BreakBeforeInlineASMColon configuration
If true, colons in ASM parameters will be placed after line breaks.

true:
asm volatile("string",
                     :
                     : val);

false:
asm volatile("string", : : val);

Differential Revision: https://reviews.llvm.org/D91950
2022-11-10 22:31:09 +01:00
Björn Schäpers 41a09a07ce [clang-format][NFCish] Alphabetical sort Format.(h|pp)
I've:
- Sorted the members of FormatStyle alphabetical. The enums and structs
  are kept close to the member.
- Sorted the yaml io functions, based on the type they operate on.
- Sorted the initializers in getLLVMStyle(), except that penalities are
  kept at the end.
- Sorted the io of FormatStyle, this changes the --dump-config behavior.
- Moved the deprecated options into the only input case, this also
  changes --dump-config, it does not put the not directly used options
  in the .clang-format anymore.
- Sorted the comparisons in operator==.
- Added WhiteSpaceMacros in operator==, I've not actively looked if all
  other members are compared.
- This showed flawed tests (or in my opinion a flawed io operation, but
  that is another discussion and change).

Differential Revision: https://reviews.llvm.org/D137409
2022-11-08 21:46:15 +01:00
Rageking8 94738a5ac3 Fix duplicate word typos; NFC
This revision fixes typos where there are 2 consecutive words which are
duplicated. There should be no code changes in this revision (only
changes to comments and docs). Do let me know if there are any
undesirable changes in this revision. Thanks.
2022-11-08 07:21:23 -05:00
Nathan James 108e41d962
[clang][NFC] Use c++17 style variable type traits
This was done as a test for D137302 and it makes sense to push these changes

Reviewed By: shafik

Differential Revision: https://reviews.llvm.org/D137491
2022-11-07 18:25:48 +00:00
Tobias Hieta 70de684d44
[clang-format] Handle object instansiation in if-statements
Before this patch code like this:

```
if (Class* obj{getObject()}) { }
```

would be mis-formated since the * would be annotated as a
binaryoperator.

This patch changes the * to become a PointerOrReference instead
and fixes the formatting issues.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D137327
2022-11-07 08:34:57 +01:00
Yitzhak Mandelbaum c0725865b1 [clang][dataflow] Generalize custom comparison to return tri-value result.
Currently, the API for a model's custom value comparison returns a
boolean. Therefore, models cannot distinguish between situations where the
values are recognized by the model and different and those where the values are
just not recognized.  This patch changes the return value to a tri-valued enum,
allowing models to express "don't know".

This patch is essentially a NFC -- no practical differences result from this
change in this patch. But, it prepares for future patches (particularly,
upcoming patches for widening) which will take advantage of the new flexibility.

Differential Revision: https://reviews.llvm.org/D137334
2022-11-03 23:31:20 +00:00
Björn Schäpers f97639ce13 [clang-format] Don't misannotate in CTor init list
They were annotated with TrailingAnnotation, which they are not. And
that resulted in some quirky formatting in some cases.

Differential Revision: https://reviews.llvm.org/D136635
2022-11-03 13:08:48 +01:00
Björn Schäpers cdbe296853 [clang-format] Fix lambda formatting in conditional
Without the patch UnwrappedLineFormatter::analyzeSolutionSpace just ran
out of possible formattings and would put everything just on one line.
The problem was that the the line break was forbidden, but putting the
conditional colon on the same line is also forbidden.

Differential Revision: https://reviews.llvm.org/D135918
2022-11-03 13:08:14 +01:00
Serge Pavlov fdab9f1203 [Clang] Check for response file existence prior to check for recursion
As now errors in file operation are handled, check for file existence
must be done prior to check for recursion, otherwise reported errors are
misleading.

Differential Revision: https://reviews.llvm.org/D136090
2022-11-03 14:49:58 +07:00
Owen Pan 117d792f35 [clang-format] Don't skip #else/#elif of #if 0
Fixes #58188.

Differential Revision: https://reviews.llvm.org/D137052
2022-11-02 13:32:08 -07:00
Matheus Izvekov ee1f132d2c
Revert "[clang] ASTImporter: Fix importing of va_list types and declarations"
This reverts commit 5f820c0f55.

Apparently it breaks aarch64 buildbots.
https://lab.llvm.org/buildbot#builders/188/builds/21591
2022-10-31 19:34:23 +01:00
Matheus Izvekov 5f820c0f55
[clang] ASTImporter: Fix importing of va_list types and declarations
This fixes a problem where __va_list_tag was not correctly imported,
possibly leading to multiple definitions with different types.

This adds __va_list_tag to it's proper scope, so that the ASTImporter
can find it.

Signed-off-by: Matheus Izvekov <mizvekov@gmail.com>

Differential Revision: https://reviews.llvm.org/D136886
2022-10-31 17:57:18 +01:00
Serge Pavlov fd3d7a9f8c Handle errors in expansion of response files
Previously an error raised during an expansion of response files (including
configuration files) was ignored and only the fact of its presence was
reported to the user with generic error messages. This made it difficult to
analyze problems. For example, if a configuration file tried to read an
inexistent file, the error message said that 'configuration file cannot
be found', which is wrong and misleading.

This change enhances handling errors in the expansion so that users
could get more informative error messages.

Differential Revision: https://reviews.llvm.org/D136090
2022-10-31 15:36:41 +07:00
Yusuke Kadowaki 3edc1210a4 [clang-format] Adds a formatter for aligning trailing comments over empty lines
This patch addresses https://github.com/llvm/llvm-project/issues/19756

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D132131
2022-10-30 12:22:39 +00:00
sstwcw d5be1550f1 [clang-format] Don't crash on malformed preprocessor conditions
Previously the program would crash on this input:

```
#else
#if X
```

The problem was that in `parsePPElse`, `PPBranchLevel` would be
incremented when the first `#else` gets parsed, but `PPLevelBranchCount`
and `PPLevelBranchIndex` would not be updated together.

I found the problem when working on D135740.

Differential Revision: https://reviews.llvm.org/D135972
2022-10-30 02:18:58 +00:00
Serge Pavlov c1728a40aa Revert "Handle errors in expansion of response files"
This reverts commit 17eb198de9.
Reverted for investigation, because ClangDriverTests failed on some builders.
2022-10-30 02:03:12 +07:00
Serge Pavlov 17eb198de9 Handle errors in expansion of response files
Previously an error raised during an expansion of response files (including
configuration files) was ignored and only the fact of its presence was
reported to the user with generic error messages. This made it difficult to
analyze problems. For example, if a configuration file tried to read an
inexistent file, the error message said that 'configuration file cannot
be found', which is wrong and misleading.

This change enhances handling errors in the expansion so that users
could get more informative error messages.

Differential Revision: https://reviews.llvm.org/D136090
2022-10-29 22:01:47 +07:00
owenca 30ea3fcc4c [clang-format][NFC] Move BracesRemover tests out of FormatTest.cpp
Differential Revision: https://reviews.llvm.org/D136830
2022-10-28 23:44:41 -07:00