aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
blob: bb8fb2404a9a58f1d873eabe5db57043e37d176b (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
//===--- UseDesignatedInitializersCheck.cpp - clang-tidy ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

#include "UseDesignatedInitializersCheck.h"
#include "../utils/DesignatedInitializers.h"
#include "clang/AST/APValue.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchersMacros.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang::tidy::modernize {

static constexpr char IgnoreSingleElementAggregatesName[] =
    "IgnoreSingleElementAggregates";
static constexpr bool IgnoreSingleElementAggregatesDefault = true;

static constexpr char RestrictToPODTypesName[] = "RestrictToPODTypes";
static constexpr bool RestrictToPODTypesDefault = false;

static constexpr char IgnoreMacrosName[] = "IgnoreMacros";
static constexpr bool IgnoreMacrosDefault = true;

static constexpr char StrictCStandardComplianceName[] =
    "StrictCStandardCompliance";
static constexpr bool StrictCStandardComplianceDefault = true;

static constexpr char StrictCppStandardComplianceName[] =
    "StrictCppStandardCompliance";
static constexpr bool StrictCppStandardComplianceDefault = true;

namespace {

struct Designators {

  Designators(const InitListExpr *InitList) : InitList(InitList) {
    assert(InitList->isSyntacticForm());
  };

  unsigned size() { return getCached().size(); }

  std::optional<llvm::StringRef> operator[](const SourceLocation &Location) {
    const auto &Designators = getCached();
    const auto Result = Designators.find(Location);
    if (Result == Designators.end())
      return {};
    const llvm::StringRef Designator = Result->getSecond();
    return (Designator.front() == '.' ? Designator.substr(1) : Designator)
        .trim("\0"); // Trim NULL characters appearing on Windows in the
                     // name.
  }

private:
  using LocationToNameMap = llvm::DenseMap<clang::SourceLocation, std::string>;

  std::optional<LocationToNameMap> CachedDesignators;
  const InitListExpr *InitList;

  LocationToNameMap &getCached() {
    return CachedDesignators ? *CachedDesignators
                             : CachedDesignators.emplace(
                                   utils::getUnwrittenDesignators(InitList));
  }
};

unsigned getNumberOfDesignated(const InitListExpr *SyntacticInitList) {
  return llvm::count_if(*SyntacticInitList, [](auto *InitExpr) {
    return isa<DesignatedInitExpr>(InitExpr);
  });
}

AST_MATCHER(CXXRecordDecl, isAggregate) {
  return Node.hasDefinition() && Node.isAggregate();
}

AST_MATCHER(CXXRecordDecl, isPOD) {
  return Node.hasDefinition() && Node.isPOD();
}

AST_MATCHER(InitListExpr, isFullyDesignated) {
  if (const InitListExpr *SyntacticForm =
          Node.isSyntacticForm() ? &Node : Node.getSyntacticForm())
    return getNumberOfDesignated(SyntacticForm) == SyntacticForm->getNumInits();
  return true;
}

AST_MATCHER(InitListExpr, hasMoreThanOneElement) {
  return Node.getNumInits() > 1;
}

} // namespace

UseDesignatedInitializersCheck::UseDesignatedInitializersCheck(
    StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context), IgnoreSingleElementAggregates(Options.get(
                                         IgnoreSingleElementAggregatesName,
                                         IgnoreSingleElementAggregatesDefault)),
      RestrictToPODTypes(
          Options.get(RestrictToPODTypesName, RestrictToPODTypesDefault)),
      IgnoreMacros(
          Options.getLocalOrGlobal(IgnoreMacrosName, IgnoreMacrosDefault)),
      StrictCStandardCompliance(Options.get(StrictCStandardComplianceName,
                                            StrictCStandardComplianceDefault)),
      StrictCppStandardCompliance(
          Options.get(StrictCppStandardComplianceName,
                      StrictCppStandardComplianceDefault)) {}

void UseDesignatedInitializersCheck::registerMatchers(MatchFinder *Finder) {
  const auto HasBaseWithFields =
      hasAnyBase(hasType(cxxRecordDecl(has(fieldDecl()))));
  Finder->addMatcher(
      initListExpr(
          hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
              cxxRecordDecl(
                  RestrictToPODTypes ? isPOD() : isAggregate(),
                  unless(anyOf(HasBaseWithFields, hasName("::std::array"))))
                  .bind("type"))))),
          IgnoreSingleElementAggregates ? hasMoreThanOneElement() : anything(),
          unless(isFullyDesignated()))
          .bind("init"),
      this);
}

void UseDesignatedInitializersCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *InitList = Result.Nodes.getNodeAs<InitListExpr>("init");
  const auto *Type = Result.Nodes.getNodeAs<CXXRecordDecl>("type");
  if (!Type || !InitList)
    return;
  const auto *SyntacticInitList = InitList->getSyntacticForm();
  if (!SyntacticInitList)
    return;
  Designators Designators{SyntacticInitList};
  const unsigned NumberOfDesignated = getNumberOfDesignated(SyntacticInitList);
  if (SyntacticInitList->getNumInits() - NumberOfDesignated >
      Designators.size())
    return;

  // If the whole initializer list is un-designated, issue only one warning and
  // a single fix-it for the whole expression.
  if (0 == NumberOfDesignated) {
    if (IgnoreMacros && InitList->getBeginLoc().isMacroID())
      return;
    {
      DiagnosticBuilder Diag =
          diag(InitList->getLBraceLoc(),
               "use designated initializer list to initialize %0");
      Diag << InitList->getType() << InitList->getSourceRange();
      for (const Stmt *InitExpr : *SyntacticInitList) {
        const auto Designator = Designators[InitExpr->getBeginLoc()];
        if (Designator && !Designator->empty())
          Diag << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
                                             ("." + *Designator + "=").str());
      }
    }
    diag(Type->getBeginLoc(), "aggregate type is defined here",
         DiagnosticIDs::Note);
    return;
  }

  // In case that only a few elements are un-designated (not all as before), the
  // check offers dedicated issues and fix-its for each of them.
  for (const auto *InitExpr : *SyntacticInitList) {
    if (isa<DesignatedInitExpr>(InitExpr))
      continue;
    if (IgnoreMacros && InitExpr->getBeginLoc().isMacroID())
      continue;
    const auto Designator = Designators[InitExpr->getBeginLoc()];
    if (!Designator || Designator->empty()) {
      // There should always be a designator. If there's unexpectedly none, we
      // at least report a generic diagnostic.
      diag(InitExpr->getBeginLoc(), "use designated init expression")
          << InitExpr->getSourceRange();
    } else {
      diag(InitExpr->getBeginLoc(),
           "use designated init expression to initialize field '%0'")
          << InitExpr->getSourceRange() << *Designator
          << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
                                        ("." + *Designator + "=").str());
    }
  }
}

void UseDesignatedInitializersCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, IgnoreSingleElementAggregatesName,
                IgnoreSingleElementAggregates);
  Options.store(Opts, RestrictToPODTypesName, RestrictToPODTypes);
  Options.store(Opts, IgnoreMacrosName, IgnoreMacros);
  Options.store(Opts, StrictCStandardComplianceName, StrictCStandardCompliance);
  Options.store(Opts, StrictCppStandardComplianceName,
                StrictCppStandardCompliance);
}

} // namespace clang::tidy::modernize