clang-tools 24.0.0git
ExpandDeducedType.cpp
Go to the documentation of this file.
1//===--- ExpandDeducedType.cpp -----------------------------------*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8#include "refactor/Tweak.h"
9
10#include "support/Logger.h"
11#include "clang/AST/DeclTemplate.h"
12#include "clang/AST/Type.h"
13#include "clang/AST/TypeLoc.h"
14#include "clang/Basic/LLVM.h"
15#include "llvm/Support/Error.h"
16#include <AST.h>
17#include <climits>
18#include <memory>
19#include <optional>
20#include <string>
21
22namespace clang {
23namespace clangd {
24namespace {
25
26/// Expand the "auto" type to the derived type
27/// Before:
28/// auto x = Something();
29/// ^^^^
30/// After:
31/// MyClass x = Something();
32/// ^^^^^^^
33/// Expand `decltype(expr)` to the deduced type
34/// Before:
35/// decltype(0) i;
36/// ^^^^^^^^^^^
37/// After:
38/// int i;
39/// ^^^
40class ExpandDeducedType : public Tweak {
41public:
42 const char *id() const final;
43 llvm::StringLiteral kind() const override {
45 }
46 bool prepare(const Selection &Inputs) override;
47 Expected<Effect> apply(const Selection &Inputs) override;
48 std::string title() const override;
49
50private:
51 SourceRange Range;
52};
53
54REGISTER_TWEAK(ExpandDeducedType)
55
56std::string ExpandDeducedType::title() const {
57 return "Replace with deduced type";
58}
59
60// Structured bindings must use auto, e.g. `const auto& [a,b,c] = ...;`.
61// Return whether N (an AutoTypeLoc) is such an auto that must not be expanded.
62bool isStructuredBindingType(const SelectionTree::Node *N) {
63 // Walk up the TypeLoc chain, because auto may be qualified.
64 while (N && N->ASTNode.get<TypeLoc>())
65 N = N->Parent;
66 // The relevant type is the only direct type child of a Decomposition.
67 return N && N->ASTNode.get<DecompositionDecl>();
68}
69
70bool isLambda(QualType QT) {
71 if (!QT.isNull())
72 if (const auto *RD = QT->getAsRecordDecl())
73 return RD->isLambda();
74 return false;
75}
76
77// Returns true iff Node is a lambda, and thus should not be expanded. Loc is
78// the location of the auto type.
79bool isDeducedAsLambda(const SelectionTree::Node *Node, SourceLocation Loc) {
80 // getDeducedType() does a traversal, which we want to avoid in prepare().
81 // But at least check this isn't auto x = []{...};, which can't ever be
82 // expanded.
83 // (It would be nice if we had an efficient getDeducedType(), instead).
84 for (const auto *It = Node; It; It = It->Parent) {
85 if (const auto *DD = It->ASTNode.get<DeclaratorDecl>()) {
86 if (DD->getTypeSourceInfo() &&
87 DD->getTypeSourceInfo()->getTypeLoc().getBeginLoc() == Loc &&
88 isLambda(DD->getType()))
89 return true;
90 }
91 }
92 return false;
93}
94
95// Returns true iff "auto" in Node is really part of the template parameter,
96// which we cannot expand.
97bool isTemplateParam(const SelectionTree::Node *Node) {
98 if (Node->Parent)
99 if (Node->Parent->ASTNode.get<NonTypeTemplateParmDecl>())
100 return true;
101 return false;
102}
103
104bool ExpandDeducedType::prepare(const Selection &Inputs) {
105 if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
106 if (auto *TypeNode = Node->ASTNode.get<TypeLoc>()) {
107 if (const AutoTypeLoc Result = TypeNode->getAs<AutoTypeLoc>()) {
108 if (!isStructuredBindingType(Node) &&
109 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
110 !isTemplateParam(Node))
111 Range = Result.getSourceRange();
112 }
113 if (auto TTPAuto = TypeNode->getAs<TemplateTypeParmTypeLoc>()) {
114 // We exclude concept constraints for now, as the SourceRange is wrong.
115 // void foo(C auto x) {};
116 // ^^^^
117 // TTPAuto->getSourceRange only covers "auto", not "C auto".
118 if (TTPAuto.getDecl()->isImplicit() &&
119 !TTPAuto.getDecl()->hasTypeConstraint())
120 Range = TTPAuto.getSourceRange();
121 }
122
123 if (auto DTTL = TypeNode->getAs<DecltypeTypeLoc>()) {
124 if (!isLambda(cast<DecltypeType>(DTTL.getType())->getUnderlyingType()))
125 Range = DTTL.getSourceRange();
126 }
127 }
128 }
129
130 return Range.isValid();
131}
132
133Expected<Tweak::Effect> ExpandDeducedType::apply(const Selection &Inputs) {
134 auto &SrcMgr = Inputs.AST->getSourceManager();
135
136 std::optional<clang::QualType> DeducedType =
137 getDeducedType(Inputs.AST->getASTContext(),
138 Inputs.AST->getHeuristicResolver(), Range.getBegin());
139
140 // if we can't resolve the type, return an error message
141 if (DeducedType == std::nullopt || (*DeducedType)->isUndeducedAutoType())
142 return error("Could not deduce type for 'auto' type");
143
144 // we shouldn't replace a dependent type which is likely not to print
145 // usefully, e.g.
146 // template <class T>
147 // struct Foobar {
148 // decltype(T{}) foobar;
149 // ^^^^^^^^^^^^^ would turn out to be `<dependent-type>`
150 // };
151 if ((*DeducedType)->isDependentType())
152 return error("Could not expand a dependent type");
153
154 // Some types aren't written as single chunks of text, e.g:
155 // auto fptr = &func; // auto is void(*)()
156 // ==>
157 // void (*fptr)() = &func;
158 // Replacing these requires examining the declarator, we don't support it yet.
159 std::string PrettyDeclarator = printType(
160 *DeducedType, Inputs.ASTSelection.commonAncestor()->getDeclContext(),
161 "DECLARATOR_ID");
162 llvm::StringRef PrettyTypeName = PrettyDeclarator;
163 if (!PrettyTypeName.consume_back("DECLARATOR_ID"))
164 return error("Could not expand type that isn't a simple string");
165 PrettyTypeName = PrettyTypeName.rtrim();
166
167 tooling::Replacement Expansion(SrcMgr, CharSourceRange(Range, true),
168 PrettyTypeName);
169
170 return Effect::mainFileEdit(SrcMgr, tooling::Replacements(Expansion));
171}
172
173} // namespace
174} // namespace clangd
175} // namespace clang
#define REGISTER_TWEAK(Subclass)
Definition Tweak.h:129
An interface base for small context-sensitive refactoring actions.
Definition Tweak.h:46
llvm::Error error(std::error_code, std::string &&)
Definition Logger.cpp:80
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder, bool FullyQualify)
Returns a QualType as string.
Definition AST.cpp:417
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition AST.cpp:624
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const llvm::StringLiteral REFACTOR_KIND
Definition Protocol.h:1102