summaryrefslogtreecommitdiff
path: root/clang/unittests/AST/TypePrinterTest.cpp
blob: 77ff4422366869964f497b10fb171196fabd556b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//===- unittests/AST/TypePrinterTest.cpp --- Type printer tests -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains tests for QualType::print() and related methods.
//
//===----------------------------------------------------------------------===//

#include "ASTPrint.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallString.h"
#include "gtest/gtest.h"

using namespace clang;
using namespace ast_matchers;
using namespace tooling;

namespace {

static void PrintType(raw_ostream &Out, const ASTContext *Context,
                      const QualType *T,
                      PrintingPolicyAdjuster PolicyAdjuster) {
  assert(T && !T->isNull() && "Expected non-null Type");
  PrintingPolicy Policy = Context->getPrintingPolicy();
  if (PolicyAdjuster)
    PolicyAdjuster(Policy);
  T->print(Out, Policy);
}

::testing::AssertionResult
PrintedTypeMatches(StringRef Code, const std::vector<std::string> &Args,
                   const DeclarationMatcher &NodeMatch,
                   StringRef ExpectedPrinted,
                   PrintingPolicyAdjuster PolicyAdjuster) {
  return PrintedNodeMatches<QualType>(Code, Args, NodeMatch, ExpectedPrinted,
                                      "", PrintType, PolicyAdjuster);
}

} // unnamed namespace

TEST(TypePrinter, TemplateId) {
  std::string Code = R"cpp(
    namespace N {
      template <typename> struct Type {};

      template <typename T>
      void Foo(const Type<T> &Param);
    }
  )cpp";
  auto Matcher = parmVarDecl(hasType(qualType().bind("id")));

  ASSERT_TRUE(PrintedTypeMatches(
      Code, {}, Matcher, "const Type<T> &",
      [](PrintingPolicy &Policy) { Policy.FullyQualifiedName = false; }));

  ASSERT_TRUE(PrintedTypeMatches(
      Code, {}, Matcher, "const Type<T> &",
      [](PrintingPolicy &Policy) { Policy.FullyQualifiedName = true; }));
}

TEST(TypePrinter, TemplateId2) {
  std::string Code = R"cpp(
      template <template <typename ...> class TemplatedType>
      void func(TemplatedType<int> Param);
    )cpp";
  auto Matcher = parmVarDecl(hasType(qualType().bind("id")));

  // Regression test ensuring we do not segfault getting the QualType as a
  // string.
  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher, "<int>",
                                 [](PrintingPolicy &Policy) {
                                   Policy.FullyQualifiedName = true;
                                   Policy.PrintCanonicalTypes = true;
                                 }));
}

TEST(TypePrinter, ParamsUglified) {
  llvm::StringLiteral Code = R"cpp(
    template <typename _Tp, template <typename> class __f>
    const __f<_Tp&> *A = nullptr;
  )cpp";
  auto Clean = [](PrintingPolicy &Policy) {
    Policy.CleanUglifiedParameters = true;
  };

  ASSERT_TRUE(PrintedTypeMatches(Code, {},
                                 varDecl(hasType(qualType().bind("id"))),
                                 "const __f<_Tp &> *", nullptr));
  ASSERT_TRUE(PrintedTypeMatches(Code, {},
                                 varDecl(hasType(qualType().bind("id"))),
                                 "const f<Tp &> *", Clean));
}

TEST(TypePrinter, TemplateIdWithNTTP) {
  constexpr char Code[] = R"cpp(
    template <int N>
    struct Str {
      constexpr Str(char const (&s)[N]) { __builtin_memcpy(value, s, N); }
      char value[N];
    };
    template <Str> class ASCII {};

    ASCII<"this nontype template argument is too long to print"> x;
  )cpp";
  auto Matcher = classTemplateSpecializationDecl(
      hasName("ASCII"), has(cxxConstructorDecl(
                            isMoveConstructor(),
                            has(parmVarDecl(hasType(qualType().bind("id")))))));

  ASSERT_TRUE(PrintedTypeMatches(
      Code, {"-std=c++20"}, Matcher,
      R"(ASCII<Str<52>{"this nontype template argument is [...]"}> &&)",
      [](PrintingPolicy &Policy) {
        Policy.EntireContentsOfLargeArray = false;
      }));

  ASSERT_TRUE(PrintedTypeMatches(
      Code, {"-std=c++20"}, Matcher,
      R"(ASCII<Str<52>{"this nontype template argument is too long to print"}> &&)",
      [](PrintingPolicy &Policy) {
        Policy.EntireContentsOfLargeArray = true;
      }));
}

TEST(TypePrinter, TemplateArgumentsSubstitution_Expressions) {
  /// Tests clang::isSubstitutedDefaultArgument on TemplateArguments
  /// that are of kind TemplateArgument::Expression
  constexpr char Code[] = R"cpp(
    constexpr bool func() { return true; }

    template <typename T1 = int,
              int      T2 = 42,
              T1       T3 = 43,
              int      T4 = sizeof(T1),
              bool     T5 = func()
              >
    struct Foo {
    };

    Foo<int, 40 + 2> X;
  )cpp";

  auto AST = tooling::buildASTFromCodeWithArgs(Code, /*Args=*/{"-std=c++20"});
  ASTContext &Ctx = AST->getASTContext();

  auto const *CTD = selectFirst<ClassTemplateDecl>(
      "id", match(classTemplateDecl(hasName("Foo")).bind("id"), Ctx));
  ASSERT_NE(CTD, nullptr);
  auto const *CTSD = *CTD->specializations().begin();
  ASSERT_NE(CTSD, nullptr);
  auto const *Params = CTD->getTemplateParameters();
  ASSERT_NE(Params, nullptr);
  auto const &ArgList = CTSD->getTemplateArgs();

  auto createBinOpExpr = [&](uint32_t LHS, uint32_t RHS,
                             uint32_t Result) -> ConstantExpr * {
    const int numBits = 32;
    clang::APValue ResultVal{llvm::APSInt(llvm::APInt(numBits, Result))};
    auto *LHSInt = IntegerLiteral::Create(Ctx, llvm::APInt(numBits, LHS),
                                          Ctx.UnsignedIntTy, {});
    auto *RHSInt = IntegerLiteral::Create(Ctx, llvm::APInt(numBits, RHS),
                                          Ctx.UnsignedIntTy, {});
    auto *BinOp = BinaryOperator::Create(
        Ctx, LHSInt, RHSInt, BinaryOperatorKind::BO_Add, Ctx.UnsignedIntTy,
        ExprValueKind::VK_PRValue, ExprObjectKind::OK_Ordinary, {}, {});
    return ConstantExpr::Create(Ctx, dyn_cast<Expr>(BinOp), ResultVal);
  };

  {
    // Arg is an integral '42'
    auto const &Arg = ArgList.get(1);
    ASSERT_EQ(Arg.getKind(), TemplateArgument::Integral);

    // Param has default expr which evaluates to '42'
    auto const *Param = Params->getParam(1);

    EXPECT_TRUE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }

  {
    // Arg is an integral '41'
    llvm::APInt Int(32, 41);
    TemplateArgument Arg(Ctx, llvm::APSInt(Int), Ctx.UnsignedIntTy);

    // Param has default expr which evaluates to '42'
    auto const *Param = Params->getParam(1);

    EXPECT_FALSE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }

  {
    // Arg is an integral '4'
    llvm::APInt Int(32, 4);
    TemplateArgument Arg(Ctx, llvm::APSInt(Int), Ctx.UnsignedIntTy);

    // Param has is value-dependent expression (i.e., sizeof(T))
    auto const *Param = Params->getParam(3);

    EXPECT_FALSE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }

  {
    const int LHS = 40;
    const int RHS = 2;
    const int Result = 42;
    auto *ConstExpr = createBinOpExpr(LHS, RHS, Result);
    // Arg is instantiated with '40 + 2'
    TemplateArgument Arg(ConstExpr);

    // Param has default expr of '42'
    auto const *Param = Params->getParam(1);

    EXPECT_TRUE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }

  {
    const int LHS = 40;
    const int RHS = 1;
    const int Result = 41;
    auto *ConstExpr = createBinOpExpr(LHS, RHS, Result);

    // Arg is instantiated with '40 + 1'
    TemplateArgument Arg(ConstExpr);

    // Param has default expr of '42'
    auto const *Param = Params->getParam(1);

    EXPECT_FALSE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }

  {
    const int LHS = 4;
    const int RHS = 0;
    const int Result = 4;
    auto *ConstExpr = createBinOpExpr(LHS, RHS, Result);

    // Arg is instantiated with '4 + 0'
    TemplateArgument Arg(ConstExpr);

    // Param has is value-dependent expression (i.e., sizeof(T))
    auto const *Param = Params->getParam(3);

    EXPECT_FALSE(clang::isSubstitutedDefaultArgument(
        Ctx, Arg, Param, ArgList.asArray(), Params->getDepth()));
  }
}