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