1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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///
9/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15/// ------------------------- - -- ---------------------------
16/// declaration-specifiers \ | /
17/// declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjCCommon.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/Basic/ExceptionSpecificationType.h"
29#include "clang/Basic/Lambda.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Lex/Token.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/ParsedAttr.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/ErrorHandling.h"
39#include <optional>
40
41namespace clang {
42 class ASTContext;
43 class CXXRecordDecl;
44 class TypeLoc;
45 class LangOptions;
46 class IdentifierInfo;
47 class NamespaceBaseDecl;
48 class ObjCDeclSpec;
49 class Sema;
50 class Declarator;
51 struct TemplateIdAnnotation;
52
53/// Represents a C++ nested-name-specifier or a global scope specifier.
54///
55/// These can be in 3 states:
56/// 1) Not present, identified by isEmpty()
57/// 2) Present, identified by isNotEmpty()
58/// 2.a) Valid, identified by isValid()
59/// 2.b) Invalid, identified by isInvalid().
60///
61/// isSet() is deprecated because it mostly corresponded to "valid" but was
62/// often used as if it meant "present".
63///
64/// The actual scope is described by getScopeRep().
65///
66/// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be empty
67/// or contain the template parameter lists attached to the current declaration.
68/// Consider the following example:
69/// template <class T> void SomeType<T>::some_method() {}
70/// If CXXScopeSpec refers to SomeType<T> then TemplateParamLists will contain
71/// a single element referring to template <class T>.
72
73class CXXScopeSpec {
74 SourceRange Range;
75 NestedNameSpecifierLocBuilder Builder;
76 ArrayRef<TemplateParameterList *> TemplateParamLists;
77
78public:
79 SourceRange getRange() const { return Range; }
80 void setRange(SourceRange R) { Range = R; }
81 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
82 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
83 SourceLocation getBeginLoc() const { return Range.getBegin(); }
84 SourceLocation getEndLoc() const { return Range.getEnd(); }
85
86 void setTemplateParamLists(ArrayRef<TemplateParameterList *> L) {
87 TemplateParamLists = L;
88 }
89 ArrayRef<TemplateParameterList *> getTemplateParamLists() const {
90 return TemplateParamLists;
91 }
92
93 /// Retrieve the representation of the nested-name-specifier.
94 NestedNameSpecifier getScopeRep() const {
95 return Builder.getRepresentation();
96 }
97
98 /// Make a nested-name-specifier of the form 'type::'.
99 ///
100 /// \param Context The AST context in which this nested-name-specifier
101 /// resides.
102 ///
103 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
104 ///
105 /// \param TL The TypeLoc that describes the type preceding the '::'.
106 ///
107 /// \param ColonColonLoc The location of the trailing '::'.
108 void Make(ASTContext &Context, TypeLoc TL, SourceLocation ColonColonLoc);
109
110 /// Extend the current nested-name-specifier by another
111 /// nested-name-specifier component of the form 'namespace::'.
112 ///
113 /// \param Context The AST context in which this nested-name-specifier
114 /// resides.
115 ///
116 /// \param Namespace The namespace or the namespace alias.
117 ///
118 /// \param NamespaceLoc The location of the namespace name or the namespace
119 /// alias.
120 ///
121 /// \param ColonColonLoc The location of the trailing '::'.
122 void Extend(ASTContext &Context, NamespaceBaseDecl *Namespace,
123 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
124
125 /// Turn this (empty) nested-name-specifier into the global
126 /// nested-name-specifier '::'.
127 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
128
129 /// Turns this (empty) nested-name-specifier into '__super'
130 /// nested-name-specifier.
131 ///
132 /// \param Context The AST context in which this nested-name-specifier
133 /// resides.
134 ///
135 /// \param RD The declaration of the class in which nested-name-specifier
136 /// appeared.
137 ///
138 /// \param SuperLoc The location of the '__super' keyword.
139 /// name.
140 ///
141 /// \param ColonColonLoc The location of the trailing '::'.
142 void MakeMicrosoftSuper(ASTContext &Context, CXXRecordDecl *RD,
143 SourceLocation SuperLoc,
144 SourceLocation ColonColonLoc);
145
146 /// Make a new nested-name-specifier from incomplete source-location
147 /// information.
148 ///
149 /// FIXME: This routine should be used very, very rarely, in cases where we
150 /// need to synthesize a nested-name-specifier. Most code should instead use
151 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
152 void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier,
153 SourceRange R);
154
155 /// Adopt an existing nested-name-specifier (with source-range
156 /// information).
157 void Adopt(NestedNameSpecifierLoc Other);
158
159 /// Retrieve a nested-name-specifier with location information, copied
160 /// into the given AST context.
161 ///
162 /// \param Context The context into which this nested-name-specifier will be
163 /// copied.
164 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
165
166 /// Retrieve the location of the name in the last qualifier
167 /// in this nested name specifier.
168 ///
169 /// For example, the location of \c bar
170 /// in
171 /// \verbatim
172 /// \::foo::bar<0>::
173 /// ^~~
174 /// \endverbatim
175 SourceLocation getLastQualifierNameLoc() const;
176
177 /// No scope specifier.
178 bool isEmpty() const { return Range.isInvalid() && !getScopeRep(); }
179 /// A scope specifier is present, but may be valid or invalid.
180 bool isNotEmpty() const { return !isEmpty(); }
181
182 /// An error occurred during parsing of the scope specifier.
183 bool isInvalid() const { return Range.isValid() && !getScopeRep(); }
184 /// A scope specifier is present, and it refers to a real scope.
185 bool isValid() const { return bool(getScopeRep()); }
186
187 /// Indicate that this nested-name-specifier is invalid.
188 void SetInvalid(SourceRange R) {
189 assert(R.isValid() && "Must have a valid source range");
190 if (Range.getBegin().isInvalid())
191 Range.setBegin(R.getBegin());
192 Range.setEnd(R.getEnd());
193 Builder.Clear();
194 }
195
196 /// Deprecated. Some call sites intend isNotEmpty() while others intend
197 /// isValid().
198 bool isSet() const { return bool(getScopeRep()); }
199
200 void clear() {
201 Range = SourceRange();
202 Builder.Clear();
203 }
204
205 /// Retrieve the data associated with the source-location information.
206 char *location_data() const { return Builder.getBuffer().first; }
207
208 /// Retrieve the size of the data associated with source-location
209 /// information.
210 unsigned location_size() const { return Builder.getBuffer().second; }
211};
212
213/// Captures information about "declaration specifiers".
214///
215/// "Declaration specifiers" encompasses storage-class-specifiers,
216/// type-specifiers, type-qualifiers, and function-specifiers.
217class DeclSpec {
218public:
219 /// storage-class-specifier
220 /// \note The order of these enumerators is important for diagnostics.
221 enum SCS {
222 SCS_unspecified = 0,
223 SCS_typedef,
224 SCS_extern,
225 SCS_static,
226 SCS_auto,
227 SCS_register,
228 SCS_private_extern,
229 SCS_mutable
230 };
231
232 // Import thread storage class specifier enumeration and constants.
233 // These can be combined with SCS_extern and SCS_static.
234 typedef ThreadStorageClassSpecifier TSCS;
235 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
236 static const TSCS TSCS___thread = clang::TSCS___thread;
237 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
238 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
239
240 enum TSC {
241 TSC_unspecified,
242 TSC_imaginary, // Unsupported
243 TSC_complex
244 };
245
246 // Import type specifier type enumeration and constants.
247 typedef TypeSpecifierType TST;
248 static const TST TST_unspecified = clang::TST_unspecified;
249 static const TST TST_void = clang::TST_void;
250 static const TST TST_char = clang::TST_char;
251 static const TST TST_wchar = clang::TST_wchar;
252 static const TST TST_char8 = clang::TST_char8;
253 static const TST TST_char16 = clang::TST_char16;
254 static const TST TST_char32 = clang::TST_char32;
255 static const TST TST_int = clang::TST_int;
256 static const TST TST_int128 = clang::TST_int128;
257 static const TST TST_bitint = clang::TST_bitint;
258 static const TST TST_half = clang::TST_half;
259 static const TST TST_BFloat16 = clang::TST_BFloat16;
260 static const TST TST_float = clang::TST_float;
261 static const TST TST_double = clang::TST_double;
262 static const TST TST_float16 = clang::TST_Float16;
263 static const TST TST_accum = clang::TST_Accum;
264 static const TST TST_fract = clang::TST_Fract;
265 static const TST TST_float128 = clang::TST_float128;
266 static const TST TST_ibm128 = clang::TST_ibm128;
267 static const TST TST_bool = clang::TST_bool;
268 static const TST TST_decimal32 = clang::TST_decimal32;
269 static const TST TST_decimal64 = clang::TST_decimal64;
270 static const TST TST_decimal128 = clang::TST_decimal128;
271 static const TST TST_enum = clang::TST_enum;
272 static const TST TST_union = clang::TST_union;
273 static const TST TST_struct = clang::TST_struct;
274 static const TST TST_interface = clang::TST_interface;
275 static const TST TST_class = clang::TST_class;
276 static const TST TST_typename = clang::TST_typename;
277 static const TST TST_typeofType = clang::TST_typeofType;
278 static const TST TST_typeofExpr = clang::TST_typeofExpr;
279 static const TST TST_typeof_unqualType = clang::TST_typeof_unqualType;
280 static const TST TST_typeof_unqualExpr = clang::TST_typeof_unqualExpr;
281 static const TST TST_decltype = clang::TST_decltype;
282 static const TST TST_decltype_auto = clang::TST_decltype_auto;
283 static const TST TST_typename_pack_indexing =
284 clang::TST_typename_pack_indexing;
285#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
286 static const TST TST_##Trait = clang::TST_##Trait;
287#include "clang/Basic/TransformTypeTraits.def"
288 static const TST TST_auto = clang::TST_auto;
289 static const TST TST_auto_type = clang::TST_auto_type;
290 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
291 static const TST TST_atomic = clang::TST_atomic;
292#define GENERIC_IMAGE_TYPE(ImgType, Id) \
293 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
294#include "clang/Basic/OpenCLImageTypes.def"
295#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
296 static const TST TST_##Name = clang::TST_##Name;
297#include "clang/Basic/HLSLIntangibleTypes.def"
298 static const TST TST_error = clang::TST_error;
299
300 // type-qualifiers
301 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
302 TQ_unspecified = 0,
303 TQ_const = 1,
304 TQ_restrict = 2,
305 TQ_volatile = 4,
306 TQ_unaligned = 8,
307 // This has no corresponding Qualifiers::TQ value, because it's not treated
308 // as a qualifier in our type system.
309 TQ_atomic = 16
310 };
311
312 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
313 /// returned by getParsedSpecifiers.
314 enum ParsedSpecifiers {
315 PQ_None = 0,
316 PQ_StorageClassSpecifier = 1,
317 PQ_TypeSpecifier = 2,
318 PQ_TypeQualifier = 4,
319 PQ_FunctionSpecifier = 8
320 // FIXME: Attributes should be included here.
321 };
322
323 enum FriendSpecified : bool { No, Yes };
324
325private:
326 // storage-class-specifier
327 LLVM_PREFERRED_TYPE(SCS)
328 unsigned StorageClassSpec : 3;
329 LLVM_PREFERRED_TYPE(TSCS)
330 unsigned ThreadStorageClassSpec : 2;
331 LLVM_PREFERRED_TYPE(bool)
332 unsigned SCS_extern_in_linkage_spec : 1;
333
334 // type-specifier
335 LLVM_PREFERRED_TYPE(TypeSpecifierWidth)
336 unsigned TypeSpecWidth : 2;
337 LLVM_PREFERRED_TYPE(TSC)
338 unsigned TypeSpecComplex : 2;
339 LLVM_PREFERRED_TYPE(TypeSpecifierSign)
340 unsigned TypeSpecSign : 2;
341 LLVM_PREFERRED_TYPE(TST)
342 unsigned TypeSpecType : 7;
343 LLVM_PREFERRED_TYPE(bool)
344 unsigned TypeAltiVecVector : 1;
345 LLVM_PREFERRED_TYPE(bool)
346 unsigned TypeAltiVecPixel : 1;
347 LLVM_PREFERRED_TYPE(bool)
348 unsigned TypeAltiVecBool : 1;
349 LLVM_PREFERRED_TYPE(bool)
350 unsigned TypeSpecOwned : 1;
351 LLVM_PREFERRED_TYPE(bool)
352 unsigned TypeSpecPipe : 1;
353 LLVM_PREFERRED_TYPE(bool)
354 unsigned TypeSpecSat : 1;
355 LLVM_PREFERRED_TYPE(bool)
356 unsigned ConstrainedAuto : 1;
357
358 // type-qualifiers
359 LLVM_PREFERRED_TYPE(TQ)
360 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
361
362 // function-specifier
363 LLVM_PREFERRED_TYPE(bool)
364 unsigned FS_inline_specified : 1;
365 LLVM_PREFERRED_TYPE(bool)
366 unsigned FS_forceinline_specified: 1;
367 LLVM_PREFERRED_TYPE(bool)
368 unsigned FS_virtual_specified : 1;
369 LLVM_PREFERRED_TYPE(bool)
370 unsigned FS_noreturn_specified : 1;
371
372 // friend-specifier
373 LLVM_PREFERRED_TYPE(bool)
374 unsigned FriendSpecifiedFirst : 1;
375
376 // constexpr-specifier
377 LLVM_PREFERRED_TYPE(ConstexprSpecKind)
378 unsigned ConstexprSpecifier : 2;
379
380 union {
381 UnionParsedType TypeRep;
382 Decl *DeclRep;
383 Expr *ExprRep;
384 TemplateIdAnnotation *TemplateIdRep;
385 };
386 Expr *PackIndexingExpr = nullptr;
387
388 /// ExplicitSpecifier - Store information about explicit spicifer.
389 ExplicitSpecifier FS_explicit_specifier;
390
391 // attributes.
392 ParsedAttributes Attrs;
393
394 // Scope specifier for the type spec, if applicable.
395 CXXScopeSpec TypeScope;
396
397 // SourceLocation info. These are null if the item wasn't specified or if
398 // the setting was synthesized.
399 SourceRange Range;
400
401 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
402 SourceRange TSWRange;
403 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc, EllipsisLoc;
404 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
405 /// typename, then this is the location of the named type (if present);
406 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
407 /// TSTNameLoc provides source range info for tag types.
408 SourceLocation TSTNameLoc;
409 SourceRange TypeofParensRange;
410 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
411 TQ_unalignedLoc;
412 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
413 SourceLocation FS_explicitCloseParenLoc;
414 SourceLocation FS_forceinlineLoc;
415 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
416 SourceLocation TQ_pipeLoc;
417
418 WrittenBuiltinSpecs writtenBS;
419 void SaveWrittenBuiltinSpecs();
420
421 ObjCDeclSpec *ObjCQualifiers;
422
423 static bool isTypeRep(TST T) {
424 return T == TST_atomic || T == TST_typename || T == TST_typeofType ||
425 T == TST_typeof_unqualType || isTransformTypeTrait(T) ||
426 T == TST_typename_pack_indexing;
427 }
428 static bool isExprRep(TST T) {
429 return T == TST_typeofExpr || T == TST_typeof_unqualExpr ||
430 T == TST_decltype || T == TST_bitint;
431 }
432 static bool isTemplateIdRep(TST T) {
433 return (T == TST_auto || T == TST_decltype_auto);
434 }
435
436 DeclSpec(const DeclSpec &) = delete;
437 void operator=(const DeclSpec &) = delete;
438public:
439 static bool isDeclRep(TST T) {
440 return (T == TST_enum || T == TST_struct ||
441 T == TST_interface || T == TST_union ||
442 T == TST_class);
443 }
444 static bool isTransformTypeTrait(TST T) {
445 constexpr std::array<TST, 16> Traits = {
446#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
447#include "clang/Basic/TransformTypeTraits.def"
448 };
449
450 return T >= Traits.front() && T <= Traits.back();
451 }
452
453 DeclSpec(AttributeFactory &attrFactory)
454 : StorageClassSpec(SCS_unspecified),
455 ThreadStorageClassSpec(TSCS_unspecified),
456 SCS_extern_in_linkage_spec(false),
457 TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
458 TypeSpecComplex(TSC_unspecified),
459 TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
460 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
461 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
462 TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
463 TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
464 FS_forceinline_specified(false), FS_virtual_specified(false),
465 FS_noreturn_specified(false), FriendSpecifiedFirst(false),
466 ConstexprSpecifier(
467 static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
468 Attrs(attrFactory), writtenBS(), ObjCQualifiers(nullptr) {}
469
470 // storage-class-specifier
471 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
472 TSCS getThreadStorageClassSpec() const {
473 return (TSCS)ThreadStorageClassSpec;
474 }
475 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
476 void setExternInLinkageSpec(bool Value) {
477 SCS_extern_in_linkage_spec = Value;
478 }
479
480 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
481 SourceLocation getThreadStorageClassSpecLoc() const {
482 return ThreadStorageClassSpecLoc;
483 }
484
485 void ClearStorageClassSpecs() {
486 StorageClassSpec = DeclSpec::SCS_unspecified;
487 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
488 SCS_extern_in_linkage_spec = false;
489 StorageClassSpecLoc = SourceLocation();
490 ThreadStorageClassSpecLoc = SourceLocation();
491 }
492
493 void ClearTypeSpecType() {
494 TypeSpecType = DeclSpec::TST_unspecified;
495 TypeSpecOwned = false;
496 TSTLoc = SourceLocation();
497 }
498
499 // type-specifier
500 TypeSpecifierWidth getTypeSpecWidth() const {
501 return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
502 }
503 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
504 TypeSpecifierSign getTypeSpecSign() const {
505 return static_cast<TypeSpecifierSign>(TypeSpecSign);
506 }
507 TST getTypeSpecType() const { return (TST)TypeSpecType; }
508 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
509 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
510 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
511 bool isTypeSpecOwned() const { return TypeSpecOwned; }
512 bool isTypeRep() const { return isTypeRep(T: (TST) TypeSpecType); }
513 bool isTypeSpecPipe() const { return TypeSpecPipe; }
514 bool isTypeSpecSat() const { return TypeSpecSat; }
515 bool isConstrainedAuto() const { return ConstrainedAuto; }
516
517 ParsedType getRepAsType() const {
518 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
519 return TypeRep;
520 }
521 Decl *getRepAsDecl() const {
522 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
523 return DeclRep;
524 }
525 Expr *getRepAsExpr() const {
526 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
527 return ExprRep;
528 }
529
530 Expr *getPackIndexingExpr() const {
531 assert(TypeSpecType == TST_typename_pack_indexing &&
532 "DeclSpec is not a pack indexing expr");
533 return PackIndexingExpr;
534 }
535
536 TemplateIdAnnotation *getRepAsTemplateId() const {
537 assert(isTemplateIdRep((TST) TypeSpecType) &&
538 "DeclSpec does not store a template id");
539 return TemplateIdRep;
540 }
541 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
542 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
543
544 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
545 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
546 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
547
548 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
549 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
550 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
551 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
552 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
553 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
554 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
555
556 SourceLocation getTypeSpecTypeNameLoc() const {
557 assert(isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) ||
558 isExprRep((TST)TypeSpecType));
559 return TSTNameLoc;
560 }
561
562 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
563 void setTypeArgumentRange(SourceRange range) { TypeofParensRange = range; }
564
565 bool hasAutoTypeSpec() const {
566 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
567 TypeSpecType == TST_decltype_auto);
568 }
569
570 bool hasTagDefinition() const;
571
572 /// Turn a type-specifier-type into a string like "_Bool" or "union".
573 static const char *getSpecifierName(DeclSpec::TST T,
574 const PrintingPolicy &Policy);
575 static const char *getSpecifierName(DeclSpec::TQ Q);
576 static const char *getSpecifierName(TypeSpecifierSign S);
577 static const char *getSpecifierName(DeclSpec::TSC C);
578 static const char *getSpecifierName(TypeSpecifierWidth W);
579 static const char *getSpecifierName(DeclSpec::SCS S);
580 static const char *getSpecifierName(DeclSpec::TSCS S);
581 static const char *getSpecifierName(ConstexprSpecKind C);
582
583 // type-qualifiers
584
585 /// getTypeQualifiers - Return a set of TQs.
586 unsigned getTypeQualifiers() const { return TypeQualifiers; }
587 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
588 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
589 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
590 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
591 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
592 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
593 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
594
595 /// Clear out all of the type qualifiers.
596 void ClearTypeQualifiers() {
597 TypeQualifiers = 0;
598 TQ_constLoc = SourceLocation();
599 TQ_restrictLoc = SourceLocation();
600 TQ_volatileLoc = SourceLocation();
601 TQ_atomicLoc = SourceLocation();
602 TQ_unalignedLoc = SourceLocation();
603 TQ_pipeLoc = SourceLocation();
604 }
605
606 // function-specifier
607 bool isInlineSpecified() const {
608 return FS_inline_specified | FS_forceinline_specified;
609 }
610 SourceLocation getInlineSpecLoc() const {
611 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
612 }
613
614 ExplicitSpecifier getExplicitSpecifier() const {
615 return FS_explicit_specifier;
616 }
617
618 bool isVirtualSpecified() const { return FS_virtual_specified; }
619 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
620
621 bool hasExplicitSpecifier() const {
622 return FS_explicit_specifier.isSpecified();
623 }
624 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
625 SourceRange getExplicitSpecRange() const {
626 return FS_explicit_specifier.getExpr()
627 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
628 : SourceRange(FS_explicitLoc);
629 }
630
631 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
632 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
633
634 void ClearFunctionSpecs() {
635 FS_inline_specified = false;
636 FS_inlineLoc = SourceLocation();
637 FS_forceinline_specified = false;
638 FS_forceinlineLoc = SourceLocation();
639 FS_virtual_specified = false;
640 FS_virtualLoc = SourceLocation();
641 FS_explicit_specifier = ExplicitSpecifier();
642 FS_explicitLoc = SourceLocation();
643 FS_explicitCloseParenLoc = SourceLocation();
644 FS_noreturn_specified = false;
645 FS_noreturnLoc = SourceLocation();
646 }
647
648 /// This method calls the passed in handler on each CVRU qual being
649 /// set.
650 /// Handle - a handler to be invoked.
651 void forEachCVRUQualifier(
652 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
653
654 /// This method calls the passed in handler on each qual being
655 /// set.
656 /// Handle - a handler to be invoked.
657 void forEachQualifier(
658 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
659
660 /// Return true if any type-specifier has been found.
661 bool hasTypeSpecifier() const {
662 return getTypeSpecType() != DeclSpec::TST_unspecified ||
663 getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
664 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
665 getTypeSpecSign() != TypeSpecifierSign::Unspecified;
666 }
667
668 /// Return a bitmask of which flavors of specifiers this
669 /// DeclSpec includes.
670 unsigned getParsedSpecifiers() const;
671
672 /// isEmpty - Return true if this declaration specifier is completely empty:
673 /// no tokens were parsed in the production of it.
674 bool isEmpty() const {
675 return getParsedSpecifiers() == DeclSpec::PQ_None;
676 }
677
678 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
679 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
680
681 /// These methods set the specified attribute of the DeclSpec and
682 /// return false if there was no error. If an error occurs (for
683 /// example, if we tried to set "auto" on a spec with "extern"
684 /// already set), they return true and set PrevSpec and DiagID
685 /// such that
686 /// Diag(Loc, DiagID) << PrevSpec;
687 /// will yield a useful result.
688 ///
689 /// TODO: use a more general approach that still allows these
690 /// diagnostics to be ignored when desired.
691 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
692 const char *&PrevSpec, unsigned &DiagID,
693 const PrintingPolicy &Policy);
694 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
695 const char *&PrevSpec, unsigned &DiagID);
696 bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
697 const char *&PrevSpec, unsigned &DiagID,
698 const PrintingPolicy &Policy);
699 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
700 unsigned &DiagID);
701 bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
702 const char *&PrevSpec, unsigned &DiagID);
703 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
704 unsigned &DiagID, const PrintingPolicy &Policy);
705 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
706 unsigned &DiagID, ParsedType Rep,
707 const PrintingPolicy &Policy);
708 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
709 unsigned &DiagID, TypeResult Rep,
710 const PrintingPolicy &Policy) {
711 if (Rep.isInvalid())
712 return SetTypeSpecError();
713 return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep: Rep.get(), Policy);
714 }
715 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
716 unsigned &DiagID, Decl *Rep, bool Owned,
717 const PrintingPolicy &Policy);
718 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
719 SourceLocation TagNameLoc, const char *&PrevSpec,
720 unsigned &DiagID, ParsedType Rep,
721 const PrintingPolicy &Policy);
722 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
723 SourceLocation TagNameLoc, const char *&PrevSpec,
724 unsigned &DiagID, Decl *Rep, bool Owned,
725 const PrintingPolicy &Policy);
726 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
727 unsigned &DiagID, TemplateIdAnnotation *Rep,
728 const PrintingPolicy &Policy);
729
730 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
731 unsigned &DiagID, Expr *Rep,
732 const PrintingPolicy &policy);
733 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
734 const char *&PrevSpec, unsigned &DiagID,
735 const PrintingPolicy &Policy);
736 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
737 const char *&PrevSpec, unsigned &DiagID,
738 const PrintingPolicy &Policy);
739 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
740 const char *&PrevSpec, unsigned &DiagID,
741 const PrintingPolicy &Policy);
742 bool SetTypePipe(bool isPipe, SourceLocation Loc,
743 const char *&PrevSpec, unsigned &DiagID,
744 const PrintingPolicy &Policy);
745 bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth,
746 const char *&PrevSpec, unsigned &DiagID,
747 const PrintingPolicy &Policy);
748 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
749 unsigned &DiagID);
750
751 void SetPackIndexingExpr(SourceLocation EllipsisLoc, Expr *Pack);
752
753 bool SetTypeSpecError();
754 void UpdateDeclRep(Decl *Rep) {
755 assert(isDeclRep((TST) TypeSpecType));
756 DeclRep = Rep;
757 }
758 void UpdateTypeRep(ParsedType Rep) {
759 assert(isTypeRep((TST) TypeSpecType));
760 TypeRep = Rep;
761 }
762 void UpdateExprRep(Expr *Rep) {
763 assert(isExprRep((TST) TypeSpecType));
764 ExprRep = Rep;
765 }
766
767 bool SetTypeQual(TQ T, SourceLocation Loc);
768
769 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
770 unsigned &DiagID, const LangOptions &Lang);
771
772 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
773 unsigned &DiagID);
774 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
775 unsigned &DiagID);
776 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
777 unsigned &DiagID);
778 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
779 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
780 SourceLocation CloseParenLoc);
781 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
782 unsigned &DiagID);
783
784 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
785 unsigned &DiagID);
786 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
787 unsigned &DiagID);
788 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
789 const char *&PrevSpec, unsigned &DiagID);
790
791 FriendSpecified isFriendSpecified() const {
792 return static_cast<FriendSpecified>(FriendLoc.isValid());
793 }
794
795 bool isFriendSpecifiedFirst() const { return FriendSpecifiedFirst; }
796
797 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
798
799 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
800 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
801
802 ConstexprSpecKind getConstexprSpecifier() const {
803 return ConstexprSpecKind(ConstexprSpecifier);
804 }
805
806 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
807 bool hasConstexprSpecifier() const {
808 return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
809 }
810
811 void ClearConstexprSpec() {
812 ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
813 ConstexprLoc = SourceLocation();
814 }
815
816 AttributePool &getAttributePool() const {
817 return Attrs.getPool();
818 }
819
820 /// Concatenates two attribute lists.
821 ///
822 /// The GCC attribute syntax allows for the following:
823 ///
824 /// \code
825 /// short __attribute__(( unused, deprecated ))
826 /// int __attribute__(( may_alias, aligned(16) )) var;
827 /// \endcode
828 ///
829 /// This declares 4 attributes using 2 lists. The following syntax is
830 /// also allowed and equivalent to the previous declaration.
831 ///
832 /// \code
833 /// short __attribute__((unused)) __attribute__((deprecated))
834 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
835 /// \endcode
836 ///
837 void addAttributes(const ParsedAttributesView &AL) {
838 Attrs.prepend(B: AL.begin(), E: AL.end());
839 }
840
841 bool hasAttributes() const { return !Attrs.empty(); }
842
843 ParsedAttributes &getAttributes() { return Attrs; }
844 const ParsedAttributes &getAttributes() const { return Attrs; }
845
846 void takeAttributesAppendingingFrom(ParsedAttributes &attrs) {
847 Attrs.takeAllAppendingFrom(Other&: attrs);
848 }
849
850 /// Finish - This does final analysis of the declspec, issuing diagnostics for
851 /// things like "_Complex" (lacking an FP type). After calling this method,
852 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
853 void Finish(Sema &S, const PrintingPolicy &Policy);
854
855 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
856 return writtenBS;
857 }
858
859 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
860 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
861
862 /// Checks if this DeclSpec can stand alone, without a Declarator.
863 ///
864 /// Only tag declspecs can stand alone.
865 bool isMissingDeclaratorOk();
866};
867
868/// Captures information about "declaration specifiers" specific to
869/// Objective-C.
870class ObjCDeclSpec {
871public:
872 /// ObjCDeclQualifier - Qualifier used on types in method
873 /// declarations. Not all combinations are sensible. Parameters
874 /// can be one of { in, out, inout } with one of { bycopy, byref }.
875 /// Returns can either be { oneway } or not.
876 ///
877 /// This should be kept in sync with Decl::ObjCDeclQualifier.
878 enum ObjCDeclQualifier {
879 DQ_None = 0x0,
880 DQ_In = 0x1,
881 DQ_Inout = 0x2,
882 DQ_Out = 0x4,
883 DQ_Bycopy = 0x8,
884 DQ_Byref = 0x10,
885 DQ_Oneway = 0x20,
886 DQ_CSNullability = 0x40
887 };
888
889 ObjCDeclSpec()
890 : objcDeclQualifier(DQ_None),
891 PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
892 GetterName(nullptr), SetterName(nullptr) {}
893
894 ObjCDeclQualifier getObjCDeclQualifier() const {
895 return (ObjCDeclQualifier)objcDeclQualifier;
896 }
897 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
898 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
899 }
900 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
901 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
902 }
903
904 ObjCPropertyAttribute::Kind getPropertyAttributes() const {
905 return ObjCPropertyAttribute::Kind(PropertyAttributes);
906 }
907 void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
908 PropertyAttributes =
909 (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
910 }
911
912 NullabilityKind getNullability() const {
913 assert(
914 ((getObjCDeclQualifier() & DQ_CSNullability) ||
915 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
916 "Objective-C declspec doesn't have nullability");
917 return static_cast<NullabilityKind>(Nullability);
918 }
919
920 SourceLocation getNullabilityLoc() const {
921 assert(
922 ((getObjCDeclQualifier() & DQ_CSNullability) ||
923 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
924 "Objective-C declspec doesn't have nullability");
925 return NullabilityLoc;
926 }
927
928 void setNullability(SourceLocation loc, NullabilityKind kind) {
929 assert(
930 ((getObjCDeclQualifier() & DQ_CSNullability) ||
931 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
932 "Set the nullability declspec or property attribute first");
933 Nullability = static_cast<unsigned>(kind);
934 NullabilityLoc = loc;
935 }
936
937 const IdentifierInfo *getGetterName() const { return GetterName; }
938 IdentifierInfo *getGetterName() { return GetterName; }
939 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
940 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
941 GetterName = name;
942 GetterNameLoc = loc;
943 }
944
945 const IdentifierInfo *getSetterName() const { return SetterName; }
946 IdentifierInfo *getSetterName() { return SetterName; }
947 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
948 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
949 SetterName = name;
950 SetterNameLoc = loc;
951 }
952
953private:
954 // FIXME: These two are unrelated and mutually exclusive. So perhaps
955 // we can put them in a union to reflect their mutual exclusivity
956 // (space saving is negligible).
957 unsigned objcDeclQualifier : 7;
958
959 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
960 unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
961
962 unsigned Nullability : 2;
963
964 SourceLocation NullabilityLoc;
965
966 IdentifierInfo *GetterName; // getter name or NULL if no getter
967 IdentifierInfo *SetterName; // setter name or NULL if no setter
968 SourceLocation GetterNameLoc; // location of the getter attribute's value
969 SourceLocation SetterNameLoc; // location of the setter attribute's value
970
971};
972
973/// Describes the kind of unqualified-id parsed.
974enum class UnqualifiedIdKind {
975 /// An identifier.
976 IK_Identifier,
977 /// An overloaded operator name, e.g., operator+.
978 IK_OperatorFunctionId,
979 /// A conversion function name, e.g., operator int.
980 IK_ConversionFunctionId,
981 /// A user-defined literal name, e.g., operator "" _i.
982 IK_LiteralOperatorId,
983 /// A constructor name.
984 IK_ConstructorName,
985 /// A constructor named via a template-id.
986 IK_ConstructorTemplateId,
987 /// A destructor name.
988 IK_DestructorName,
989 /// A template-id, e.g., f<int>.
990 IK_TemplateId,
991 /// An implicit 'self' parameter
992 IK_ImplicitSelfParam,
993 /// A deduction-guide name (a template-name)
994 IK_DeductionGuideName
995};
996
997/// Represents a C++ unqualified-id that has been parsed.
998class UnqualifiedId {
999private:
1000 UnqualifiedId(const UnqualifiedId &Other) = delete;
1001 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
1002
1003 /// Describes the kind of unqualified-id parsed.
1004 UnqualifiedIdKind Kind;
1005
1006public:
1007 struct OFI {
1008 /// The kind of overloaded operator.
1009 OverloadedOperatorKind Operator;
1010
1011 /// The source locations of the individual tokens that name
1012 /// the operator, e.g., the "new", "[", and "]" tokens in
1013 /// operator new [].
1014 ///
1015 /// Different operators have different numbers of tokens in their name,
1016 /// up to three. Any remaining source locations in this array will be
1017 /// set to an invalid value for operators with fewer than three tokens.
1018 SourceLocation SymbolLocations[3];
1019 };
1020
1021 /// Anonymous union that holds extra data associated with the
1022 /// parsed unqualified-id.
1023 union {
1024 /// When Kind == IK_Identifier, the parsed identifier, or when
1025 /// Kind == IK_UserLiteralId, the identifier suffix.
1026 const IdentifierInfo *Identifier;
1027
1028 /// When Kind == IK_OperatorFunctionId, the overloaded operator
1029 /// that we parsed.
1030 struct OFI OperatorFunctionId;
1031
1032 /// When Kind == IK_ConversionFunctionId, the type that the
1033 /// conversion function names.
1034 UnionParsedType ConversionFunctionId;
1035
1036 /// When Kind == IK_ConstructorName, the class-name of the type
1037 /// whose constructor is being referenced.
1038 UnionParsedType ConstructorName;
1039
1040 /// When Kind == IK_DestructorName, the type referred to by the
1041 /// class-name.
1042 UnionParsedType DestructorName;
1043
1044 /// When Kind == IK_DeductionGuideName, the parsed template-name.
1045 UnionParsedTemplateTy TemplateName;
1046
1047 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1048 /// the template-id annotation that contains the template name and
1049 /// template arguments.
1050 TemplateIdAnnotation *TemplateId;
1051 };
1052
1053 /// The location of the first token that describes this unqualified-id,
1054 /// which will be the location of the identifier, "operator" keyword,
1055 /// tilde (for a destructor), or the template name of a template-id.
1056 SourceLocation StartLocation;
1057
1058 /// The location of the last token that describes this unqualified-id.
1059 SourceLocation EndLocation;
1060
1061 UnqualifiedId()
1062 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1063
1064 /// Clear out this unqualified-id, setting it to default (invalid)
1065 /// state.
1066 void clear() {
1067 Kind = UnqualifiedIdKind::IK_Identifier;
1068 Identifier = nullptr;
1069 StartLocation = SourceLocation();
1070 EndLocation = SourceLocation();
1071 }
1072
1073 /// Determine whether this unqualified-id refers to a valid name.
1074 bool isValid() const { return StartLocation.isValid(); }
1075
1076 /// Determine whether this unqualified-id refers to an invalid name.
1077 bool isInvalid() const { return !isValid(); }
1078
1079 /// Determine what kind of name we have.
1080 UnqualifiedIdKind getKind() const { return Kind; }
1081
1082 /// Specify that this unqualified-id was parsed as an identifier.
1083 ///
1084 /// \param Id the parsed identifier.
1085 /// \param IdLoc the location of the parsed identifier.
1086 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1087 Kind = UnqualifiedIdKind::IK_Identifier;
1088 Identifier = Id;
1089 StartLocation = EndLocation = IdLoc;
1090 }
1091
1092 /// Specify that this unqualified-id was parsed as an
1093 /// operator-function-id.
1094 ///
1095 /// \param OperatorLoc the location of the 'operator' keyword.
1096 ///
1097 /// \param Op the overloaded operator.
1098 ///
1099 /// \param SymbolLocations the locations of the individual operator symbols
1100 /// in the operator.
1101 void setOperatorFunctionId(SourceLocation OperatorLoc,
1102 OverloadedOperatorKind Op,
1103 SourceLocation SymbolLocations[3]);
1104
1105 /// Specify that this unqualified-id was parsed as a
1106 /// conversion-function-id.
1107 ///
1108 /// \param OperatorLoc the location of the 'operator' keyword.
1109 ///
1110 /// \param Ty the type to which this conversion function is converting.
1111 ///
1112 /// \param EndLoc the location of the last token that makes up the type name.
1113 void setConversionFunctionId(SourceLocation OperatorLoc,
1114 ParsedType Ty,
1115 SourceLocation EndLoc) {
1116 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1117 StartLocation = OperatorLoc;
1118 EndLocation = EndLoc;
1119 ConversionFunctionId = Ty;
1120 }
1121
1122 /// Specific that this unqualified-id was parsed as a
1123 /// literal-operator-id.
1124 ///
1125 /// \param Id the parsed identifier.
1126 ///
1127 /// \param OpLoc the location of the 'operator' keyword.
1128 ///
1129 /// \param IdLoc the location of the identifier.
1130 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1131 SourceLocation IdLoc) {
1132 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1133 Identifier = Id;
1134 StartLocation = OpLoc;
1135 EndLocation = IdLoc;
1136 }
1137
1138 /// Specify that this unqualified-id was parsed as a constructor name.
1139 ///
1140 /// \param ClassType the class type referred to by the constructor name.
1141 ///
1142 /// \param ClassNameLoc the location of the class name.
1143 ///
1144 /// \param EndLoc the location of the last token that makes up the type name.
1145 void setConstructorName(ParsedType ClassType,
1146 SourceLocation ClassNameLoc,
1147 SourceLocation EndLoc) {
1148 Kind = UnqualifiedIdKind::IK_ConstructorName;
1149 StartLocation = ClassNameLoc;
1150 EndLocation = EndLoc;
1151 ConstructorName = ClassType;
1152 }
1153
1154 /// Specify that this unqualified-id was parsed as a
1155 /// template-id that names a constructor.
1156 ///
1157 /// \param TemplateId the template-id annotation that describes the parsed
1158 /// template-id. This UnqualifiedId instance will take ownership of the
1159 /// \p TemplateId and will free it on destruction.
1160 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1161
1162 /// Specify that this unqualified-id was parsed as a destructor name.
1163 ///
1164 /// \param TildeLoc the location of the '~' that introduces the destructor
1165 /// name.
1166 ///
1167 /// \param ClassType the name of the class referred to by the destructor name.
1168 void setDestructorName(SourceLocation TildeLoc,
1169 ParsedType ClassType,
1170 SourceLocation EndLoc) {
1171 Kind = UnqualifiedIdKind::IK_DestructorName;
1172 StartLocation = TildeLoc;
1173 EndLocation = EndLoc;
1174 DestructorName = ClassType;
1175 }
1176
1177 /// Specify that this unqualified-id was parsed as a template-id.
1178 ///
1179 /// \param TemplateId the template-id annotation that describes the parsed
1180 /// template-id. This UnqualifiedId instance will take ownership of the
1181 /// \p TemplateId and will free it on destruction.
1182 void setTemplateId(TemplateIdAnnotation *TemplateId);
1183
1184 /// Specify that this unqualified-id was parsed as a template-name for
1185 /// a deduction-guide.
1186 ///
1187 /// \param Template The parsed template-name.
1188 /// \param TemplateLoc The location of the parsed template-name.
1189 void setDeductionGuideName(ParsedTemplateTy Template,
1190 SourceLocation TemplateLoc) {
1191 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1192 TemplateName = Template;
1193 StartLocation = EndLocation = TemplateLoc;
1194 }
1195
1196 /// Specify that this unqualified-id is an implicit 'self'
1197 /// parameter.
1198 ///
1199 /// \param Id the identifier.
1200 void setImplicitSelfParam(const IdentifierInfo *Id) {
1201 Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
1202 Identifier = Id;
1203 StartLocation = EndLocation = SourceLocation();
1204 }
1205
1206 /// Return the source range that covers this unqualified-id.
1207 SourceRange getSourceRange() const LLVM_READONLY {
1208 return SourceRange(StartLocation, EndLocation);
1209 }
1210 SourceLocation getBeginLoc() const LLVM_READONLY { return StartLocation; }
1211 SourceLocation getEndLoc() const LLVM_READONLY { return EndLocation; }
1212};
1213
1214/// A set of tokens that has been cached for later parsing.
1215typedef SmallVector<Token, 4> CachedTokens;
1216
1217/// One instance of this struct is used for each type in a
1218/// declarator that is parsed.
1219///
1220/// This is intended to be a small value object.
1221struct DeclaratorChunk {
1222 DeclaratorChunk() {};
1223
1224 enum {
1225 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1226 } Kind;
1227
1228 /// Loc - The place where this type was defined.
1229 SourceLocation Loc;
1230 /// EndLoc - If valid, the place where this chunck ends.
1231 SourceLocation EndLoc;
1232
1233 SourceRange getSourceRange() const {
1234 if (EndLoc.isInvalid())
1235 return SourceRange(Loc, Loc);
1236 return SourceRange(Loc, EndLoc);
1237 }
1238
1239 ParsedAttributesView AttrList;
1240
1241 struct PointerTypeInfo {
1242 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1243 LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1244 unsigned TypeQuals : 5;
1245
1246 /// The location of the const-qualifier, if any.
1247 SourceLocation ConstQualLoc;
1248
1249 /// The location of the volatile-qualifier, if any.
1250 SourceLocation VolatileQualLoc;
1251
1252 /// The location of the restrict-qualifier, if any.
1253 SourceLocation RestrictQualLoc;
1254
1255 /// The location of the _Atomic-qualifier, if any.
1256 SourceLocation AtomicQualLoc;
1257
1258 /// The location of the __unaligned-qualifier, if any.
1259 SourceLocation UnalignedQualLoc;
1260
1261 void destroy() {
1262 }
1263 };
1264
1265 struct ReferenceTypeInfo {
1266 /// The type qualifier: restrict. [GNU] C++ extension
1267 bool HasRestrict : 1;
1268 /// True if this is an lvalue reference, false if it's an rvalue reference.
1269 bool LValueRef : 1;
1270 void destroy() {
1271 }
1272 };
1273
1274 struct ArrayTypeInfo {
1275 /// The type qualifiers for the array:
1276 /// const/volatile/restrict/__unaligned/_Atomic.
1277 LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1278 unsigned TypeQuals : 5;
1279
1280 /// True if this dimension included the 'static' keyword.
1281 LLVM_PREFERRED_TYPE(bool)
1282 unsigned hasStatic : 1;
1283
1284 /// True if this dimension was [*]. In this case, NumElts is null.
1285 LLVM_PREFERRED_TYPE(bool)
1286 unsigned isStar : 1;
1287
1288 /// This is the size of the array, or null if [] or [*] was specified.
1289 /// Since the parser is multi-purpose, and we don't want to impose a root
1290 /// expression class on all clients, NumElts is untyped.
1291 Expr *NumElts;
1292
1293 void destroy() {}
1294 };
1295
1296 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1297 /// declarator is parsed. There are two interesting styles of parameters
1298 /// here:
1299 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1300 /// lists will have information about the identifier, but no type information.
1301 /// Parameter type lists will have type info (if the actions module provides
1302 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1303 struct ParamInfo {
1304 const IdentifierInfo *Ident;
1305 SourceLocation IdentLoc;
1306 Decl *Param;
1307
1308 /// DefaultArgTokens - When the parameter's default argument
1309 /// cannot be parsed immediately (because it occurs within the
1310 /// declaration of a member function), it will be stored here as a
1311 /// sequence of tokens to be parsed once the class definition is
1312 /// complete. Non-NULL indicates that there is a default argument.
1313 std::unique_ptr<CachedTokens> DefaultArgTokens;
1314
1315 ParamInfo() = default;
1316 ParamInfo(const IdentifierInfo *ident, SourceLocation iloc, Decl *param,
1317 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1318 : Ident(ident), IdentLoc(iloc), Param(param),
1319 DefaultArgTokens(std::move(DefArgTokens)) {}
1320 };
1321
1322 struct TypeAndRange {
1323 ParsedType Ty;
1324 SourceRange Range;
1325 };
1326
1327 struct FunctionTypeInfo {
1328 /// hasPrototype - This is true if the function had at least one typed
1329 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1330 /// and is treated as a K&R-style function.
1331 LLVM_PREFERRED_TYPE(bool)
1332 unsigned hasPrototype : 1;
1333
1334 /// isVariadic - If this function has a prototype, and if that
1335 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1336 /// contains the location of the ellipsis.
1337 LLVM_PREFERRED_TYPE(bool)
1338 unsigned isVariadic : 1;
1339
1340 /// Can this declaration be a constructor-style initializer?
1341 LLVM_PREFERRED_TYPE(bool)
1342 unsigned isAmbiguous : 1;
1343
1344 /// Whether the ref-qualifier (if any) is an lvalue reference.
1345 /// Otherwise, it's an rvalue reference.
1346 LLVM_PREFERRED_TYPE(bool)
1347 unsigned RefQualifierIsLValueRef : 1;
1348
1349 /// ExceptionSpecType - An ExceptionSpecificationType value.
1350 LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
1351 unsigned ExceptionSpecType : 4;
1352
1353 /// DeleteParams - If this is true, we need to delete[] Params.
1354 LLVM_PREFERRED_TYPE(bool)
1355 unsigned DeleteParams : 1;
1356
1357 /// HasTrailingReturnType - If this is true, a trailing return type was
1358 /// specified.
1359 LLVM_PREFERRED_TYPE(bool)
1360 unsigned HasTrailingReturnType : 1;
1361
1362 /// The location of the left parenthesis in the source.
1363 SourceLocation LParenLoc;
1364
1365 /// When isVariadic is true, the location of the ellipsis in the source.
1366 SourceLocation EllipsisLoc;
1367
1368 /// The location of the right parenthesis in the source.
1369 SourceLocation RParenLoc;
1370
1371 /// NumParams - This is the number of formal parameters specified by the
1372 /// declarator.
1373 unsigned NumParams;
1374
1375 /// NumExceptionsOrDecls - This is the number of types in the
1376 /// dynamic-exception-decl, if the function has one. In C, this is the
1377 /// number of declarations in the function prototype.
1378 unsigned NumExceptionsOrDecls;
1379
1380 /// The location of the ref-qualifier, if any.
1381 ///
1382 /// If this is an invalid location, there is no ref-qualifier.
1383 SourceLocation RefQualifierLoc;
1384
1385 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1386 /// any.
1387 SourceLocation MutableLoc;
1388
1389 /// The beginning location of the exception specification, if any.
1390 SourceLocation ExceptionSpecLocBeg;
1391
1392 /// The end location of the exception specification, if any.
1393 SourceLocation ExceptionSpecLocEnd;
1394
1395 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1396 /// describe the parameters specified by this function declarator. null if
1397 /// there are no parameters specified.
1398 ParamInfo *Params;
1399
1400 /// DeclSpec for the function with the qualifier related info.
1401 DeclSpec *MethodQualifiers;
1402
1403 /// AttributeFactory for the MethodQualifiers.
1404 AttributeFactory *QualAttrFactory;
1405
1406 union {
1407 /// Pointer to a new[]'d array of TypeAndRange objects that
1408 /// contain the types in the function's dynamic exception specification
1409 /// and their locations, if there is one.
1410 TypeAndRange *Exceptions;
1411
1412 /// Pointer to the expression in the noexcept-specifier of this
1413 /// function, if it has one.
1414 Expr *NoexceptExpr;
1415
1416 /// Pointer to the cached tokens for an exception-specification
1417 /// that has not yet been parsed.
1418 CachedTokens *ExceptionSpecTokens;
1419
1420 /// Pointer to a new[]'d array of declarations that need to be available
1421 /// for lookup inside the function body, if one exists. Does not exist in
1422 /// C++.
1423 NamedDecl **DeclsInPrototype;
1424 };
1425
1426 /// If HasTrailingReturnType is true, this is the trailing return
1427 /// type specified.
1428 UnionParsedType TrailingReturnType;
1429
1430 /// If HasTrailingReturnType is true, this is the location of the trailing
1431 /// return type.
1432 SourceLocation TrailingReturnTypeLoc;
1433
1434 /// Reset the parameter list to having zero parameters.
1435 ///
1436 /// This is used in various places for error recovery.
1437 void freeParams() {
1438 for (unsigned I = 0; I < NumParams; ++I)
1439 Params[I].DefaultArgTokens.reset();
1440 if (DeleteParams) {
1441 delete[] Params;
1442 DeleteParams = false;
1443 }
1444 NumParams = 0;
1445 }
1446
1447 void destroy() {
1448 freeParams();
1449 delete QualAttrFactory;
1450 delete MethodQualifiers;
1451 switch (getExceptionSpecType()) {
1452 default:
1453 break;
1454 case EST_Dynamic:
1455 delete[] Exceptions;
1456 break;
1457 case EST_Unparsed:
1458 delete ExceptionSpecTokens;
1459 break;
1460 case EST_None:
1461 if (NumExceptionsOrDecls != 0)
1462 delete[] DeclsInPrototype;
1463 break;
1464 }
1465 }
1466
1467 DeclSpec &getOrCreateMethodQualifiers() {
1468 if (!MethodQualifiers) {
1469 QualAttrFactory = new AttributeFactory();
1470 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1471 }
1472 return *MethodQualifiers;
1473 }
1474
1475 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1476 /// like "void foo(a,b,c)". In a function definition, this will be followed
1477 /// by the parameter type definitions.
1478 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1479
1480 SourceLocation getLParenLoc() const { return LParenLoc; }
1481
1482 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1483
1484 SourceLocation getRParenLoc() const { return RParenLoc; }
1485
1486 SourceLocation getExceptionSpecLocBeg() const {
1487 return ExceptionSpecLocBeg;
1488 }
1489
1490 SourceLocation getExceptionSpecLocEnd() const {
1491 return ExceptionSpecLocEnd;
1492 }
1493
1494 SourceRange getExceptionSpecRange() const {
1495 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1496 }
1497
1498 /// Retrieve the location of the ref-qualifier, if any.
1499 SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
1500
1501 /// Retrieve the location of the 'const' qualifier.
1502 SourceLocation getConstQualifierLoc() const {
1503 assert(MethodQualifiers);
1504 return MethodQualifiers->getConstSpecLoc();
1505 }
1506
1507 /// Retrieve the location of the 'volatile' qualifier.
1508 SourceLocation getVolatileQualifierLoc() const {
1509 assert(MethodQualifiers);
1510 return MethodQualifiers->getVolatileSpecLoc();
1511 }
1512
1513 /// Retrieve the location of the 'restrict' qualifier.
1514 SourceLocation getRestrictQualifierLoc() const {
1515 assert(MethodQualifiers);
1516 return MethodQualifiers->getRestrictSpecLoc();
1517 }
1518
1519 /// Retrieve the location of the 'mutable' qualifier, if any.
1520 SourceLocation getMutableLoc() const { return MutableLoc; }
1521
1522 /// Determine whether this function declaration contains a
1523 /// ref-qualifier.
1524 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1525
1526 /// Determine whether this lambda-declarator contains a 'mutable'
1527 /// qualifier.
1528 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1529
1530 /// Determine whether this method has qualifiers.
1531 bool hasMethodTypeQualifiers() const {
1532 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1533 MethodQualifiers->getAttributes().size());
1534 }
1535
1536 /// Get the type of exception specification this function has.
1537 ExceptionSpecificationType getExceptionSpecType() const {
1538 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1539 }
1540
1541 /// Get the number of dynamic exception specifications.
1542 unsigned getNumExceptions() const {
1543 assert(ExceptionSpecType != EST_None);
1544 return NumExceptionsOrDecls;
1545 }
1546
1547 /// Get the non-parameter decls defined within this function
1548 /// prototype. Typically these are tag declarations.
1549 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1550 assert(ExceptionSpecType == EST_None);
1551 return llvm::ArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1552 }
1553
1554 /// Determine whether this function declarator had a
1555 /// trailing-return-type.
1556 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1557
1558 /// Get the trailing-return-type for this function declarator.
1559 ParsedType getTrailingReturnType() const {
1560 assert(HasTrailingReturnType);
1561 return TrailingReturnType;
1562 }
1563
1564 /// Get the trailing-return-type location for this function declarator.
1565 SourceLocation getTrailingReturnTypeLoc() const {
1566 assert(HasTrailingReturnType);
1567 return TrailingReturnTypeLoc;
1568 }
1569 };
1570
1571 struct BlockPointerTypeInfo {
1572 /// For now, sema will catch these as invalid.
1573 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1574 LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1575 unsigned TypeQuals : 5;
1576
1577 void destroy() {
1578 }
1579 };
1580
1581 struct MemberPointerTypeInfo {
1582 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1583 LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1584 unsigned TypeQuals : 5;
1585 /// Location of the '*' token.
1586 SourceLocation StarLoc;
1587 // CXXScopeSpec has a constructor, so it can't be a direct member.
1588 // So we need some pointer-aligned storage and a bit of trickery.
1589 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1590 CXXScopeSpec &Scope() {
1591 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1592 }
1593 const CXXScopeSpec &Scope() const {
1594 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1595 }
1596 void destroy() {
1597 Scope().~CXXScopeSpec();
1598 }
1599 };
1600
1601 struct PipeTypeInfo {
1602 /// The access writes.
1603 unsigned AccessWrites : 3;
1604
1605 void destroy() {}
1606 };
1607
1608 union {
1609 PointerTypeInfo Ptr;
1610 ReferenceTypeInfo Ref;
1611 ArrayTypeInfo Arr;
1612 FunctionTypeInfo Fun;
1613 BlockPointerTypeInfo Cls;
1614 MemberPointerTypeInfo Mem;
1615 PipeTypeInfo PipeInfo;
1616 };
1617
1618 void destroy() {
1619 switch (Kind) {
1620 case DeclaratorChunk::Function: return Fun.destroy();
1621 case DeclaratorChunk::Pointer: return Ptr.destroy();
1622 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1623 case DeclaratorChunk::Reference: return Ref.destroy();
1624 case DeclaratorChunk::Array: return Arr.destroy();
1625 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1626 case DeclaratorChunk::Paren: return;
1627 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1628 }
1629 }
1630
1631 /// If there are attributes applied to this declaratorchunk, return
1632 /// them.
1633 const ParsedAttributesView &getAttrs() const { return AttrList; }
1634 ParsedAttributesView &getAttrs() { return AttrList; }
1635
1636 /// Return a DeclaratorChunk for a pointer.
1637 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1638 SourceLocation ConstQualLoc,
1639 SourceLocation VolatileQualLoc,
1640 SourceLocation RestrictQualLoc,
1641 SourceLocation AtomicQualLoc,
1642 SourceLocation UnalignedQualLoc) {
1643 DeclaratorChunk I;
1644 I.Kind = Pointer;
1645 I.Loc = Loc;
1646 new (&I.Ptr) PointerTypeInfo;
1647 I.Ptr.TypeQuals = TypeQuals;
1648 I.Ptr.ConstQualLoc = ConstQualLoc;
1649 I.Ptr.VolatileQualLoc = VolatileQualLoc;
1650 I.Ptr.RestrictQualLoc = RestrictQualLoc;
1651 I.Ptr.AtomicQualLoc = AtomicQualLoc;
1652 I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
1653 return I;
1654 }
1655
1656 /// Return a DeclaratorChunk for a reference.
1657 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1658 bool lvalue) {
1659 DeclaratorChunk I;
1660 I.Kind = Reference;
1661 I.Loc = Loc;
1662 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1663 I.Ref.LValueRef = lvalue;
1664 return I;
1665 }
1666
1667 /// Return a DeclaratorChunk for an array.
1668 static DeclaratorChunk getArray(unsigned TypeQuals,
1669 bool isStatic, bool isStar, Expr *NumElts,
1670 SourceLocation LBLoc, SourceLocation RBLoc) {
1671 DeclaratorChunk I;
1672 I.Kind = Array;
1673 I.Loc = LBLoc;
1674 I.EndLoc = RBLoc;
1675 I.Arr.TypeQuals = TypeQuals;
1676 I.Arr.hasStatic = isStatic;
1677 I.Arr.isStar = isStar;
1678 I.Arr.NumElts = NumElts;
1679 return I;
1680 }
1681
1682 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1683 /// "TheDeclarator" is the declarator that this will be added to.
1684 static DeclaratorChunk getFunction(bool HasProto,
1685 bool IsAmbiguous,
1686 SourceLocation LParenLoc,
1687 ParamInfo *Params, unsigned NumParams,
1688 SourceLocation EllipsisLoc,
1689 SourceLocation RParenLoc,
1690 bool RefQualifierIsLvalueRef,
1691 SourceLocation RefQualifierLoc,
1692 SourceLocation MutableLoc,
1693 ExceptionSpecificationType ESpecType,
1694 SourceRange ESpecRange,
1695 ParsedType *Exceptions,
1696 SourceRange *ExceptionRanges,
1697 unsigned NumExceptions,
1698 Expr *NoexceptExpr,
1699 CachedTokens *ExceptionSpecTokens,
1700 ArrayRef<NamedDecl *> DeclsInPrototype,
1701 SourceLocation LocalRangeBegin,
1702 SourceLocation LocalRangeEnd,
1703 Declarator &TheDeclarator,
1704 TypeResult TrailingReturnType =
1705 TypeResult(),
1706 SourceLocation TrailingReturnTypeLoc =
1707 SourceLocation(),
1708 DeclSpec *MethodQualifiers = nullptr);
1709
1710 /// Return a DeclaratorChunk for a block.
1711 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1712 SourceLocation Loc) {
1713 DeclaratorChunk I;
1714 I.Kind = BlockPointer;
1715 I.Loc = Loc;
1716 I.Cls.TypeQuals = TypeQuals;
1717 return I;
1718 }
1719
1720 /// Return a DeclaratorChunk for a block.
1721 static DeclaratorChunk getPipe(unsigned TypeQuals,
1722 SourceLocation Loc) {
1723 DeclaratorChunk I;
1724 I.Kind = Pipe;
1725 I.Loc = Loc;
1726 I.Cls.TypeQuals = TypeQuals;
1727 return I;
1728 }
1729
1730 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1731 unsigned TypeQuals,
1732 SourceLocation StarLoc,
1733 SourceLocation EndLoc) {
1734 DeclaratorChunk I;
1735 I.Kind = MemberPointer;
1736 I.Loc = SS.getBeginLoc();
1737 I.EndLoc = EndLoc;
1738 new (&I.Mem) MemberPointerTypeInfo;
1739 I.Mem.StarLoc = StarLoc;
1740 I.Mem.TypeQuals = TypeQuals;
1741 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1742 return I;
1743 }
1744
1745 /// Return a DeclaratorChunk for a paren.
1746 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1747 SourceLocation RParenLoc) {
1748 DeclaratorChunk I;
1749 I.Kind = Paren;
1750 I.Loc = LParenLoc;
1751 I.EndLoc = RParenLoc;
1752 return I;
1753 }
1754
1755 bool isParen() const {
1756 return Kind == Paren;
1757 }
1758};
1759
1760/// A parsed C++17 decomposition declarator of the form
1761/// '[' identifier-list ']'
1762class DecompositionDeclarator {
1763public:
1764 struct Binding {
1765 IdentifierInfo *Name;
1766 SourceLocation NameLoc;
1767 std::optional<ParsedAttributes> Attrs;
1768 SourceLocation EllipsisLoc;
1769 };
1770
1771private:
1772 /// The locations of the '[' and ']' tokens.
1773 SourceLocation LSquareLoc, RSquareLoc;
1774
1775 /// The bindings.
1776 Binding *Bindings;
1777 unsigned NumBindings : 31;
1778 LLVM_PREFERRED_TYPE(bool)
1779 unsigned DeleteBindings : 1;
1780
1781 friend class Declarator;
1782
1783public:
1784 DecompositionDeclarator()
1785 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1786 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1787 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1788 ~DecompositionDeclarator() { clear(); }
1789
1790 void clear() {
1791 LSquareLoc = RSquareLoc = SourceLocation();
1792 if (DeleteBindings)
1793 delete[] Bindings;
1794 else
1795 for (Binding &B : llvm::MutableArrayRef(Bindings, NumBindings))
1796 B.Attrs.reset();
1797 Bindings = nullptr;
1798 NumBindings = 0;
1799 DeleteBindings = false;
1800 }
1801
1802 ArrayRef<Binding> bindings() const {
1803 return llvm::ArrayRef(Bindings, NumBindings);
1804 }
1805
1806 bool isSet() const { return LSquareLoc.isValid(); }
1807
1808 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1809 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1810 SourceRange getSourceRange() const {
1811 return SourceRange(LSquareLoc, RSquareLoc);
1812 }
1813};
1814
1815/// Described the kind of function definition (if any) provided for
1816/// a function.
1817enum class FunctionDefinitionKind {
1818 Declaration,
1819 Definition,
1820 Defaulted,
1821 Deleted
1822};
1823
1824enum class DeclaratorContext {
1825 File, // File scope declaration.
1826 Prototype, // Within a function prototype.
1827 ObjCResult, // An ObjC method result type.
1828 ObjCParameter, // An ObjC method parameter type.
1829 KNRTypeList, // K&R type definition list for formals.
1830 TypeName, // Abstract declarator for types.
1831 FunctionalCast, // Type in a C++ functional cast expression.
1832 Member, // Struct/Union field.
1833 Block, // Declaration within a block in a function.
1834 ForInit, // Declaration within first part of a for loop.
1835 SelectionInit, // Declaration within optional init stmt of if/switch.
1836 Condition, // Condition declaration in a C++ if/switch/while/for.
1837 TemplateParam, // Within a template parameter list.
1838 CXXNew, // C++ new-expression.
1839 CXXCatch, // C++ catch exception-declaration
1840 ObjCCatch, // Objective-C catch exception-declaration
1841 BlockLiteral, // Block literal declarator.
1842 LambdaExpr, // Lambda-expression declarator.
1843 LambdaExprParameter, // Lambda-expression parameter declarator.
1844 ConversionId, // C++ conversion-type-id.
1845 TrailingReturn, // C++11 trailing-type-specifier.
1846 TrailingReturnVar, // C++11 trailing-type-specifier for variable.
1847 TemplateArg, // Any template argument (in template argument list).
1848 TemplateTypeArg, // Template type argument (in default argument).
1849 AliasDecl, // C++11 alias-declaration.
1850 AliasTemplate, // C++11 alias-declaration template.
1851 RequiresExpr, // C++2a requires-expression.
1852 Association // C11 _Generic selection expression association.
1853};
1854
1855// Describes whether the current context is a context where an implicit
1856// typename is allowed (C++2a [temp.res]p5]).
1857enum class ImplicitTypenameContext {
1858 No,
1859 Yes,
1860};
1861
1862/// Information about one declarator, including the parsed type
1863/// information and the identifier.
1864///
1865/// When the declarator is fully formed, this is turned into the appropriate
1866/// Decl object.
1867///
1868/// Declarators come in two types: normal declarators and abstract declarators.
1869/// Abstract declarators are used when parsing types, and don't have an
1870/// identifier. Normal declarators do have ID's.
1871///
1872/// Instances of this class should be a transient object that lives on the
1873/// stack, not objects that are allocated in large quantities on the heap.
1874class Declarator {
1875
1876private:
1877 const DeclSpec &DS;
1878 CXXScopeSpec SS;
1879 UnqualifiedId Name;
1880 SourceRange Range;
1881
1882 /// Where we are parsing this declarator.
1883 DeclaratorContext Context;
1884
1885 /// The C++17 structured binding, if any. This is an alternative to a Name.
1886 DecompositionDeclarator BindingGroup;
1887
1888 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1889 /// parsed. This is pushed from the identifier out, which means that element
1890 /// #0 will be the most closely bound to the identifier, and
1891 /// DeclTypeInfo.back() will be the least closely bound.
1892 SmallVector<DeclaratorChunk, 4> DeclTypeInfo;
1893
1894 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1895 LLVM_PREFERRED_TYPE(bool)
1896 unsigned InvalidType : 1;
1897
1898 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1899 LLVM_PREFERRED_TYPE(bool)
1900 unsigned GroupingParens : 1;
1901
1902 /// FunctionDefinition - Is this Declarator for a function or member
1903 /// definition and, if so, what kind?
1904 ///
1905 /// Actually a FunctionDefinitionKind.
1906 LLVM_PREFERRED_TYPE(FunctionDefinitionKind)
1907 unsigned FunctionDefinition : 2;
1908
1909 /// Is this Declarator a redeclaration?
1910 LLVM_PREFERRED_TYPE(bool)
1911 unsigned Redeclaration : 1;
1912
1913 /// true if the declaration is preceded by \c __extension__.
1914 LLVM_PREFERRED_TYPE(bool)
1915 unsigned Extension : 1;
1916
1917 /// Indicates whether this is an Objective-C instance variable.
1918 LLVM_PREFERRED_TYPE(bool)
1919 unsigned ObjCIvar : 1;
1920
1921 /// Indicates whether this is an Objective-C 'weak' property.
1922 LLVM_PREFERRED_TYPE(bool)
1923 unsigned ObjCWeakProperty : 1;
1924
1925 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1926 LLVM_PREFERRED_TYPE(bool)
1927 unsigned InlineStorageUsed : 1;
1928
1929 /// Indicates whether this declarator has an initializer.
1930 LLVM_PREFERRED_TYPE(bool)
1931 unsigned HasInitializer : 1;
1932
1933 /// Attributes attached to the declarator.
1934 ParsedAttributes Attrs;
1935
1936 /// Attributes attached to the declaration. See also documentation for the
1937 /// corresponding constructor parameter.
1938 const ParsedAttributesView &DeclarationAttrs;
1939
1940 /// The asm label, if specified.
1941 Expr *AsmLabel;
1942
1943 /// \brief The constraint-expression specified by the trailing
1944 /// requires-clause, or null if no such clause was specified.
1945 Expr *TrailingRequiresClause;
1946
1947 /// If this declarator declares a template, its template parameter lists.
1948 ArrayRef<TemplateParameterList *> TemplateParameterLists;
1949
1950 /// If the declarator declares an abbreviated function template, the innermost
1951 /// template parameter list containing the invented and explicit template
1952 /// parameters (if any).
1953 TemplateParameterList *InventedTemplateParameterList;
1954
1955#ifndef _MSC_VER
1956 union {
1957#endif
1958 /// InlineParams - This is a local array used for the first function decl
1959 /// chunk to avoid going to the heap for the common case when we have one
1960 /// function chunk in the declarator.
1961 DeclaratorChunk::ParamInfo InlineParams[16];
1962 DecompositionDeclarator::Binding InlineBindings[16];
1963#ifndef _MSC_VER
1964 };
1965#endif
1966
1967 /// If this is the second or subsequent declarator in this declaration,
1968 /// the location of the comma before this declarator.
1969 SourceLocation CommaLoc;
1970
1971 /// If provided, the source location of the ellipsis used to describe
1972 /// this declarator as a parameter pack.
1973 SourceLocation EllipsisLoc;
1974
1975 Expr *PackIndexingExpr;
1976
1977 friend struct DeclaratorChunk;
1978
1979public:
1980 /// `DS` and `DeclarationAttrs` must outlive the `Declarator`. In particular,
1981 /// take care not to pass temporary objects for these parameters.
1982 ///
1983 /// `DeclarationAttrs` contains [[]] attributes from the
1984 /// attribute-specifier-seq at the beginning of a declaration, which appertain
1985 /// to the declared entity itself. Attributes with other syntax (e.g. GNU)
1986 /// should not be placed in this attribute list; if they occur at the
1987 /// beginning of a declaration, they apply to the `DeclSpec` and should be
1988 /// attached to that instead.
1989 ///
1990 /// Here is an example of an attribute associated with a declaration:
1991 ///
1992 /// [[deprecated]] int x, y;
1993 ///
1994 /// This attribute appertains to all of the entities declared in the
1995 /// declaration, i.e. `x` and `y` in this case.
1996 Declarator(const DeclSpec &DS, const ParsedAttributesView &DeclarationAttrs,
1997 DeclaratorContext C)
1998 : DS(DS), Range(DS.getSourceRange()), Context(C),
1999 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
2000 GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
2001 FunctionDefinitionKind::Declaration)),
2002 Redeclaration(false), Extension(false), ObjCIvar(false),
2003 ObjCWeakProperty(false), InlineStorageUsed(false),
2004 HasInitializer(false), Attrs(DS.getAttributePool().getFactory()),
2005 DeclarationAttrs(DeclarationAttrs), AsmLabel(nullptr),
2006 TrailingRequiresClause(nullptr),
2007 InventedTemplateParameterList(nullptr) {
2008 assert(llvm::all_of(DeclarationAttrs,
2009 [](const ParsedAttr &AL) {
2010 return (AL.isStandardAttributeSyntax() ||
2011 AL.isRegularKeywordAttribute());
2012 }) &&
2013 "DeclarationAttrs may only contain [[]] and keyword attributes");
2014 }
2015
2016 ~Declarator() {
2017 clear();
2018 }
2019 /// getDeclSpec - Return the declaration-specifier that this declarator was
2020 /// declared with.
2021 const DeclSpec &getDeclSpec() const { return DS; }
2022
2023 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
2024 /// should be used with extreme care: declspecs can often be shared between
2025 /// multiple declarators, so mutating the DeclSpec affects all of the
2026 /// Declarators. This should only be done when the declspec is known to not
2027 /// be shared or when in error recovery etc.
2028 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
2029
2030 AttributePool &getAttributePool() const {
2031 return Attrs.getPool();
2032 }
2033
2034 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
2035 /// nested-name-specifier) that is part of the declarator-id.
2036 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
2037 CXXScopeSpec &getCXXScopeSpec() { return SS; }
2038
2039 /// Retrieve the name specified by this declarator.
2040 UnqualifiedId &getName() { return Name; }
2041
2042 const DecompositionDeclarator &getDecompositionDeclarator() const {
2043 return BindingGroup;
2044 }
2045
2046 DeclaratorContext getContext() const { return Context; }
2047
2048 bool isPrototypeContext() const {
2049 return (Context == DeclaratorContext::Prototype ||
2050 Context == DeclaratorContext::ObjCParameter ||
2051 Context == DeclaratorContext::ObjCResult ||
2052 Context == DeclaratorContext::LambdaExprParameter);
2053 }
2054
2055 /// Get the source range that spans this declarator.
2056 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2057 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2058 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2059
2060 void SetSourceRange(SourceRange R) { Range = R; }
2061 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
2062 /// invalid.
2063 void SetRangeBegin(SourceLocation Loc) {
2064 if (!Loc.isInvalid())
2065 Range.setBegin(Loc);
2066 }
2067 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
2068 void SetRangeEnd(SourceLocation Loc) {
2069 if (!Loc.isInvalid())
2070 Range.setEnd(Loc);
2071 }
2072 /// ExtendWithDeclSpec - Extend the declarator source range to include the
2073 /// given declspec, unless its location is invalid. Adopts the range start if
2074 /// the current range start is invalid.
2075 void ExtendWithDeclSpec(const DeclSpec &DS) {
2076 SourceRange SR = DS.getSourceRange();
2077 if (Range.getBegin().isInvalid())
2078 Range.setBegin(SR.getBegin());
2079 if (!SR.getEnd().isInvalid())
2080 Range.setEnd(SR.getEnd());
2081 }
2082
2083 /// Reset the contents of this Declarator.
2084 void clear() {
2085 SS.clear();
2086 Name.clear();
2087 Range = DS.getSourceRange();
2088 BindingGroup.clear();
2089
2090 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
2091 DeclTypeInfo[i].destroy();
2092 DeclTypeInfo.clear();
2093 Attrs.clear();
2094 AsmLabel = nullptr;
2095 InlineStorageUsed = false;
2096 HasInitializer = false;
2097 ObjCIvar = false;
2098 ObjCWeakProperty = false;
2099 CommaLoc = SourceLocation();
2100 EllipsisLoc = SourceLocation();
2101 PackIndexingExpr = nullptr;
2102 }
2103
2104 /// mayOmitIdentifier - Return true if the identifier is either optional or
2105 /// not allowed. This is true for typenames, prototypes, and template
2106 /// parameter lists.
2107 bool mayOmitIdentifier() const {
2108 switch (Context) {
2109 case DeclaratorContext::File:
2110 case DeclaratorContext::KNRTypeList:
2111 case DeclaratorContext::Member:
2112 case DeclaratorContext::Block:
2113 case DeclaratorContext::ForInit:
2114 case DeclaratorContext::SelectionInit:
2115 case DeclaratorContext::Condition:
2116 return false;
2117
2118 case DeclaratorContext::TypeName:
2119 case DeclaratorContext::FunctionalCast:
2120 case DeclaratorContext::AliasDecl:
2121 case DeclaratorContext::AliasTemplate:
2122 case DeclaratorContext::Prototype:
2123 case DeclaratorContext::LambdaExprParameter:
2124 case DeclaratorContext::ObjCParameter:
2125 case DeclaratorContext::ObjCResult:
2126 case DeclaratorContext::TemplateParam:
2127 case DeclaratorContext::CXXNew:
2128 case DeclaratorContext::CXXCatch:
2129 case DeclaratorContext::ObjCCatch:
2130 case DeclaratorContext::BlockLiteral:
2131 case DeclaratorContext::LambdaExpr:
2132 case DeclaratorContext::ConversionId:
2133 case DeclaratorContext::TemplateArg:
2134 case DeclaratorContext::TemplateTypeArg:
2135 case DeclaratorContext::TrailingReturn:
2136 case DeclaratorContext::TrailingReturnVar:
2137 case DeclaratorContext::RequiresExpr:
2138 case DeclaratorContext::Association:
2139 return true;
2140 }
2141 llvm_unreachable("unknown context kind!");
2142 }
2143
2144 /// mayHaveIdentifier - Return true if the identifier is either optional or
2145 /// required. This is true for normal declarators and prototypes, but not
2146 /// typenames.
2147 bool mayHaveIdentifier() const {
2148 switch (Context) {
2149 case DeclaratorContext::File:
2150 case DeclaratorContext::KNRTypeList:
2151 case DeclaratorContext::Member:
2152 case DeclaratorContext::Block:
2153 case DeclaratorContext::ForInit:
2154 case DeclaratorContext::SelectionInit:
2155 case DeclaratorContext::Condition:
2156 case DeclaratorContext::Prototype:
2157 case DeclaratorContext::LambdaExprParameter:
2158 case DeclaratorContext::TemplateParam:
2159 case DeclaratorContext::CXXCatch:
2160 case DeclaratorContext::ObjCCatch:
2161 case DeclaratorContext::RequiresExpr:
2162 return true;
2163
2164 case DeclaratorContext::TypeName:
2165 case DeclaratorContext::FunctionalCast:
2166 case DeclaratorContext::CXXNew:
2167 case DeclaratorContext::AliasDecl:
2168 case DeclaratorContext::AliasTemplate:
2169 case DeclaratorContext::ObjCParameter:
2170 case DeclaratorContext::ObjCResult:
2171 case DeclaratorContext::BlockLiteral:
2172 case DeclaratorContext::LambdaExpr:
2173 case DeclaratorContext::ConversionId:
2174 case DeclaratorContext::TemplateArg:
2175 case DeclaratorContext::TemplateTypeArg:
2176 case DeclaratorContext::TrailingReturn:
2177 case DeclaratorContext::TrailingReturnVar:
2178 case DeclaratorContext::Association:
2179 return false;
2180 }
2181 llvm_unreachable("unknown context kind!");
2182 }
2183
2184 /// Return true if the context permits a C++17 decomposition declarator.
2185 bool mayHaveDecompositionDeclarator() const {
2186 switch (Context) {
2187 case DeclaratorContext::File:
2188 // FIXME: It's not clear that the proposal meant to allow file-scope
2189 // structured bindings, but it does.
2190 case DeclaratorContext::Block:
2191 case DeclaratorContext::ForInit:
2192 case DeclaratorContext::SelectionInit:
2193 case DeclaratorContext::Condition:
2194 return true;
2195
2196 case DeclaratorContext::Member:
2197 case DeclaratorContext::Prototype:
2198 case DeclaratorContext::TemplateParam:
2199 case DeclaratorContext::RequiresExpr:
2200 // Maybe one day...
2201 return false;
2202
2203 // These contexts don't allow any kind of non-abstract declarator.
2204 case DeclaratorContext::KNRTypeList:
2205 case DeclaratorContext::TypeName:
2206 case DeclaratorContext::FunctionalCast:
2207 case DeclaratorContext::AliasDecl:
2208 case DeclaratorContext::AliasTemplate:
2209 case DeclaratorContext::LambdaExprParameter:
2210 case DeclaratorContext::ObjCParameter:
2211 case DeclaratorContext::ObjCResult:
2212 case DeclaratorContext::CXXNew:
2213 case DeclaratorContext::CXXCatch:
2214 case DeclaratorContext::ObjCCatch:
2215 case DeclaratorContext::BlockLiteral:
2216 case DeclaratorContext::LambdaExpr:
2217 case DeclaratorContext::ConversionId:
2218 case DeclaratorContext::TemplateArg:
2219 case DeclaratorContext::TemplateTypeArg:
2220 case DeclaratorContext::TrailingReturn:
2221 case DeclaratorContext::TrailingReturnVar:
2222 case DeclaratorContext::Association:
2223 return false;
2224 }
2225 llvm_unreachable("unknown context kind!");
2226 }
2227
2228 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2229 /// followed by a C++ direct initializer, e.g. "int x(1);".
2230 bool mayBeFollowedByCXXDirectInit() const {
2231 if (hasGroupingParens()) return false;
2232
2233 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2234 return false;
2235
2236 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2237 Context != DeclaratorContext::File)
2238 return false;
2239
2240 // Special names can't have direct initializers.
2241 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2242 return false;
2243
2244 switch (Context) {
2245 case DeclaratorContext::File:
2246 case DeclaratorContext::Block:
2247 case DeclaratorContext::ForInit:
2248 case DeclaratorContext::SelectionInit:
2249 case DeclaratorContext::TrailingReturnVar:
2250 return true;
2251
2252 case DeclaratorContext::Condition:
2253 // This may not be followed by a direct initializer, but it can't be a
2254 // function declaration either, and we'd prefer to perform a tentative
2255 // parse in order to produce the right diagnostic.
2256 return true;
2257
2258 case DeclaratorContext::KNRTypeList:
2259 case DeclaratorContext::Member:
2260 case DeclaratorContext::Prototype:
2261 case DeclaratorContext::LambdaExprParameter:
2262 case DeclaratorContext::ObjCParameter:
2263 case DeclaratorContext::ObjCResult:
2264 case DeclaratorContext::TemplateParam:
2265 case DeclaratorContext::CXXCatch:
2266 case DeclaratorContext::ObjCCatch:
2267 case DeclaratorContext::TypeName:
2268 case DeclaratorContext::FunctionalCast: // FIXME
2269 case DeclaratorContext::CXXNew:
2270 case DeclaratorContext::AliasDecl:
2271 case DeclaratorContext::AliasTemplate:
2272 case DeclaratorContext::BlockLiteral:
2273 case DeclaratorContext::LambdaExpr:
2274 case DeclaratorContext::ConversionId:
2275 case DeclaratorContext::TemplateArg:
2276 case DeclaratorContext::TemplateTypeArg:
2277 case DeclaratorContext::TrailingReturn:
2278 case DeclaratorContext::RequiresExpr:
2279 case DeclaratorContext::Association:
2280 return false;
2281 }
2282 llvm_unreachable("unknown context kind!");
2283 }
2284
2285 /// isPastIdentifier - Return true if we have parsed beyond the point where
2286 /// the name would appear. (This may happen even if we haven't actually parsed
2287 /// a name, perhaps because this context doesn't require one.)
2288 bool isPastIdentifier() const { return Name.isValid(); }
2289
2290 /// hasName - Whether this declarator has a name, which might be an
2291 /// identifier (accessible via getIdentifier()) or some kind of
2292 /// special C++ name (constructor, destructor, etc.), or a structured
2293 /// binding (which is not exactly a name, but occupies the same position).
2294 bool hasName() const {
2295 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2296 Name.Identifier || isDecompositionDeclarator();
2297 }
2298
2299 /// Return whether this declarator is a decomposition declarator.
2300 bool isDecompositionDeclarator() const {
2301 return BindingGroup.isSet();
2302 }
2303
2304 const IdentifierInfo *getIdentifier() const {
2305 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2306 return Name.Identifier;
2307
2308 return nullptr;
2309 }
2310 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2311
2312 /// Set the name of this declarator to be the given identifier.
2313 void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
2314 Name.setIdentifier(Id, IdLoc);
2315 }
2316
2317 /// Set the decomposition bindings for this declarator.
2318 void setDecompositionBindings(
2319 SourceLocation LSquareLoc,
2320 MutableArrayRef<DecompositionDeclarator::Binding> Bindings,
2321 SourceLocation RSquareLoc);
2322
2323 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2324 /// EndLoc, which should be the last token of the chunk.
2325 /// This function takes attrs by R-Value reference because it takes ownership
2326 /// of those attributes from the parameter.
2327 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2328 SourceLocation EndLoc) {
2329 DeclTypeInfo.push_back(Elt: TI);
2330 DeclTypeInfo.back().getAttrs().prepend(B: attrs.begin(), E: attrs.end());
2331 getAttributePool().takeAllFrom(pool&: attrs.getPool());
2332
2333 if (!EndLoc.isInvalid())
2334 SetRangeEnd(EndLoc);
2335 }
2336
2337 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2338 /// EndLoc, which should be the last token of the chunk. This overload is for
2339 /// copying a 'chunk' from another declarator, so it takes the pool that the
2340 /// other Declarator owns so that it can 'take' the attributes from it.
2341 void AddTypeInfo(const DeclaratorChunk &TI, AttributePool &OtherPool,
2342 SourceLocation EndLoc) {
2343 DeclTypeInfo.push_back(Elt: TI);
2344 getAttributePool().takeFrom(List&: DeclTypeInfo.back().getAttrs(), Pool&: OtherPool);
2345
2346 if (!EndLoc.isInvalid())
2347 SetRangeEnd(EndLoc);
2348 }
2349
2350 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2351 /// EndLoc, which should be the last token of the chunk.
2352 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2353 DeclTypeInfo.push_back(Elt: TI);
2354
2355 assert(TI.AttrList.empty() &&
2356 "Cannot add a declarator chunk with attributes with this overload");
2357
2358 if (!EndLoc.isInvalid())
2359 SetRangeEnd(EndLoc);
2360 }
2361
2362 /// Add a new innermost chunk to this declarator.
2363 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2364 DeclTypeInfo.insert(I: DeclTypeInfo.begin(), Elt: TI);
2365 }
2366
2367 /// Return the number of types applied to this declarator.
2368 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2369
2370 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2371 /// closest to the identifier.
2372 const DeclaratorChunk &getTypeObject(unsigned i) const {
2373 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2374 return DeclTypeInfo[i];
2375 }
2376 DeclaratorChunk &getTypeObject(unsigned i) {
2377 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2378 return DeclTypeInfo[i];
2379 }
2380
2381 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2382 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2383
2384 /// Returns the range of type objects, from the identifier outwards.
2385 type_object_range type_objects() const {
2386 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2387 }
2388
2389 void DropFirstTypeObject() {
2390 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2391 DeclTypeInfo.front().destroy();
2392 DeclTypeInfo.erase(CI: DeclTypeInfo.begin());
2393 }
2394
2395 /// Return the innermost (closest to the declarator) chunk of this
2396 /// declarator that is not a parens chunk, or null if there are no
2397 /// non-parens chunks.
2398 const DeclaratorChunk *getInnermostNonParenChunk() const {
2399 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2400 if (!DeclTypeInfo[i].isParen())
2401 return &DeclTypeInfo[i];
2402 }
2403 return nullptr;
2404 }
2405
2406 /// Return the outermost (furthest from the declarator) chunk of
2407 /// this declarator that is not a parens chunk, or null if there are
2408 /// no non-parens chunks.
2409 const DeclaratorChunk *getOutermostNonParenChunk() const {
2410 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2411 if (!DeclTypeInfo[i-1].isParen())
2412 return &DeclTypeInfo[i-1];
2413 }
2414 return nullptr;
2415 }
2416
2417 /// isArrayOfUnknownBound - This method returns true if the declarator
2418 /// is a declarator for an array of unknown bound (looking through
2419 /// parentheses).
2420 bool isArrayOfUnknownBound() const {
2421 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2422 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2423 !chunk->Arr.NumElts);
2424 }
2425
2426 /// isFunctionDeclarator - This method returns true if the declarator
2427 /// is a function declarator (looking through parentheses).
2428 /// If true is returned, then the reference type parameter idx is
2429 /// assigned with the index of the declaration chunk.
2430 bool isFunctionDeclarator(unsigned& idx) const {
2431 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2432 switch (DeclTypeInfo[i].Kind) {
2433 case DeclaratorChunk::Function:
2434 idx = i;
2435 return true;
2436 case DeclaratorChunk::Paren:
2437 continue;
2438 case DeclaratorChunk::Pointer:
2439 case DeclaratorChunk::Reference:
2440 case DeclaratorChunk::Array:
2441 case DeclaratorChunk::BlockPointer:
2442 case DeclaratorChunk::MemberPointer:
2443 case DeclaratorChunk::Pipe:
2444 return false;
2445 }
2446 llvm_unreachable("Invalid type chunk");
2447 }
2448 return false;
2449 }
2450
2451 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2452 /// this method returns true if the identifier is a function declarator
2453 /// (looking through parentheses).
2454 bool isFunctionDeclarator() const {
2455 unsigned index;
2456 return isFunctionDeclarator(idx&: index);
2457 }
2458
2459 /// getFunctionTypeInfo - Retrieves the function type info object
2460 /// (looking through parentheses).
2461 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2462 assert(isFunctionDeclarator() && "Not a function declarator!");
2463 unsigned index = 0;
2464 isFunctionDeclarator(idx&: index);
2465 return DeclTypeInfo[index].Fun;
2466 }
2467
2468 /// getFunctionTypeInfo - Retrieves the function type info object
2469 /// (looking through parentheses).
2470 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2471 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2472 }
2473
2474 /// Determine whether the declaration that will be produced from
2475 /// this declaration will be a function.
2476 ///
2477 /// A declaration can declare a function even if the declarator itself
2478 /// isn't a function declarator, if the type specifier refers to a function
2479 /// type. This routine checks for both cases.
2480 bool isDeclarationOfFunction() const;
2481
2482 /// Return true if this declaration appears in a context where a
2483 /// function declarator would be a function declaration.
2484 bool isFunctionDeclarationContext() const {
2485 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2486 return false;
2487
2488 switch (Context) {
2489 case DeclaratorContext::File:
2490 case DeclaratorContext::Member:
2491 case DeclaratorContext::Block:
2492 case DeclaratorContext::ForInit:
2493 case DeclaratorContext::SelectionInit:
2494 return true;
2495
2496 case DeclaratorContext::Condition:
2497 case DeclaratorContext::KNRTypeList:
2498 case DeclaratorContext::TypeName:
2499 case DeclaratorContext::FunctionalCast:
2500 case DeclaratorContext::AliasDecl:
2501 case DeclaratorContext::AliasTemplate:
2502 case DeclaratorContext::Prototype:
2503 case DeclaratorContext::LambdaExprParameter:
2504 case DeclaratorContext::ObjCParameter:
2505 case DeclaratorContext::ObjCResult:
2506 case DeclaratorContext::TemplateParam:
2507 case DeclaratorContext::CXXNew:
2508 case DeclaratorContext::CXXCatch:
2509 case DeclaratorContext::ObjCCatch:
2510 case DeclaratorContext::BlockLiteral:
2511 case DeclaratorContext::LambdaExpr:
2512 case DeclaratorContext::ConversionId:
2513 case DeclaratorContext::TemplateArg:
2514 case DeclaratorContext::TemplateTypeArg:
2515 case DeclaratorContext::TrailingReturn:
2516 case DeclaratorContext::TrailingReturnVar:
2517 case DeclaratorContext::RequiresExpr:
2518 case DeclaratorContext::Association:
2519 return false;
2520 }
2521 llvm_unreachable("unknown context kind!");
2522 }
2523
2524 /// Determine whether this declaration appears in a context where an
2525 /// expression could appear.
2526 bool isExpressionContext() const {
2527 switch (Context) {
2528 case DeclaratorContext::File:
2529 case DeclaratorContext::KNRTypeList:
2530 case DeclaratorContext::Member:
2531
2532 // FIXME: sizeof(...) permits an expression.
2533 case DeclaratorContext::TypeName:
2534
2535 case DeclaratorContext::FunctionalCast:
2536 case DeclaratorContext::AliasDecl:
2537 case DeclaratorContext::AliasTemplate:
2538 case DeclaratorContext::Prototype:
2539 case DeclaratorContext::LambdaExprParameter:
2540 case DeclaratorContext::ObjCParameter:
2541 case DeclaratorContext::ObjCResult:
2542 case DeclaratorContext::TemplateParam:
2543 case DeclaratorContext::CXXNew:
2544 case DeclaratorContext::CXXCatch:
2545 case DeclaratorContext::ObjCCatch:
2546 case DeclaratorContext::BlockLiteral:
2547 case DeclaratorContext::LambdaExpr:
2548 case DeclaratorContext::ConversionId:
2549 case DeclaratorContext::TrailingReturn:
2550 case DeclaratorContext::TrailingReturnVar:
2551 case DeclaratorContext::TemplateTypeArg:
2552 case DeclaratorContext::RequiresExpr:
2553 case DeclaratorContext::Association:
2554 return false;
2555
2556 case DeclaratorContext::Block:
2557 case DeclaratorContext::ForInit:
2558 case DeclaratorContext::SelectionInit:
2559 case DeclaratorContext::Condition:
2560 case DeclaratorContext::TemplateArg:
2561 return true;
2562 }
2563
2564 llvm_unreachable("unknown context kind!");
2565 }
2566
2567 /// Return true if a function declarator at this position would be a
2568 /// function declaration.
2569 bool isFunctionDeclaratorAFunctionDeclaration() const {
2570 if (!isFunctionDeclarationContext())
2571 return false;
2572
2573 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2574 if (getTypeObject(i: I).Kind != DeclaratorChunk::Paren)
2575 return false;
2576
2577 return true;
2578 }
2579
2580 /// Determine whether a trailing return type was written (at any
2581 /// level) within this declarator.
2582 bool hasTrailingReturnType() const {
2583 for (const auto &Chunk : type_objects())
2584 if (Chunk.Kind == DeclaratorChunk::Function &&
2585 Chunk.Fun.hasTrailingReturnType())
2586 return true;
2587 return false;
2588 }
2589 /// Get the trailing return type appearing (at any level) within this
2590 /// declarator.
2591 ParsedType getTrailingReturnType() const {
2592 for (const auto &Chunk : type_objects())
2593 if (Chunk.Kind == DeclaratorChunk::Function &&
2594 Chunk.Fun.hasTrailingReturnType())
2595 return Chunk.Fun.getTrailingReturnType();
2596 return ParsedType();
2597 }
2598
2599 /// \brief Sets a trailing requires clause for this declarator.
2600 void setTrailingRequiresClause(Expr *TRC) {
2601 TrailingRequiresClause = TRC;
2602
2603 SetRangeEnd(TRC->getEndLoc());
2604 }
2605
2606 /// \brief Sets a trailing requires clause for this declarator.
2607 Expr *getTrailingRequiresClause() {
2608 return TrailingRequiresClause;
2609 }
2610
2611 /// \brief Determine whether a trailing requires clause was written in this
2612 /// declarator.
2613 bool hasTrailingRequiresClause() const {
2614 return TrailingRequiresClause != nullptr;
2615 }
2616
2617 /// Sets the template parameter lists that preceded the declarator.
2618 void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2619 TemplateParameterLists = TPLs;
2620 }
2621
2622 /// The template parameter lists that preceded the declarator.
2623 ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2624 return TemplateParameterLists;
2625 }
2626
2627 /// Sets the template parameter list generated from the explicit template
2628 /// parameters along with any invented template parameters from
2629 /// placeholder-typed parameters.
2630 void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2631 InventedTemplateParameterList = Invented;
2632 }
2633
2634 /// The template parameter list generated from the explicit template
2635 /// parameters along with any invented template parameters from
2636 /// placeholder-typed parameters, if there were any such parameters.
2637 TemplateParameterList * getInventedTemplateParameterList() const {
2638 return InventedTemplateParameterList;
2639 }
2640
2641 /// takeAttributesAppending - Takes attributes from the given
2642 /// ParsedAttributes set and add them to this declarator.
2643 ///
2644 /// These examples both add 3 attributes to "var":
2645 /// short int var __attribute__((aligned(16),common,deprecated));
2646 /// short int x, __attribute__((aligned(16)) var
2647 /// __attribute__((common,deprecated));
2648 ///
2649 /// Also extends the range of the declarator.
2650 void takeAttributesAppending(ParsedAttributes &attrs) {
2651 Attrs.takeAllAppendingFrom(Other&: attrs);
2652
2653 if (attrs.Range.getEnd().isValid())
2654 SetRangeEnd(attrs.Range.getEnd());
2655 }
2656
2657 const ParsedAttributes &getAttributes() const { return Attrs; }
2658 ParsedAttributes &getAttributes() { return Attrs; }
2659
2660 const ParsedAttributesView &getDeclarationAttributes() const {
2661 return DeclarationAttrs;
2662 }
2663
2664 /// hasAttributes - do we contain any attributes?
2665 bool hasAttributes() const {
2666 if (!getAttributes().empty() || !getDeclarationAttributes().empty() ||
2667 getDeclSpec().hasAttributes())
2668 return true;
2669 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2670 if (!getTypeObject(i).getAttrs().empty())
2671 return true;
2672 return false;
2673 }
2674
2675 void setAsmLabel(Expr *E) { AsmLabel = E; }
2676 Expr *getAsmLabel() const { return AsmLabel; }
2677
2678 void setExtension(bool Val = true) { Extension = Val; }
2679 bool getExtension() const { return Extension; }
2680
2681 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2682 bool isObjCIvar() const { return ObjCIvar; }
2683
2684 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2685 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2686
2687 void setInvalidType(bool Val = true) { InvalidType = Val; }
2688 bool isInvalidType() const {
2689 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2690 }
2691
2692 void setGroupingParens(bool flag) { GroupingParens = flag; }
2693 bool hasGroupingParens() const { return GroupingParens; }
2694
2695 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2696 SourceLocation getCommaLoc() const { return CommaLoc; }
2697 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2698
2699 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2700 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2701 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2702
2703 bool hasPackIndexing() const { return PackIndexingExpr != nullptr; }
2704 Expr *getPackIndexingExpr() const { return PackIndexingExpr; }
2705 void setPackIndexingExpr(Expr *PI) { PackIndexingExpr = PI; }
2706
2707 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2708 FunctionDefinition = static_cast<unsigned>(Val);
2709 }
2710
2711 bool isFunctionDefinition() const {
2712 return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
2713 }
2714
2715 FunctionDefinitionKind getFunctionDefinitionKind() const {
2716 return (FunctionDefinitionKind)FunctionDefinition;
2717 }
2718
2719 void setHasInitializer(bool Val = true) { HasInitializer = Val; }
2720 bool hasInitializer() const { return HasInitializer; }
2721
2722 /// Returns true if this declares a real member and not a friend.
2723 bool isFirstDeclarationOfMember() {
2724 return getContext() == DeclaratorContext::Member &&
2725 !getDeclSpec().isFriendSpecified();
2726 }
2727
2728 /// Returns true if this declares a static member. This cannot be called on a
2729 /// declarator outside of a MemberContext because we won't know until
2730 /// redeclaration time if the decl is static.
2731 bool isStaticMember();
2732
2733 bool isExplicitObjectMemberFunction();
2734
2735 /// Returns true if this declares a constructor or a destructor.
2736 bool isCtorOrDtor();
2737
2738 void setRedeclaration(bool Val) { Redeclaration = Val; }
2739 bool isRedeclaration() const { return Redeclaration; }
2740};
2741
2742/// This little struct is used to capture information about
2743/// structure field declarators, which is basically just a bitfield size.
2744struct FieldDeclarator {
2745 Declarator D;
2746 Expr *BitfieldSize;
2747 explicit FieldDeclarator(const DeclSpec &DS,
2748 const ParsedAttributes &DeclarationAttrs)
2749 : D(DS, DeclarationAttrs, DeclaratorContext::Member),
2750 BitfieldSize(nullptr) {}
2751};
2752
2753/// Represents a C++11 virt-specifier-seq.
2754class VirtSpecifiers {
2755public:
2756 enum Specifier {
2757 VS_None = 0,
2758 VS_Override = 1,
2759 VS_Final = 2,
2760 VS_Sealed = 4,
2761 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2762 VS_GNU_Final = 8,
2763 VS_Abstract = 16
2764 };
2765
2766 VirtSpecifiers() = default;
2767
2768 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2769 const char *&PrevSpec);
2770
2771 bool isUnset() const { return Specifiers == 0; }
2772
2773 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2774 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2775
2776 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2777 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2778 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2779 SourceLocation getAbstractLoc() const { return VS_abstractLoc; }
2780
2781 void clear() { Specifiers = 0; }
2782
2783 static const char *getSpecifierName(Specifier VS);
2784
2785 SourceLocation getFirstLocation() const { return FirstLocation; }
2786 SourceLocation getLastLocation() const { return LastLocation; }
2787 Specifier getLastSpecifier() const { return LastSpecifier; }
2788
2789private:
2790 unsigned Specifiers = 0;
2791 Specifier LastSpecifier = VS_None;
2792
2793 SourceLocation VS_overrideLoc, VS_finalLoc, VS_abstractLoc;
2794 SourceLocation FirstLocation;
2795 SourceLocation LastLocation;
2796};
2797
2798enum class LambdaCaptureInitKind {
2799 NoInit, //!< [a]
2800 CopyInit, //!< [a = b], [a = {b}]
2801 DirectInit, //!< [a(b)]
2802 ListInit //!< [a{b}]
2803};
2804
2805/// Represents a complete lambda introducer.
2806struct LambdaIntroducer {
2807 /// An individual capture in a lambda introducer.
2808 struct LambdaCapture {
2809 LambdaCaptureKind Kind;
2810 SourceLocation Loc;
2811 IdentifierInfo *Id;
2812 SourceLocation EllipsisLoc;
2813 LambdaCaptureInitKind InitKind;
2814 ExprResult Init;
2815 ParsedType InitCaptureType;
2816 SourceRange ExplicitRange;
2817
2818 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2819 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2820 LambdaCaptureInitKind InitKind, ExprResult Init,
2821 ParsedType InitCaptureType,
2822 SourceRange ExplicitRange)
2823 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2824 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2825 ExplicitRange(ExplicitRange) {}
2826 };
2827
2828 SourceRange Range;
2829 SourceLocation DefaultLoc;
2830 LambdaCaptureDefault Default = LCD_None;
2831 SmallVector<LambdaCapture, 4> Captures;
2832
2833 LambdaIntroducer() = default;
2834
2835 bool hasLambdaCapture() const {
2836 return Captures.size() > 0 || Default != LCD_None;
2837 }
2838
2839 /// Append a capture in a lambda introducer.
2840 void addCapture(LambdaCaptureKind Kind,
2841 SourceLocation Loc,
2842 IdentifierInfo* Id,
2843 SourceLocation EllipsisLoc,
2844 LambdaCaptureInitKind InitKind,
2845 ExprResult Init,
2846 ParsedType InitCaptureType,
2847 SourceRange ExplicitRange) {
2848 Captures.push_back(Elt: LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2849 InitCaptureType, ExplicitRange));
2850 }
2851};
2852
2853struct InventedTemplateParameterInfo {
2854 /// The number of parameters in the template parameter list that were
2855 /// explicitly specified by the user, as opposed to being invented by use
2856 /// of an auto parameter.
2857 unsigned NumExplicitTemplateParams = 0;
2858
2859 /// If this is a generic lambda or abbreviated function template, use this
2860 /// as the depth of each 'auto' parameter, during initial AST construction.
2861 unsigned AutoTemplateParameterDepth = 0;
2862
2863 /// Store the list of the template parameters for a generic lambda or an
2864 /// abbreviated function template.
2865 /// If this is a generic lambda or abbreviated function template, this holds
2866 /// the explicit template parameters followed by the auto parameters
2867 /// converted into TemplateTypeParmDecls.
2868 /// It can be used to construct the generic lambda or abbreviated template's
2869 /// template parameter list during initial AST construction.
2870 SmallVector<NamedDecl*, 4> TemplateParams;
2871};
2872
2873} // end namespace clang
2874
2875#endif // LLVM_CLANG_SEMA_DECLSPEC_H
2876