clang-tools 23.0.0git
DesignatedInitializers.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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///
9/// \file
10/// This file provides utilities for designated initializers.
11///
12//===----------------------------------------------------------------------===//
13
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/Type.h"
17#include "llvm/ADT/ScopeExit.h"
18
19namespace clang::tidy::utils {
20
21/// Returns true if Name is reserved, like _Foo or __Vector_base.
22static inline bool isReservedName(StringRef Name) {
23 // This doesn't catch all cases, but the most common.
24 return Name.size() >= 2 && Name[0] == '_' &&
25 (isUppercase(Name[1]) || Name[1] == '_');
26}
27
28namespace {
29
30// Helper class to iterate over the designator names of an aggregate type.
31//
32// For an array type, yields [0], [1], [2]...
33// For aggregate classes, yields null for each base, then .field1, .field2,
34// ...
35class AggregateDesignatorNames {
36public:
37 AggregateDesignatorNames(QualType T) {
38 if (!T.isNull()) {
39 T = T.getCanonicalType();
40 if (T->isArrayType()) {
41 IsArray = true;
42 Valid = true;
43 return;
44 }
45 if (const RecordDecl *RD = T->getAsRecordDecl()) {
46 Valid = true;
47 FieldsIt = RD->field_begin();
48 FieldsEnd = RD->field_end();
49 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
50 BasesIt = CRD->bases_begin();
51 BasesEnd = CRD->bases_end();
52 Valid = CRD->isAggregate();
53 }
54 OneField = Valid && BasesIt == BasesEnd && FieldsIt != FieldsEnd &&
55 std::next(FieldsIt) == FieldsEnd;
56 }
57 }
58 }
59 // Returns false if the type was not an aggregate.
60 operator bool() const { return Valid; }
61 // Advance to the next element in the aggregate.
62 void next() {
63 if (IsArray)
64 ++Index;
65 else if (BasesIt != BasesEnd)
66 ++BasesIt;
67 else if (FieldsIt != FieldsEnd)
68 ++FieldsIt;
69 }
70 // Print the designator to Out.
71 // Returns false if we could not produce a designator for this element.
72 bool append(std::string &Out, bool ForSubobject) {
73 if (IsArray) {
74 Out.push_back('[');
75 Out.append(std::to_string(Index));
76 Out.push_back(']');
77 return true;
78 }
79 if (BasesIt != BasesEnd)
80 return false; // Bases can't be designated. Should we make one up?
81 if (FieldsIt != FieldsEnd) {
82 StringRef FieldName;
83 if (const IdentifierInfo *II = FieldsIt->getIdentifier())
84 FieldName = II->getName();
85
86 // For certain objects, their subobjects may be named directly.
87 if (ForSubobject &&
88 (FieldsIt->isAnonymousStructOrUnion() ||
89 // std::array<int,3> x = {1,2,3}. Designators not strictly valid!
90 (OneField && isReservedName(FieldName))))
91 return true;
92
93 if (!FieldName.empty() && !isReservedName(FieldName)) {
94 Out.push_back('.');
95 Out.append(FieldName.begin(), FieldName.end());
96 return true;
97 }
98 return false;
99 }
100 return false;
101 }
102
103private:
104 bool Valid = false;
105 bool IsArray = false;
106 bool OneField = false; // e.g. std::array { T __elements[N]; }
107 unsigned Index = 0;
108 CXXRecordDecl::base_class_const_iterator BasesIt;
109 CXXRecordDecl::base_class_const_iterator BasesEnd;
110 RecordDecl::field_iterator FieldsIt;
111 RecordDecl::field_iterator FieldsEnd;
112};
113
114} // namespace
115
116// Collect designator labels describing the elements of an init list.
117//
118// This function contributes the designators of some (sub)object, which is
119// represented by the semantic InitListExpr Sem.
120// This includes any nested subobjects, but *only* if they are part of the
121// same original syntactic init list (due to brace elision). In other words,
122// it may descend into subobjects but not written init-lists.
123//
124// For example: struct Outer { Inner a,b; }; struct Inner { int x, y; }
125// Outer o{{1, 2}, 3};
126// This function will be called with Sem = { {1, 2}, {3, ImplicitValue} }
127// It should generate designators '.a:' and '.b.x:'.
128// '.a:' is produced directly without recursing into the written sublist.
129// (The written sublist will have a separate collectDesignators() call later).
130// Recursion with Prefix='.b' and Sem = {3, ImplicitValue} produces '.b.x:'.
131static void collectDesignators(const InitListExpr *Sem,
132 llvm::DenseMap<SourceLocation, std::string> &Out,
133 std::string &Prefix) {
134 if (!Sem || Sem->isTransparent())
135 return;
136 assert(Sem->isSemanticForm());
137
138 // The elements of the semantic form all correspond to direct subobjects of
139 // the aggregate type. `Fields` iterates over these subobject names.
140 AggregateDesignatorNames Fields(Sem->getType());
141 if (!Fields)
142 return;
143 for (const Expr *Init : Sem->inits()) {
144 const llvm::scope_exit Next([&, Size(Prefix.size())] {
145 Fields.next(); // Always advance to the next subobject name.
146 Prefix.resize(Size); // Erase any designator we appended.
147 });
148 // Skip for a broken initializer or if it is a "hole" in a subobject that
149 // was not explicitly initialized.
150 if (!Init || isa<ImplicitValueInitExpr>(Init))
151 continue;
152
153 const auto *BraceElidedSubobject = dyn_cast<InitListExpr>(Init);
154 if (BraceElidedSubobject && BraceElidedSubobject->isExplicit())
155 BraceElidedSubobject = nullptr; // there were braces!
156
157 if (!Fields.append(Prefix, BraceElidedSubobject != nullptr))
158 continue; // no designator available for this subobject
159 if (BraceElidedSubobject) {
160 // If the braces were elided, this aggregate subobject is initialized
161 // inline in the same syntactic list.
162 // Descend into the semantic list describing the subobject.
163 collectDesignators(BraceElidedSubobject, Out, Prefix);
164 continue;
165 }
166 Out.try_emplace(Init->getBeginLoc(), Prefix);
167 }
168}
169
170llvm::DenseMap<SourceLocation, std::string>
171getUnwrittenDesignators(const InitListExpr *Syn) {
172 // Traverse the semantic form to find the designators.
173 // We use their SourceLocation to correlate with the syntactic form later.
174 llvm::DenseMap<SourceLocation, std::string> Designators;
175 std::string EmptyPrefix;
176 collectDesignators(Syn->isSemanticForm() ? Syn : Syn->getSemanticForm(),
177 Designators, EmptyPrefix);
178 return Designators;
179}
180
181} // namespace clang::tidy::utils
This file provides utilities for designated initializers.
static bool isReservedName(StringRef Name)
Returns true if Name is reserved, like _Foo or __Vector_base.
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
Get designators describing the elements of a (syntactic) init list.
static void collectDesignators(const InitListExpr *Sem, llvm::DenseMap< SourceLocation, std::string > &Out, std::string &Prefix)