Skip to content

Commit feadcae

Browse files
authored
Merge branch 'main' into fix/fixit-unknown-attributes
2 parents b411937 + dde30a4 commit feadcae

File tree

249 files changed

+10735
-2105
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

249 files changed

+10735
-2105
lines changed

clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp

Lines changed: 151 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,30 @@
1717
#include <cctype>
1818
#include <optional>
1919

20+
namespace clang::tidy {
21+
22+
template <>
23+
struct OptionEnumMapping<
24+
modernize::UseTrailingReturnTypeCheck::TransformLambda> {
25+
static llvm::ArrayRef<std::pair<
26+
modernize::UseTrailingReturnTypeCheck::TransformLambda, StringRef>>
27+
getEnumMapping() {
28+
static constexpr std::pair<
29+
modernize::UseTrailingReturnTypeCheck::TransformLambda, StringRef>
30+
Mapping[] = {
31+
{modernize::UseTrailingReturnTypeCheck::TransformLambda::All,
32+
"all"},
33+
{modernize::UseTrailingReturnTypeCheck::TransformLambda::
34+
AllExceptAuto,
35+
"all_except_auto"},
36+
{modernize::UseTrailingReturnTypeCheck::TransformLambda::None,
37+
"none"}};
38+
return Mapping;
39+
}
40+
};
41+
42+
} // namespace clang::tidy
43+
2044
using namespace clang::ast_matchers;
2145

2246
namespace clang::tidy::modernize {
@@ -111,10 +135,17 @@ struct UnqualNameVisitor : public RecursiveASTVisitor<UnqualNameVisitor> {
111135
private:
112136
const FunctionDecl &F;
113137
};
138+
139+
AST_MATCHER(LambdaExpr, hasExplicitResultType) {
140+
return Node.hasExplicitResultType();
141+
}
142+
114143
} // namespace
115144

116145
constexpr llvm::StringLiteral ErrorMessageOnFunction =
117146
"use a trailing return type for this function";
147+
constexpr llvm::StringLiteral ErrorMessageOnLambda =
148+
"use a trailing return type for this lambda";
118149

119150
static SourceLocation expandIfMacroId(SourceLocation Loc,
120151
const SourceManager &SM) {
@@ -329,6 +360,48 @@ findReturnTypeAndCVSourceRange(const FunctionDecl &F, const TypeLoc &ReturnLoc,
329360
return ReturnTypeRange;
330361
}
331362

363+
static SourceLocation findLambdaTrailingReturnInsertLoc(
364+
const CXXMethodDecl *Method, const SourceManager &SM,
365+
const LangOptions &LangOpts, const ASTContext &Ctx) {
366+
// 'requires' keyword is present in lambda declaration
367+
if (Method->getTrailingRequiresClause()) {
368+
SourceLocation ParamEndLoc;
369+
if (Method->param_empty())
370+
ParamEndLoc = Method->getBeginLoc();
371+
else
372+
ParamEndLoc = Method->getParametersSourceRange().getEnd();
373+
374+
std::pair<FileID, unsigned> ParamEndLocInfo =
375+
SM.getDecomposedLoc(ParamEndLoc);
376+
StringRef Buffer = SM.getBufferData(ParamEndLocInfo.first);
377+
378+
Lexer Lexer(SM.getLocForStartOfFile(ParamEndLocInfo.first), LangOpts,
379+
Buffer.begin(), Buffer.data() + ParamEndLocInfo.second,
380+
Buffer.end());
381+
382+
Token Token;
383+
while (!Lexer.LexFromRawLexer(Token)) {
384+
if (Token.is(tok::raw_identifier)) {
385+
IdentifierInfo &Info = Ctx.Idents.get(StringRef(
386+
SM.getCharacterData(Token.getLocation()), Token.getLength()));
387+
Token.setIdentifierInfo(&Info);
388+
Token.setKind(Info.getTokenID());
389+
}
390+
391+
if (Token.is(tok::kw_requires))
392+
return Token.getLocation().getLocWithOffset(-1);
393+
}
394+
395+
return {};
396+
}
397+
398+
// If no requires clause, insert before the body
399+
if (const Stmt *Body = Method->getBody())
400+
return Body->getBeginLoc().getLocWithOffset(-1);
401+
402+
return {};
403+
}
404+
332405
static void keepSpecifiers(std::string &ReturnType, std::string &Auto,
333406
SourceRange ReturnTypeCVRange, const FunctionDecl &F,
334407
const FriendDecl *Fr, const ASTContext &Ctx,
@@ -382,14 +455,43 @@ static void keepSpecifiers(std::string &ReturnType, std::string &Auto,
382455
}
383456
}
384457

458+
UseTrailingReturnTypeCheck::UseTrailingReturnTypeCheck(
459+
StringRef Name, ClangTidyContext *Context)
460+
: ClangTidyCheck(Name, Context),
461+
TransformFunctions(Options.get("TransformFunctions", true)),
462+
TransformLambdas(Options.get("TransformLambdas", TransformLambda::All)) {
463+
464+
if (TransformFunctions == false && TransformLambdas == TransformLambda::None)
465+
this->configurationDiag(
466+
"The check 'modernize-use-trailing-return-type' will not perform any "
467+
"analysis because 'TransformFunctions' and 'TransformLambdas' are "
468+
"disabled.");
469+
}
470+
471+
void UseTrailingReturnTypeCheck::storeOptions(
472+
ClangTidyOptions::OptionMap &Opts) {
473+
Options.store(Opts, "TransformFunctions", TransformFunctions);
474+
Options.store(Opts, "TransformLambdas", TransformLambdas);
475+
}
476+
385477
void UseTrailingReturnTypeCheck::registerMatchers(MatchFinder *Finder) {
386-
auto F = functionDecl(
387-
unless(anyOf(hasTrailingReturn(), returns(voidType()),
388-
cxxConversionDecl(), cxxMethodDecl(isImplicit()))))
389-
.bind("Func");
478+
auto F =
479+
functionDecl(
480+
unless(anyOf(
481+
hasTrailingReturn(), returns(voidType()), cxxConversionDecl(),
482+
cxxMethodDecl(
483+
anyOf(isImplicit(),
484+
hasParent(cxxRecordDecl(hasParent(lambdaExpr()))))))))
485+
.bind("Func");
486+
487+
if (TransformFunctions) {
488+
Finder->addMatcher(F, this);
489+
Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this);
490+
}
390491

391-
Finder->addMatcher(F, this);
392-
Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this);
492+
if (TransformLambdas != TransformLambda::None)
493+
Finder->addMatcher(
494+
lambdaExpr(unless(hasExplicitResultType())).bind("Lambda"), this);
393495
}
394496

395497
void UseTrailingReturnTypeCheck::registerPPCallbacks(
@@ -401,8 +503,13 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) {
401503
assert(PP && "Expected registerPPCallbacks() to have been called before so "
402504
"preprocessor is available");
403505

404-
const auto *F = Result.Nodes.getNodeAs<FunctionDecl>("Func");
506+
if (const auto *Lambda = Result.Nodes.getNodeAs<LambdaExpr>("Lambda")) {
507+
diagOnLambda(Lambda, Result);
508+
return;
509+
}
510+
405511
const auto *Fr = Result.Nodes.getNodeAs<FriendDecl>("Friend");
512+
const auto *F = Result.Nodes.getNodeAs<FunctionDecl>("Func");
406513
assert(F && "Matcher is expected to find only FunctionDecls");
407514

408515
// Three-way comparison operator<=> is syntactic sugar and generates implicit
@@ -495,4 +602,41 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) {
495602
<< FixItHint::CreateInsertion(InsertionLoc, " -> " + ReturnType);
496603
}
497604

605+
void UseTrailingReturnTypeCheck::diagOnLambda(
606+
const LambdaExpr *Lambda,
607+
const ast_matchers::MatchFinder::MatchResult &Result) {
608+
609+
const CXXMethodDecl *Method = Lambda->getCallOperator();
610+
if (!Method || Lambda->hasExplicitResultType())
611+
return;
612+
613+
const ASTContext *Ctx = Result.Context;
614+
const QualType ReturnType = Method->getReturnType();
615+
616+
// We can't write 'auto' in C++11 mode, try to write generic msg and bail out.
617+
if (ReturnType->isDependentType() &&
618+
Ctx->getLangOpts().LangStd == LangStandard::lang_cxx11) {
619+
if (TransformLambdas == TransformLambda::All)
620+
diag(Lambda->getBeginLoc(), ErrorMessageOnLambda);
621+
return;
622+
}
623+
624+
if (ReturnType->isUndeducedAutoType() &&
625+
TransformLambdas == TransformLambda::AllExceptAuto)
626+
return;
627+
628+
const SourceLocation TrailingReturnInsertLoc =
629+
findLambdaTrailingReturnInsertLoc(Method, *Result.SourceManager,
630+
getLangOpts(), *Result.Context);
631+
632+
if (TrailingReturnInsertLoc.isValid())
633+
diag(Lambda->getBeginLoc(), "use a trailing return type for this lambda")
634+
<< FixItHint::CreateInsertion(
635+
TrailingReturnInsertLoc,
636+
" -> " +
637+
ReturnType.getAsString(Result.Context->getPrintingPolicy()));
638+
else
639+
diag(Lambda->getBeginLoc(), ErrorMessageOnLambda);
640+
}
641+
498642
} // namespace clang::tidy::modernize

clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,25 @@ struct ClassifiedToken {
2626
/// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-trailing-return-type.html
2727
class UseTrailingReturnTypeCheck : public ClangTidyCheck {
2828
public:
29-
UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context)
30-
: ClangTidyCheck(Name, Context) {}
29+
UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context);
3130
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
3231
return LangOpts.CPlusPlus11;
3332
}
33+
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
3434
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
3535
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
3636
Preprocessor *ModuleExpanderPP) override;
3737
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
3838

39+
enum TransformLambda { All, AllExceptAuto, None };
40+
3941
private:
4042
Preprocessor *PP = nullptr;
43+
const bool TransformFunctions;
44+
const TransformLambda TransformLambdas;
45+
46+
void diagOnLambda(const LambdaExpr *Lambda,
47+
const ast_matchers::MatchFinder::MatchResult &Result);
4148
};
4249

4350
} // namespace clang::tidy::modernize

clang-tools-extra/clangd/ModulesBuilder.cpp

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -430,10 +430,10 @@ class CachingProjectModules : public ProjectModules {
430430
/// Collect the directly and indirectly required module names for \param
431431
/// ModuleName in topological order. The \param ModuleName is guaranteed to
432432
/// be the last element in \param ModuleNames.
433-
llvm::SmallVector<StringRef> getAllRequiredModules(PathRef RequiredSource,
434-
CachingProjectModules &MDB,
435-
StringRef ModuleName) {
436-
llvm::SmallVector<llvm::StringRef> ModuleNames;
433+
llvm::SmallVector<std::string> getAllRequiredModules(PathRef RequiredSource,
434+
CachingProjectModules &MDB,
435+
StringRef ModuleName) {
436+
llvm::SmallVector<std::string> ModuleNames;
437437
llvm::StringSet<> ModuleNamesSet;
438438

439439
auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void {
@@ -444,7 +444,7 @@ llvm::SmallVector<StringRef> getAllRequiredModules(PathRef RequiredSource,
444444
if (ModuleNamesSet.insert(RequiredModuleName).second)
445445
Visitor(RequiredModuleName, Visitor);
446446

447-
ModuleNames.push_back(ModuleName);
447+
ModuleNames.push_back(ModuleName.str());
448448
};
449449
VisitDeps(ModuleName, VisitDeps);
450450

@@ -494,28 +494,30 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile(
494494
// Get Required modules in topological order.
495495
auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName);
496496
for (llvm::StringRef ReqModuleName : ReqModuleNames) {
497-
if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
497+
if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName))
498498
continue;
499499

500500
if (auto Cached = Cache.getModule(ReqModuleName)) {
501501
if (IsModuleFileUpToDate(Cached->getModuleFilePath(), BuiltModuleFiles,
502502
TFS.view(std::nullopt))) {
503-
log("Reusing module {0} from {1}", ModuleName,
503+
log("Reusing module {0} from {1}", ReqModuleName,
504504
Cached->getModuleFilePath());
505505
BuiltModuleFiles.addModuleFile(std::move(Cached));
506506
continue;
507507
}
508508
Cache.remove(ReqModuleName);
509509
}
510510

511+
std::string ReqFileName =
512+
MDB.getSourceForModuleName(ReqModuleName, RequiredSource);
511513
llvm::Expected<ModuleFile> MF = buildModuleFile(
512-
ModuleName, ModuleUnitFileName, getCDB(), TFS, BuiltModuleFiles);
514+
ReqModuleName, ReqFileName, getCDB(), TFS, BuiltModuleFiles);
513515
if (llvm::Error Err = MF.takeError())
514516
return Err;
515517

516-
log("Built module {0} to {1}", ModuleName, MF->getModuleFilePath());
518+
log("Built module {0} to {1}", ReqModuleName, MF->getModuleFilePath());
517519
auto BuiltModuleFile = std::make_shared<const ModuleFile>(std::move(*MF));
518-
Cache.add(ModuleName, BuiltModuleFile);
520+
Cache.add(ReqModuleName, BuiltModuleFile);
519521
BuiltModuleFiles.addModuleFile(std::move(BuiltModuleFile));
520522
}
521523

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# A smoke test to check that a simple dependency chain for modules can work.
2+
#
3+
# FIXME: This fails on the Windows ARM64 build server. Not entirely sure why as it has been tested on
4+
# an ARM64 Windows VM and appears to work there.
5+
# UNSUPPORTED: host=aarch64-pc-windows-msvc
6+
#
7+
# RUN: rm -fr %t
8+
# RUN: mkdir -p %t
9+
# RUN: split-file %s %t
10+
#
11+
# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp
12+
# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json
13+
# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc.tmp
14+
#
15+
# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
16+
# (with the extra slash in the front), so we add it here.
17+
# RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' %/t/definition.jsonrpc.tmp > %/t/definition.jsonrpc
18+
#
19+
# RUN: clangd -experimental-modules-support -lit-test < %t/definition.jsonrpc \
20+
# RUN: | FileCheck -strict-whitespace %t/definition.jsonrpc
21+
22+
#--- A-frag.cppm
23+
export module A:frag;
24+
export void printA() {}
25+
26+
#--- A.cppm
27+
export module A;
28+
export import :frag;
29+
30+
#--- Use.cpp
31+
import A;
32+
void foo() {
33+
print
34+
}
35+
36+
#--- compile_commands.json.tmpl
37+
[
38+
{
39+
"directory": "DIR",
40+
"command": "CLANG_CC -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c DIR/Use.cpp",
41+
"file": "DIR/Use.cpp"
42+
},
43+
{
44+
"directory": "DIR",
45+
"command": "CLANG_CC -std=c++20 DIR/A.cppm --precompile -o DIR/A.pcm",
46+
"file": "DIR/A.cppm"
47+
},
48+
{
49+
"directory": "DIR",
50+
"command": "CLANG_CC -std=c++20 DIR/A-frag.cppm --precompile -o DIR/A-frag.pcm",
51+
"file": "DIR/A-frag.cppm"
52+
}
53+
]
54+
55+
#--- definition.jsonrpc.tmpl
56+
{
57+
"jsonrpc": "2.0",
58+
"id": 0,
59+
"method": "initialize",
60+
"params": {
61+
"processId": 123,
62+
"rootPath": "clangd",
63+
"capabilities": {
64+
"textDocument": {
65+
"completion": {
66+
"completionItem": {
67+
"snippetSupport": true
68+
}
69+
}
70+
}
71+
},
72+
"trace": "off"
73+
}
74+
}
75+
---
76+
{
77+
"jsonrpc": "2.0",
78+
"method": "textDocument/didOpen",
79+
"params": {
80+
"textDocument": {
81+
"uri": "file://DIR/Use.cpp",
82+
"languageId": "cpp",
83+
"version": 1,
84+
"text": "import A;\nvoid foo() {\n print\n}\n"
85+
}
86+
}
87+
}
88+
89+
# CHECK: "message"{{.*}}printA{{.*}}(fix available)
90+
91+
---
92+
{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"file://DIR/Use.cpp"},"context":{"triggerKind":1},"position":{"line":2,"character":6}}}
93+
---
94+
{"jsonrpc":"2.0","id":2,"method":"shutdown"}
95+
---
96+
{"jsonrpc":"2.0","method":"exit"}

0 commit comments

Comments
 (0)