blob: 8364dfc4b0bb38ab27a0f6b0afd4c1aa942ce08a [file] [log] [blame]
David 'Digit' Turner031fad72015-04-29 16:20:20 +02001//===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file defines the classes used to store parsed information about
12/// declaration-specifiers and declarators.
13///
14/// \verbatim
15/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
16/// ------------------------- - -- ---------------------------
17/// declaration-specifiers \ | /
18/// declarators
19/// \endverbatim
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
24#define LLVM_CLANG_SEMA_DECLSPEC_H
25
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/Basic/ExceptionSpecificationType.h"
28#include "clang/Basic/Lambda.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Lex/Token.h"
32#include "clang/Sema/AttributeList.h"
33#include "clang/Sema/Ownership.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ErrorHandling.h"
37
38namespace clang {
39 class ASTContext;
40 class TypeLoc;
41 class LangOptions;
42 class DiagnosticsEngine;
43 class IdentifierInfo;
44 class NamespaceAliasDecl;
45 class NamespaceDecl;
46 class NestedNameSpecifier;
47 class NestedNameSpecifierLoc;
48 class ObjCDeclSpec;
49 class Preprocessor;
50 class Sema;
51 class Declarator;
52 struct TemplateIdAnnotation;
53
54/// \brief Represents a C++ nested-name-specifier or a global scope specifier.
55///
56/// These can be in 3 states:
57/// 1) Not present, identified by isEmpty()
58/// 2) Present, identified by isNotEmpty()
59/// 2.a) Valid, idenified by isValid()
60/// 2.b) Invalid, identified by isInvalid().
61///
62/// isSet() is deprecated because it mostly corresponded to "valid" but was
63/// often used as if it meant "present".
64///
65/// The actual scope is described by getScopeRep().
66class CXXScopeSpec {
67 SourceRange Range;
68 NestedNameSpecifierLocBuilder Builder;
69
70public:
71 const SourceRange &getRange() const { return Range; }
72 void setRange(const SourceRange &R) { Range = R; }
73 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
74 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
75 SourceLocation getBeginLoc() const { return Range.getBegin(); }
76 SourceLocation getEndLoc() const { return Range.getEnd(); }
77
78 /// \brief Retrieve the representation of the nested-name-specifier.
79 NestedNameSpecifier *getScopeRep() const {
80 return Builder.getRepresentation();
81 }
82
83 /// \brief Extend the current nested-name-specifier by another
84 /// nested-name-specifier component of the form 'type::'.
85 ///
86 /// \param Context The AST context in which this nested-name-specifier
87 /// resides.
88 ///
89 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
90 ///
91 /// \param TL The TypeLoc that describes the type preceding the '::'.
92 ///
93 /// \param ColonColonLoc The location of the trailing '::'.
94 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
95 SourceLocation ColonColonLoc);
96
97 /// \brief Extend the current nested-name-specifier by another
98 /// nested-name-specifier component of the form 'identifier::'.
99 ///
100 /// \param Context The AST context in which this nested-name-specifier
101 /// resides.
102 ///
103 /// \param Identifier The identifier.
104 ///
105 /// \param IdentifierLoc The location of the identifier.
106 ///
107 /// \param ColonColonLoc The location of the trailing '::'.
108 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
109 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
110
111 /// \brief Extend the current nested-name-specifier by another
112 /// nested-name-specifier component of the form 'namespace::'.
113 ///
114 /// \param Context The AST context in which this nested-name-specifier
115 /// resides.
116 ///
117 /// \param Namespace The namespace.
118 ///
119 /// \param NamespaceLoc The location of the namespace name.
120 ///
121 /// \param ColonColonLoc The location of the trailing '::'.
122 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
123 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
124
125 /// \brief Extend the current nested-name-specifier by another
126 /// nested-name-specifier component of the form 'namespace-alias::'.
127 ///
128 /// \param Context The AST context in which this nested-name-specifier
129 /// resides.
130 ///
131 /// \param Alias The namespace alias.
132 ///
133 /// \param AliasLoc The location of the namespace alias
134 /// name.
135 ///
136 /// \param ColonColonLoc The location of the trailing '::'.
137 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
138 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
139
140 /// \brief Turn this (empty) nested-name-specifier into the global
141 /// nested-name-specifier '::'.
142 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
143
144 /// \brief Make a new nested-name-specifier from incomplete source-location
145 /// information.
146 ///
147 /// FIXME: This routine should be used very, very rarely, in cases where we
148 /// need to synthesize a nested-name-specifier. Most code should instead use
149 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
150 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
151 SourceRange R);
152
153 /// \brief Adopt an existing nested-name-specifier (with source-range
154 /// information).
155 void Adopt(NestedNameSpecifierLoc Other);
156
157 /// \brief Retrieve a nested-name-specifier with location information, copied
158 /// into the given AST context.
159 ///
160 /// \param Context The context into which this nested-name-specifier will be
161 /// copied.
162 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
163
164 /// \brief Retrieve the location of the name in the last qualifier
165 /// in this nested name specifier.
166 ///
167 /// For example, the location of \c bar
168 /// in
169 /// \verbatim
170 /// \::foo::bar<0>::
171 /// ^~~
172 /// \endverbatim
173 SourceLocation getLastQualifierNameLoc() const;
174
175 /// No scope specifier.
176 bool isEmpty() const { return !Range.isValid(); }
177 /// A scope specifier is present, but may be valid or invalid.
178 bool isNotEmpty() const { return !isEmpty(); }
179
180 /// An error occurred during parsing of the scope specifier.
181 bool isInvalid() const { return isNotEmpty() && getScopeRep() == nullptr; }
182 /// A scope specifier is present, and it refers to a real scope.
183 bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; }
184
185 /// \brief Indicate that this nested-name-specifier is invalid.
186 void SetInvalid(SourceRange R) {
187 assert(R.isValid() && "Must have a valid source range");
188 if (Range.getBegin().isInvalid())
189 Range.setBegin(R.getBegin());
190 Range.setEnd(R.getEnd());
191 Builder.Clear();
192 }
193
194 /// Deprecated. Some call sites intend isNotEmpty() while others intend
195 /// isValid().
196 bool isSet() const { return getScopeRep() != nullptr; }
197
198 void clear() {
199 Range = SourceRange();
200 Builder.Clear();
201 }
202
203 /// \brief Retrieve the data associated with the source-location information.
204 char *location_data() const { return Builder.getBuffer().first; }
205
206 /// \brief Retrieve the size of the data associated with source-location
207 /// information.
208 unsigned location_size() const { return Builder.getBuffer().second; }
209};
210
211/// \brief Captures information about "declaration specifiers".
212///
213/// "Declaration specifiers" encompasses storage-class-specifiers,
214/// type-specifiers, type-qualifiers, and function-specifiers.
215class DeclSpec {
216public:
217 /// \brief storage-class-specifier
218 /// \note The order of these enumerators is important for diagnostics.
219 enum SCS {
220 SCS_unspecified = 0,
221 SCS_typedef,
222 SCS_extern,
223 SCS_static,
224 SCS_auto,
225 SCS_register,
226 SCS_private_extern,
227 SCS_mutable
228 };
229
230 // Import thread storage class specifier enumeration and constants.
231 // These can be combined with SCS_extern and SCS_static.
232 typedef ThreadStorageClassSpecifier TSCS;
233 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
234 static const TSCS TSCS___thread = clang::TSCS___thread;
235 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
236 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
237
238 // Import type specifier width enumeration and constants.
239 typedef TypeSpecifierWidth TSW;
240 static const TSW TSW_unspecified = clang::TSW_unspecified;
241 static const TSW TSW_short = clang::TSW_short;
242 static const TSW TSW_long = clang::TSW_long;
243 static const TSW TSW_longlong = clang::TSW_longlong;
244
245 enum TSC {
246 TSC_unspecified,
247 TSC_imaginary,
248 TSC_complex
249 };
250
251 // Import type specifier sign enumeration and constants.
252 typedef TypeSpecifierSign TSS;
253 static const TSS TSS_unspecified = clang::TSS_unspecified;
254 static const TSS TSS_signed = clang::TSS_signed;
255 static const TSS TSS_unsigned = clang::TSS_unsigned;
256
257 // Import type specifier type enumeration and constants.
258 typedef TypeSpecifierType TST;
259 static const TST TST_unspecified = clang::TST_unspecified;
260 static const TST TST_void = clang::TST_void;
261 static const TST TST_char = clang::TST_char;
262 static const TST TST_wchar = clang::TST_wchar;
263 static const TST TST_char16 = clang::TST_char16;
264 static const TST TST_char32 = clang::TST_char32;
265 static const TST TST_int = clang::TST_int;
266 static const TST TST_int128 = clang::TST_int128;
267 static const TST TST_half = clang::TST_half;
268 static const TST TST_float = clang::TST_float;
269 static const TST TST_double = clang::TST_double;
270 static const TST TST_bool = clang::TST_bool;
271 static const TST TST_decimal32 = clang::TST_decimal32;
272 static const TST TST_decimal64 = clang::TST_decimal64;
273 static const TST TST_decimal128 = clang::TST_decimal128;
274 static const TST TST_enum = clang::TST_enum;
275 static const TST TST_union = clang::TST_union;
276 static const TST TST_struct = clang::TST_struct;
277 static const TST TST_interface = clang::TST_interface;
278 static const TST TST_class = clang::TST_class;
279 static const TST TST_typename = clang::TST_typename;
280 static const TST TST_typeofType = clang::TST_typeofType;
281 static const TST TST_typeofExpr = clang::TST_typeofExpr;
282 static const TST TST_decltype = clang::TST_decltype;
283 static const TST TST_decltype_auto = clang::TST_decltype_auto;
284 static const TST TST_underlyingType = clang::TST_underlyingType;
285 static const TST TST_auto = clang::TST_auto;
286 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
287 static const TST TST_atomic = clang::TST_atomic;
288 static const TST TST_error = clang::TST_error;
289
290 // type-qualifiers
291 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
292 TQ_unspecified = 0,
293 TQ_const = 1,
294 TQ_restrict = 2,
295 TQ_volatile = 4,
296 // This has no corresponding Qualifiers::TQ value, because it's not treated
297 // as a qualifier in our type system.
298 TQ_atomic = 8
299 };
300
301 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
302 /// returned by getParsedSpecifiers.
303 enum ParsedSpecifiers {
304 PQ_None = 0,
305 PQ_StorageClassSpecifier = 1,
306 PQ_TypeSpecifier = 2,
307 PQ_TypeQualifier = 4,
308 PQ_FunctionSpecifier = 8
309 };
310
311private:
312 // storage-class-specifier
313 /*SCS*/unsigned StorageClassSpec : 3;
314 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
315 unsigned SCS_extern_in_linkage_spec : 1;
316
317 // type-specifier
318 /*TSW*/unsigned TypeSpecWidth : 2;
319 /*TSC*/unsigned TypeSpecComplex : 2;
320 /*TSS*/unsigned TypeSpecSign : 2;
321 /*TST*/unsigned TypeSpecType : 6;
322 unsigned TypeAltiVecVector : 1;
323 unsigned TypeAltiVecPixel : 1;
324 unsigned TypeAltiVecBool : 1;
325 unsigned TypeSpecOwned : 1;
326
327 // type-qualifiers
328 unsigned TypeQualifiers : 4; // Bitwise OR of TQ.
329
330 // function-specifier
331 unsigned FS_inline_specified : 1;
332 unsigned FS_forceinline_specified: 1;
333 unsigned FS_virtual_specified : 1;
334 unsigned FS_explicit_specified : 1;
335 unsigned FS_noreturn_specified : 1;
336
337 // friend-specifier
338 unsigned Friend_specified : 1;
339
340 // constexpr-specifier
341 unsigned Constexpr_specified : 1;
342
343 union {
344 UnionParsedType TypeRep;
345 Decl *DeclRep;
346 Expr *ExprRep;
347 };
348
349 // attributes.
350 ParsedAttributes Attrs;
351
352 // Scope specifier for the type spec, if applicable.
353 CXXScopeSpec TypeScope;
354
355 // List of protocol qualifiers for objective-c classes. Used for
356 // protocol-qualified interfaces "NString<foo>" and protocol-qualified id
357 // "id<foo>".
358 Decl * const *ProtocolQualifiers;
359 unsigned NumProtocolQualifiers;
360 SourceLocation ProtocolLAngleLoc;
361 SourceLocation *ProtocolLocs;
362
363 // SourceLocation info. These are null if the item wasn't specified or if
364 // the setting was synthesized.
365 SourceRange Range;
366
367 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
368 SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
369 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
370 /// typename, then this is the location of the named type (if present);
371 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
372 /// TSTNameLoc provides source range info for tag types.
373 SourceLocation TSTNameLoc;
374 SourceRange TypeofParensRange;
375 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc;
376 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
377 SourceLocation FS_forceinlineLoc;
378 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
379
380 WrittenBuiltinSpecs writtenBS;
381 void SaveWrittenBuiltinSpecs();
382
383 ObjCDeclSpec *ObjCQualifiers;
384
385 static bool isTypeRep(TST T) {
386 return (T == TST_typename || T == TST_typeofType ||
387 T == TST_underlyingType || T == TST_atomic);
388 }
389 static bool isExprRep(TST T) {
390 return (T == TST_typeofExpr || T == TST_decltype);
391 }
392
393 DeclSpec(const DeclSpec &) LLVM_DELETED_FUNCTION;
394 void operator=(const DeclSpec &) LLVM_DELETED_FUNCTION;
395public:
396 static bool isDeclRep(TST T) {
397 return (T == TST_enum || T == TST_struct ||
398 T == TST_interface || T == TST_union ||
399 T == TST_class);
400 }
401
402 DeclSpec(AttributeFactory &attrFactory)
403 : StorageClassSpec(SCS_unspecified),
404 ThreadStorageClassSpec(TSCS_unspecified),
405 SCS_extern_in_linkage_spec(false),
406 TypeSpecWidth(TSW_unspecified),
407 TypeSpecComplex(TSC_unspecified),
408 TypeSpecSign(TSS_unspecified),
409 TypeSpecType(TST_unspecified),
410 TypeAltiVecVector(false),
411 TypeAltiVecPixel(false),
412 TypeAltiVecBool(false),
413 TypeSpecOwned(false),
414 TypeQualifiers(TQ_unspecified),
415 FS_inline_specified(false),
416 FS_forceinline_specified(false),
417 FS_virtual_specified(false),
418 FS_explicit_specified(false),
419 FS_noreturn_specified(false),
420 Friend_specified(false),
421 Constexpr_specified(false),
422 Attrs(attrFactory),
423 ProtocolQualifiers(nullptr),
424 NumProtocolQualifiers(0),
425 ProtocolLocs(nullptr),
426 writtenBS(),
427 ObjCQualifiers(nullptr) {
428 }
429 ~DeclSpec() {
430 delete [] ProtocolQualifiers;
431 delete [] ProtocolLocs;
432 }
433 // storage-class-specifier
434 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
435 TSCS getThreadStorageClassSpec() const {
436 return (TSCS)ThreadStorageClassSpec;
437 }
438 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
439 void setExternInLinkageSpec(bool Value) {
440 SCS_extern_in_linkage_spec = Value;
441 }
442
443 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
444 SourceLocation getThreadStorageClassSpecLoc() const {
445 return ThreadStorageClassSpecLoc;
446 }
447
448 void ClearStorageClassSpecs() {
449 StorageClassSpec = DeclSpec::SCS_unspecified;
450 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
451 SCS_extern_in_linkage_spec = false;
452 StorageClassSpecLoc = SourceLocation();
453 ThreadStorageClassSpecLoc = SourceLocation();
454 }
455
456 void ClearTypeSpecType() {
457 TypeSpecType = DeclSpec::TST_unspecified;
458 TypeSpecOwned = false;
459 TSTLoc = SourceLocation();
460 }
461
462 // type-specifier
463 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
464 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
465 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
466 TST getTypeSpecType() const { return (TST)TypeSpecType; }
467 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
468 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
469 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
470 bool isTypeSpecOwned() const { return TypeSpecOwned; }
471 ParsedType getRepAsType() const {
472 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
473 return TypeRep;
474 }
475 Decl *getRepAsDecl() const {
476 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
477 return DeclRep;
478 }
479 Expr *getRepAsExpr() const {
480 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
481 return ExprRep;
482 }
483 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
484 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
485
486 const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
487 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
488 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
489
490 SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
491 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
492 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
493 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
494 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
495
496 SourceLocation getTypeSpecTypeNameLoc() const {
497 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
498 return TSTNameLoc;
499 }
500
501 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
502 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
503
504 bool containsPlaceholderType() const {
505 return TypeSpecType == TST_auto || TypeSpecType == TST_decltype_auto;
506 }
507
508 bool hasTagDefinition() const;
509
510 /// \brief Turn a type-specifier-type into a string like "_Bool" or "union".
511 static const char *getSpecifierName(DeclSpec::TST T,
512 const PrintingPolicy &Policy);
513 static const char *getSpecifierName(DeclSpec::TQ Q);
514 static const char *getSpecifierName(DeclSpec::TSS S);
515 static const char *getSpecifierName(DeclSpec::TSC C);
516 static const char *getSpecifierName(DeclSpec::TSW W);
517 static const char *getSpecifierName(DeclSpec::SCS S);
518 static const char *getSpecifierName(DeclSpec::TSCS S);
519
520 // type-qualifiers
521
522 /// getTypeQualifiers - Return a set of TQs.
523 unsigned getTypeQualifiers() const { return TypeQualifiers; }
524 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
525 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
526 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
527 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
528
529 /// \brief Clear out all of the type qualifiers.
530 void ClearTypeQualifiers() {
531 TypeQualifiers = 0;
532 TQ_constLoc = SourceLocation();
533 TQ_restrictLoc = SourceLocation();
534 TQ_volatileLoc = SourceLocation();
535 TQ_atomicLoc = SourceLocation();
536 }
537
538 // function-specifier
539 bool isInlineSpecified() const {
540 return FS_inline_specified | FS_forceinline_specified;
541 }
542 SourceLocation getInlineSpecLoc() const {
543 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
544 }
545
546 bool isVirtualSpecified() const { return FS_virtual_specified; }
547 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
548
549 bool isExplicitSpecified() const { return FS_explicit_specified; }
550 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
551
552 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
553 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
554
555 void ClearFunctionSpecs() {
556 FS_inline_specified = false;
557 FS_inlineLoc = SourceLocation();
558 FS_forceinline_specified = false;
559 FS_forceinlineLoc = SourceLocation();
560 FS_virtual_specified = false;
561 FS_virtualLoc = SourceLocation();
562 FS_explicit_specified = false;
563 FS_explicitLoc = SourceLocation();
564 FS_noreturn_specified = false;
565 FS_noreturnLoc = SourceLocation();
566 }
567
568 /// \brief Return true if any type-specifier has been found.
569 bool hasTypeSpecifier() const {
570 return getTypeSpecType() != DeclSpec::TST_unspecified ||
571 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
572 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
573 getTypeSpecSign() != DeclSpec::TSS_unspecified;
574 }
575
576 /// \brief Return a bitmask of which flavors of specifiers this
577 /// DeclSpec includes.
578 unsigned getParsedSpecifiers() const;
579
580 /// isEmpty - Return true if this declaration specifier is completely empty:
581 /// no tokens were parsed in the production of it.
582 bool isEmpty() const {
583 return getParsedSpecifiers() == DeclSpec::PQ_None;
584 }
585
586 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
587 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
588
589 /// These methods set the specified attribute of the DeclSpec and
590 /// return false if there was no error. If an error occurs (for
591 /// example, if we tried to set "auto" on a spec with "extern"
592 /// already set), they return true and set PrevSpec and DiagID
593 /// such that
594 /// Diag(Loc, DiagID) << PrevSpec;
595 /// will yield a useful result.
596 ///
597 /// TODO: use a more general approach that still allows these
598 /// diagnostics to be ignored when desired.
599 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
600 const char *&PrevSpec, unsigned &DiagID,
601 const PrintingPolicy &Policy);
602 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
603 const char *&PrevSpec, unsigned &DiagID);
604 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
605 unsigned &DiagID, const PrintingPolicy &Policy);
606 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
607 unsigned &DiagID);
608 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
609 unsigned &DiagID);
610 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
611 unsigned &DiagID, const PrintingPolicy &Policy);
612 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
613 unsigned &DiagID, ParsedType Rep,
614 const PrintingPolicy &Policy);
615 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
616 unsigned &DiagID, Decl *Rep, bool Owned,
617 const PrintingPolicy &Policy);
618 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
619 SourceLocation TagNameLoc, const char *&PrevSpec,
620 unsigned &DiagID, ParsedType Rep,
621 const PrintingPolicy &Policy);
622 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
623 SourceLocation TagNameLoc, const char *&PrevSpec,
624 unsigned &DiagID, Decl *Rep, bool Owned,
625 const PrintingPolicy &Policy);
626
627 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
628 unsigned &DiagID, Expr *Rep,
629 const PrintingPolicy &policy);
630 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
631 const char *&PrevSpec, unsigned &DiagID,
632 const PrintingPolicy &Policy);
633 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
634 const char *&PrevSpec, unsigned &DiagID,
635 const PrintingPolicy &Policy);
636 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
637 const char *&PrevSpec, unsigned &DiagID,
638 const PrintingPolicy &Policy);
639 bool SetTypeSpecError();
640 void UpdateDeclRep(Decl *Rep) {
641 assert(isDeclRep((TST) TypeSpecType));
642 DeclRep = Rep;
643 }
644 void UpdateTypeRep(ParsedType Rep) {
645 assert(isTypeRep((TST) TypeSpecType));
646 TypeRep = Rep;
647 }
648 void UpdateExprRep(Expr *Rep) {
649 assert(isExprRep((TST) TypeSpecType));
650 ExprRep = Rep;
651 }
652
653 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
654 unsigned &DiagID, const LangOptions &Lang);
655
656 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
657 unsigned &DiagID);
658 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
659 unsigned &DiagID);
660 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
661 unsigned &DiagID);
662 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
663 unsigned &DiagID);
664 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
665 unsigned &DiagID);
666
667 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
668 unsigned &DiagID);
669 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
670 unsigned &DiagID);
671 bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
672 unsigned &DiagID);
673
674 bool isFriendSpecified() const { return Friend_specified; }
675 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
676
677 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
678 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
679
680 bool isConstexprSpecified() const { return Constexpr_specified; }
681 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
682
683 void ClearConstexprSpec() {
684 Constexpr_specified = false;
685 ConstexprLoc = SourceLocation();
686 }
687
688 AttributePool &getAttributePool() const {
689 return Attrs.getPool();
690 }
691
692 /// \brief Concatenates two attribute lists.
693 ///
694 /// The GCC attribute syntax allows for the following:
695 ///
696 /// \code
697 /// short __attribute__(( unused, deprecated ))
698 /// int __attribute__(( may_alias, aligned(16) )) var;
699 /// \endcode
700 ///
701 /// This declares 4 attributes using 2 lists. The following syntax is
702 /// also allowed and equivalent to the previous declaration.
703 ///
704 /// \code
705 /// short __attribute__((unused)) __attribute__((deprecated))
706 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
707 /// \endcode
708 ///
709 void addAttributes(AttributeList *AL) {
710 Attrs.addAll(AL);
711 }
712
713 bool hasAttributes() const { return !Attrs.empty(); }
714
715 ParsedAttributes &getAttributes() { return Attrs; }
716 const ParsedAttributes &getAttributes() const { return Attrs; }
717
718 void takeAttributesFrom(ParsedAttributes &attrs) {
719 Attrs.takeAllFrom(attrs);
720 }
721
722 typedef Decl * const *ProtocolQualifierListTy;
723 ProtocolQualifierListTy getProtocolQualifiers() const {
724 return ProtocolQualifiers;
725 }
726 SourceLocation *getProtocolLocs() const { return ProtocolLocs; }
727 unsigned getNumProtocolQualifiers() const {
728 return NumProtocolQualifiers;
729 }
730 SourceLocation getProtocolLAngleLoc() const { return ProtocolLAngleLoc; }
731 void setProtocolQualifiers(Decl * const *Protos, unsigned NP,
732 SourceLocation *ProtoLocs,
733 SourceLocation LAngleLoc);
734
735 /// Finish - This does final analysis of the declspec, issuing diagnostics for
736 /// things like "_Imaginary" (lacking an FP type). After calling this method,
737 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
738 void Finish(DiagnosticsEngine &D, Preprocessor &PP,
739 const PrintingPolicy &Policy);
740
741 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
742 return writtenBS;
743 }
744
745 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
746 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
747
748 /// \brief Checks if this DeclSpec can stand alone, without a Declarator.
749 ///
750 /// Only tag declspecs can stand alone.
751 bool isMissingDeclaratorOk();
752};
753
754/// \brief Captures information about "declaration specifiers" specific to
755/// Objective-C.
756class ObjCDeclSpec {
757public:
758 /// ObjCDeclQualifier - Qualifier used on types in method
759 /// declarations. Not all combinations are sensible. Parameters
760 /// can be one of { in, out, inout } with one of { bycopy, byref }.
761 /// Returns can either be { oneway } or not.
762 ///
763 /// This should be kept in sync with Decl::ObjCDeclQualifier.
764 enum ObjCDeclQualifier {
765 DQ_None = 0x0,
766 DQ_In = 0x1,
767 DQ_Inout = 0x2,
768 DQ_Out = 0x4,
769 DQ_Bycopy = 0x8,
770 DQ_Byref = 0x10,
771 DQ_Oneway = 0x20
772 };
773
774 /// PropertyAttributeKind - list of property attributes.
775 enum ObjCPropertyAttributeKind {
776 DQ_PR_noattr = 0x0,
777 DQ_PR_readonly = 0x01,
778 DQ_PR_getter = 0x02,
779 DQ_PR_assign = 0x04,
780 DQ_PR_readwrite = 0x08,
781 DQ_PR_retain = 0x10,
782 DQ_PR_copy = 0x20,
783 DQ_PR_nonatomic = 0x40,
784 DQ_PR_setter = 0x80,
785 DQ_PR_atomic = 0x100,
786 DQ_PR_weak = 0x200,
787 DQ_PR_strong = 0x400,
788 DQ_PR_unsafe_unretained = 0x800
789 };
790
791
792 ObjCDeclSpec()
793 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
794 GetterName(nullptr), SetterName(nullptr) { }
795 ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
796 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
797 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
798 }
799
800 ObjCPropertyAttributeKind getPropertyAttributes() const {
801 return ObjCPropertyAttributeKind(PropertyAttributes);
802 }
803 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
804 PropertyAttributes =
805 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
806 }
807
808 const IdentifierInfo *getGetterName() const { return GetterName; }
809 IdentifierInfo *getGetterName() { return GetterName; }
810 void setGetterName(IdentifierInfo *name) { GetterName = name; }
811
812 const IdentifierInfo *getSetterName() const { return SetterName; }
813 IdentifierInfo *getSetterName() { return SetterName; }
814 void setSetterName(IdentifierInfo *name) { SetterName = name; }
815
816private:
817 // FIXME: These two are unrelated and mutually exclusive. So perhaps
818 // we can put them in a union to reflect their mutual exclusivity
819 // (space saving is negligible).
820 ObjCDeclQualifier objcDeclQualifier : 6;
821
822 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
823 unsigned PropertyAttributes : 12;
824 IdentifierInfo *GetterName; // getter name or NULL if no getter
825 IdentifierInfo *SetterName; // setter name or NULL if no setter
826};
827
828/// \brief Represents a C++ unqualified-id that has been parsed.
829class UnqualifiedId {
830private:
831 UnqualifiedId(const UnqualifiedId &Other) LLVM_DELETED_FUNCTION;
832 const UnqualifiedId &operator=(const UnqualifiedId &) LLVM_DELETED_FUNCTION;
833
834public:
835 /// \brief Describes the kind of unqualified-id parsed.
836 enum IdKind {
837 /// \brief An identifier.
838 IK_Identifier,
839 /// \brief An overloaded operator name, e.g., operator+.
840 IK_OperatorFunctionId,
841 /// \brief A conversion function name, e.g., operator int.
842 IK_ConversionFunctionId,
843 /// \brief A user-defined literal name, e.g., operator "" _i.
844 IK_LiteralOperatorId,
845 /// \brief A constructor name.
846 IK_ConstructorName,
847 /// \brief A constructor named via a template-id.
848 IK_ConstructorTemplateId,
849 /// \brief A destructor name.
850 IK_DestructorName,
851 /// \brief A template-id, e.g., f<int>.
852 IK_TemplateId,
853 /// \brief An implicit 'self' parameter
854 IK_ImplicitSelfParam
855 } Kind;
856
857 struct OFI {
858 /// \brief The kind of overloaded operator.
859 OverloadedOperatorKind Operator;
860
861 /// \brief The source locations of the individual tokens that name
862 /// the operator, e.g., the "new", "[", and "]" tokens in
863 /// operator new [].
864 ///
865 /// Different operators have different numbers of tokens in their name,
866 /// up to three. Any remaining source locations in this array will be
867 /// set to an invalid value for operators with fewer than three tokens.
868 unsigned SymbolLocations[3];
869 };
870
871 /// \brief Anonymous union that holds extra data associated with the
872 /// parsed unqualified-id.
873 union {
874 /// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
875 /// == IK_UserLiteralId, the identifier suffix.
876 IdentifierInfo *Identifier;
877
878 /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
879 /// that we parsed.
880 struct OFI OperatorFunctionId;
881
882 /// \brief When Kind == IK_ConversionFunctionId, the type that the
883 /// conversion function names.
884 UnionParsedType ConversionFunctionId;
885
886 /// \brief When Kind == IK_ConstructorName, the class-name of the type
887 /// whose constructor is being referenced.
888 UnionParsedType ConstructorName;
889
890 /// \brief When Kind == IK_DestructorName, the type referred to by the
891 /// class-name.
892 UnionParsedType DestructorName;
893
894 /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
895 /// the template-id annotation that contains the template name and
896 /// template arguments.
897 TemplateIdAnnotation *TemplateId;
898 };
899
900 /// \brief The location of the first token that describes this unqualified-id,
901 /// which will be the location of the identifier, "operator" keyword,
902 /// tilde (for a destructor), or the template name of a template-id.
903 SourceLocation StartLocation;
904
905 /// \brief The location of the last token that describes this unqualified-id.
906 SourceLocation EndLocation;
907
908 UnqualifiedId() : Kind(IK_Identifier), Identifier(nullptr) { }
909
910 /// \brief Clear out this unqualified-id, setting it to default (invalid)
911 /// state.
912 void clear() {
913 Kind = IK_Identifier;
914 Identifier = nullptr;
915 StartLocation = SourceLocation();
916 EndLocation = SourceLocation();
917 }
918
919 /// \brief Determine whether this unqualified-id refers to a valid name.
920 bool isValid() const { return StartLocation.isValid(); }
921
922 /// \brief Determine whether this unqualified-id refers to an invalid name.
923 bool isInvalid() const { return !isValid(); }
924
925 /// \brief Determine what kind of name we have.
926 IdKind getKind() const { return Kind; }
927 void setKind(IdKind kind) { Kind = kind; }
928
929 /// \brief Specify that this unqualified-id was parsed as an identifier.
930 ///
931 /// \param Id the parsed identifier.
932 /// \param IdLoc the location of the parsed identifier.
933 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
934 Kind = IK_Identifier;
935 Identifier = const_cast<IdentifierInfo *>(Id);
936 StartLocation = EndLocation = IdLoc;
937 }
938
939 /// \brief Specify that this unqualified-id was parsed as an
940 /// operator-function-id.
941 ///
942 /// \param OperatorLoc the location of the 'operator' keyword.
943 ///
944 /// \param Op the overloaded operator.
945 ///
946 /// \param SymbolLocations the locations of the individual operator symbols
947 /// in the operator.
948 void setOperatorFunctionId(SourceLocation OperatorLoc,
949 OverloadedOperatorKind Op,
950 SourceLocation SymbolLocations[3]);
951
952 /// \brief Specify that this unqualified-id was parsed as a
953 /// conversion-function-id.
954 ///
955 /// \param OperatorLoc the location of the 'operator' keyword.
956 ///
957 /// \param Ty the type to which this conversion function is converting.
958 ///
959 /// \param EndLoc the location of the last token that makes up the type name.
960 void setConversionFunctionId(SourceLocation OperatorLoc,
961 ParsedType Ty,
962 SourceLocation EndLoc) {
963 Kind = IK_ConversionFunctionId;
964 StartLocation = OperatorLoc;
965 EndLocation = EndLoc;
966 ConversionFunctionId = Ty;
967 }
968
969 /// \brief Specific that this unqualified-id was parsed as a
970 /// literal-operator-id.
971 ///
972 /// \param Id the parsed identifier.
973 ///
974 /// \param OpLoc the location of the 'operator' keyword.
975 ///
976 /// \param IdLoc the location of the identifier.
977 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
978 SourceLocation IdLoc) {
979 Kind = IK_LiteralOperatorId;
980 Identifier = const_cast<IdentifierInfo *>(Id);
981 StartLocation = OpLoc;
982 EndLocation = IdLoc;
983 }
984
985 /// \brief Specify that this unqualified-id was parsed as a constructor name.
986 ///
987 /// \param ClassType the class type referred to by the constructor name.
988 ///
989 /// \param ClassNameLoc the location of the class name.
990 ///
991 /// \param EndLoc the location of the last token that makes up the type name.
992 void setConstructorName(ParsedType ClassType,
993 SourceLocation ClassNameLoc,
994 SourceLocation EndLoc) {
995 Kind = IK_ConstructorName;
996 StartLocation = ClassNameLoc;
997 EndLocation = EndLoc;
998 ConstructorName = ClassType;
999 }
1000
1001 /// \brief Specify that this unqualified-id was parsed as a
1002 /// template-id that names a constructor.
1003 ///
1004 /// \param TemplateId the template-id annotation that describes the parsed
1005 /// template-id. This UnqualifiedId instance will take ownership of the
1006 /// \p TemplateId and will free it on destruction.
1007 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1008
1009 /// \brief Specify that this unqualified-id was parsed as a destructor name.
1010 ///
1011 /// \param TildeLoc the location of the '~' that introduces the destructor
1012 /// name.
1013 ///
1014 /// \param ClassType the name of the class referred to by the destructor name.
1015 void setDestructorName(SourceLocation TildeLoc,
1016 ParsedType ClassType,
1017 SourceLocation EndLoc) {
1018 Kind = IK_DestructorName;
1019 StartLocation = TildeLoc;
1020 EndLocation = EndLoc;
1021 DestructorName = ClassType;
1022 }
1023
1024 /// \brief Specify that this unqualified-id was parsed as a template-id.
1025 ///
1026 /// \param TemplateId the template-id annotation that describes the parsed
1027 /// template-id. This UnqualifiedId instance will take ownership of the
1028 /// \p TemplateId and will free it on destruction.
1029 void setTemplateId(TemplateIdAnnotation *TemplateId);
1030
1031 /// \brief Return the source range that covers this unqualified-id.
1032 SourceRange getSourceRange() const LLVM_READONLY {
1033 return SourceRange(StartLocation, EndLocation);
1034 }
1035 SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1036 SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1037};
1038
1039/// \brief A set of tokens that has been cached for later parsing.
1040typedef SmallVector<Token, 4> CachedTokens;
1041
1042/// \brief One instance of this struct is used for each type in a
1043/// declarator that is parsed.
1044///
1045/// This is intended to be a small value object.
1046struct DeclaratorChunk {
1047 enum {
1048 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
1049 } Kind;
1050
1051 /// Loc - The place where this type was defined.
1052 SourceLocation Loc;
1053 /// EndLoc - If valid, the place where this chunck ends.
1054 SourceLocation EndLoc;
1055
1056 struct TypeInfoCommon {
1057 AttributeList *AttrList;
1058 };
1059
1060 struct PointerTypeInfo : TypeInfoCommon {
1061 /// The type qualifiers: const/volatile/restrict/atomic.
1062 unsigned TypeQuals : 4;
1063
1064 /// The location of the const-qualifier, if any.
1065 unsigned ConstQualLoc;
1066
1067 /// The location of the volatile-qualifier, if any.
1068 unsigned VolatileQualLoc;
1069
1070 /// The location of the restrict-qualifier, if any.
1071 unsigned RestrictQualLoc;
1072
1073 /// The location of the _Atomic-qualifier, if any.
1074 unsigned AtomicQualLoc;
1075
1076 void destroy() {
1077 }
1078 };
1079
1080 struct ReferenceTypeInfo : TypeInfoCommon {
1081 /// The type qualifier: restrict. [GNU] C++ extension
1082 bool HasRestrict : 1;
1083 /// True if this is an lvalue reference, false if it's an rvalue reference.
1084 bool LValueRef : 1;
1085 void destroy() {
1086 }
1087 };
1088
1089 struct ArrayTypeInfo : TypeInfoCommon {
1090 /// The type qualifiers for the array: const/volatile/restrict/_Atomic.
1091 unsigned TypeQuals : 4;
1092
1093 /// True if this dimension included the 'static' keyword.
1094 bool hasStatic : 1;
1095
1096 /// True if this dimension was [*]. In this case, NumElts is null.
1097 bool isStar : 1;
1098
1099 /// This is the size of the array, or null if [] or [*] was specified.
1100 /// Since the parser is multi-purpose, and we don't want to impose a root
1101 /// expression class on all clients, NumElts is untyped.
1102 Expr *NumElts;
1103
1104 void destroy() {}
1105 };
1106
1107 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1108 /// declarator is parsed. There are two interesting styles of parameters
1109 /// here:
1110 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1111 /// lists will have information about the identifier, but no type information.
1112 /// Parameter type lists will have type info (if the actions module provides
1113 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1114 struct ParamInfo {
1115 IdentifierInfo *Ident;
1116 SourceLocation IdentLoc;
1117 Decl *Param;
1118
1119 /// DefaultArgTokens - When the parameter's default argument
1120 /// cannot be parsed immediately (because it occurs within the
1121 /// declaration of a member function), it will be stored here as a
1122 /// sequence of tokens to be parsed once the class definition is
1123 /// complete. Non-NULL indicates that there is a default argument.
1124 CachedTokens *DefaultArgTokens;
1125
1126 ParamInfo() {}
1127 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1128 Decl *param,
1129 CachedTokens *DefArgTokens = nullptr)
1130 : Ident(ident), IdentLoc(iloc), Param(param),
1131 DefaultArgTokens(DefArgTokens) {}
1132 };
1133
1134 struct TypeAndRange {
1135 ParsedType Ty;
1136 SourceRange Range;
1137 };
1138
1139 struct FunctionTypeInfo : TypeInfoCommon {
1140 /// hasPrototype - This is true if the function had at least one typed
1141 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1142 /// and is treated as a K&R-style function.
1143 unsigned hasPrototype : 1;
1144
1145 /// isVariadic - If this function has a prototype, and if that
1146 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1147 /// contains the location of the ellipsis.
1148 unsigned isVariadic : 1;
1149
1150 /// Can this declaration be a constructor-style initializer?
1151 unsigned isAmbiguous : 1;
1152
1153 /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1154 /// Otherwise, it's an rvalue reference.
1155 unsigned RefQualifierIsLValueRef : 1;
1156
1157 /// The type qualifiers: const/volatile/restrict.
1158 /// The qualifier bitmask values are the same as in QualType.
1159 unsigned TypeQuals : 3;
1160
1161 /// ExceptionSpecType - An ExceptionSpecificationType value.
1162 unsigned ExceptionSpecType : 3;
1163
1164 /// DeleteParams - If this is true, we need to delete[] Params.
1165 unsigned DeleteParams : 1;
1166
1167 /// HasTrailingReturnType - If this is true, a trailing return type was
1168 /// specified.
1169 unsigned HasTrailingReturnType : 1;
1170
1171 /// The location of the left parenthesis in the source.
1172 unsigned LParenLoc;
1173
1174 /// When isVariadic is true, the location of the ellipsis in the source.
1175 unsigned EllipsisLoc;
1176
1177 /// The location of the right parenthesis in the source.
1178 unsigned RParenLoc;
1179
1180 /// NumParams - This is the number of formal parameters specified by the
1181 /// declarator.
1182 unsigned NumParams;
1183
1184 /// NumExceptions - This is the number of types in the dynamic-exception-
1185 /// decl, if the function has one.
1186 unsigned NumExceptions;
1187
1188 /// \brief The location of the ref-qualifier, if any.
1189 ///
1190 /// If this is an invalid location, there is no ref-qualifier.
1191 unsigned RefQualifierLoc;
1192
1193 /// \brief The location of the const-qualifier, if any.
1194 ///
1195 /// If this is an invalid location, there is no const-qualifier.
1196 unsigned ConstQualifierLoc;
1197
1198 /// \brief The location of the volatile-qualifier, if any.
1199 ///
1200 /// If this is an invalid location, there is no volatile-qualifier.
1201 unsigned VolatileQualifierLoc;
1202
1203 /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1204 /// any.
1205 unsigned MutableLoc;
1206
1207 /// \brief The location of the keyword introducing the spec, if any.
1208 unsigned ExceptionSpecLoc;
1209
1210 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1211 /// describe the parameters specified by this function declarator. null if
1212 /// there are no parameters specified.
1213 ParamInfo *Params;
1214
1215 union {
1216 /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1217 /// contain the types in the function's dynamic exception specification
1218 /// and their locations, if there is one.
1219 TypeAndRange *Exceptions;
1220
1221 /// \brief Pointer to the expression in the noexcept-specifier of this
1222 /// function, if it has one.
1223 Expr *NoexceptExpr;
1224 };
1225
1226 /// \brief If HasTrailingReturnType is true, this is the trailing return
1227 /// type specified.
1228 UnionParsedType TrailingReturnType;
1229
1230 /// \brief Reset the parameter list to having zero parameters.
1231 ///
1232 /// This is used in various places for error recovery.
1233 void freeParams() {
1234 for (unsigned I = 0; I < NumParams; ++I) {
1235 delete Params[I].DefaultArgTokens;
1236 Params[I].DefaultArgTokens = nullptr;
1237 }
1238 if (DeleteParams) {
1239 delete[] Params;
1240 DeleteParams = false;
1241 }
1242 NumParams = 0;
1243 }
1244
1245 void destroy() {
1246 if (DeleteParams)
1247 delete[] Params;
1248 if (getExceptionSpecType() == EST_Dynamic)
1249 delete[] Exceptions;
1250 }
1251
1252 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1253 /// like "void foo(a,b,c)". In a function definition, this will be followed
1254 /// by the parameter type definitions.
1255 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1256
1257 SourceLocation getLParenLoc() const {
1258 return SourceLocation::getFromRawEncoding(LParenLoc);
1259 }
1260
1261 SourceLocation getEllipsisLoc() const {
1262 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1263 }
1264
1265 SourceLocation getRParenLoc() const {
1266 return SourceLocation::getFromRawEncoding(RParenLoc);
1267 }
1268
1269 SourceLocation getExceptionSpecLoc() const {
1270 return SourceLocation::getFromRawEncoding(ExceptionSpecLoc);
1271 }
1272
1273 /// \brief Retrieve the location of the ref-qualifier, if any.
1274 SourceLocation getRefQualifierLoc() const {
1275 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1276 }
1277
1278 /// \brief Retrieve the location of the ref-qualifier, if any.
1279 SourceLocation getConstQualifierLoc() const {
1280 return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1281 }
1282
1283 /// \brief Retrieve the location of the ref-qualifier, if any.
1284 SourceLocation getVolatileQualifierLoc() const {
1285 return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1286 }
1287
1288 /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1289 SourceLocation getMutableLoc() const {
1290 return SourceLocation::getFromRawEncoding(MutableLoc);
1291 }
1292
1293 /// \brief Determine whether this function declaration contains a
1294 /// ref-qualifier.
1295 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1296
1297 /// \brief Determine whether this lambda-declarator contains a 'mutable'
1298 /// qualifier.
1299 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1300
1301 /// \brief Get the type of exception specification this function has.
1302 ExceptionSpecificationType getExceptionSpecType() const {
1303 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1304 }
1305
1306 /// \brief Determine whether this function declarator had a
1307 /// trailing-return-type.
1308 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1309
1310 /// \brief Get the trailing-return-type for this function declarator.
1311 ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1312 };
1313
1314 struct BlockPointerTypeInfo : TypeInfoCommon {
1315 /// For now, sema will catch these as invalid.
1316 /// The type qualifiers: const/volatile/restrict/_Atomic.
1317 unsigned TypeQuals : 4;
1318
1319 void destroy() {
1320 }
1321 };
1322
1323 struct MemberPointerTypeInfo : TypeInfoCommon {
1324 /// The type qualifiers: const/volatile/restrict/_Atomic.
1325 unsigned TypeQuals : 4;
1326 // CXXScopeSpec has a constructor, so it can't be a direct member.
1327 // So we need some pointer-aligned storage and a bit of trickery.
1328 union {
1329 void *Aligner;
1330 char Mem[sizeof(CXXScopeSpec)];
1331 } ScopeMem;
1332 CXXScopeSpec &Scope() {
1333 return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
1334 }
1335 const CXXScopeSpec &Scope() const {
1336 return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
1337 }
1338 void destroy() {
1339 Scope().~CXXScopeSpec();
1340 }
1341 };
1342
1343 union {
1344 TypeInfoCommon Common;
1345 PointerTypeInfo Ptr;
1346 ReferenceTypeInfo Ref;
1347 ArrayTypeInfo Arr;
1348 FunctionTypeInfo Fun;
1349 BlockPointerTypeInfo Cls;
1350 MemberPointerTypeInfo Mem;
1351 };
1352
1353 void destroy() {
1354 switch (Kind) {
1355 case DeclaratorChunk::Function: return Fun.destroy();
1356 case DeclaratorChunk::Pointer: return Ptr.destroy();
1357 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1358 case DeclaratorChunk::Reference: return Ref.destroy();
1359 case DeclaratorChunk::Array: return Arr.destroy();
1360 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1361 case DeclaratorChunk::Paren: return;
1362 }
1363 }
1364
1365 /// \brief If there are attributes applied to this declaratorchunk, return
1366 /// them.
1367 const AttributeList *getAttrs() const {
1368 return Common.AttrList;
1369 }
1370
1371 AttributeList *&getAttrListRef() {
1372 return Common.AttrList;
1373 }
1374
1375 /// \brief Return a DeclaratorChunk for a pointer.
1376 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1377 SourceLocation ConstQualLoc,
1378 SourceLocation VolatileQualLoc,
1379 SourceLocation RestrictQualLoc) {
1380 DeclaratorChunk I;
1381 I.Kind = Pointer;
1382 I.Loc = Loc;
1383 I.Ptr.TypeQuals = TypeQuals;
1384 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1385 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1386 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1387 I.Ptr.AttrList = nullptr;
1388 return I;
1389 }
1390
1391 /// \brief Return a DeclaratorChunk for a reference.
1392 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1393 bool lvalue) {
1394 DeclaratorChunk I;
1395 I.Kind = Reference;
1396 I.Loc = Loc;
1397 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1398 I.Ref.LValueRef = lvalue;
1399 I.Ref.AttrList = nullptr;
1400 return I;
1401 }
1402
1403 /// \brief Return a DeclaratorChunk for an array.
1404 static DeclaratorChunk getArray(unsigned TypeQuals,
1405 bool isStatic, bool isStar, Expr *NumElts,
1406 SourceLocation LBLoc, SourceLocation RBLoc) {
1407 DeclaratorChunk I;
1408 I.Kind = Array;
1409 I.Loc = LBLoc;
1410 I.EndLoc = RBLoc;
1411 I.Arr.AttrList = nullptr;
1412 I.Arr.TypeQuals = TypeQuals;
1413 I.Arr.hasStatic = isStatic;
1414 I.Arr.isStar = isStar;
1415 I.Arr.NumElts = NumElts;
1416 return I;
1417 }
1418
1419 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1420 /// "TheDeclarator" is the declarator that this will be added to.
1421 static DeclaratorChunk getFunction(bool HasProto,
1422 bool IsAmbiguous,
1423 SourceLocation LParenLoc,
1424 ParamInfo *Params, unsigned NumParams,
1425 SourceLocation EllipsisLoc,
1426 SourceLocation RParenLoc,
1427 unsigned TypeQuals,
1428 bool RefQualifierIsLvalueRef,
1429 SourceLocation RefQualifierLoc,
1430 SourceLocation ConstQualifierLoc,
1431 SourceLocation VolatileQualifierLoc,
1432 SourceLocation MutableLoc,
1433 ExceptionSpecificationType ESpecType,
1434 SourceLocation ESpecLoc,
1435 ParsedType *Exceptions,
1436 SourceRange *ExceptionRanges,
1437 unsigned NumExceptions,
1438 Expr *NoexceptExpr,
1439 SourceLocation LocalRangeBegin,
1440 SourceLocation LocalRangeEnd,
1441 Declarator &TheDeclarator,
1442 TypeResult TrailingReturnType =
1443 TypeResult());
1444
1445 /// \brief Return a DeclaratorChunk for a block.
1446 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1447 SourceLocation Loc) {
1448 DeclaratorChunk I;
1449 I.Kind = BlockPointer;
1450 I.Loc = Loc;
1451 I.Cls.TypeQuals = TypeQuals;
1452 I.Cls.AttrList = nullptr;
1453 return I;
1454 }
1455
1456 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1457 unsigned TypeQuals,
1458 SourceLocation Loc) {
1459 DeclaratorChunk I;
1460 I.Kind = MemberPointer;
1461 I.Loc = Loc;
1462 I.Mem.TypeQuals = TypeQuals;
1463 I.Mem.AttrList = nullptr;
1464 new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
1465 return I;
1466 }
1467
1468 /// \brief Return a DeclaratorChunk for a paren.
1469 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1470 SourceLocation RParenLoc) {
1471 DeclaratorChunk I;
1472 I.Kind = Paren;
1473 I.Loc = LParenLoc;
1474 I.EndLoc = RParenLoc;
1475 I.Common.AttrList = nullptr;
1476 return I;
1477 }
1478
1479 bool isParen() const {
1480 return Kind == Paren;
1481 }
1482};
1483
1484/// \brief Described the kind of function definition (if any) provided for
1485/// a function.
1486enum FunctionDefinitionKind {
1487 FDK_Declaration,
1488 FDK_Definition,
1489 FDK_Defaulted,
1490 FDK_Deleted
1491};
1492
1493/// \brief Information about one declarator, including the parsed type
1494/// information and the identifier.
1495///
1496/// When the declarator is fully formed, this is turned into the appropriate
1497/// Decl object.
1498///
1499/// Declarators come in two types: normal declarators and abstract declarators.
1500/// Abstract declarators are used when parsing types, and don't have an
1501/// identifier. Normal declarators do have ID's.
1502///
1503/// Instances of this class should be a transient object that lives on the
1504/// stack, not objects that are allocated in large quantities on the heap.
1505class Declarator {
1506public:
1507 enum TheContext {
1508 FileContext, // File scope declaration.
1509 PrototypeContext, // Within a function prototype.
1510 ObjCResultContext, // An ObjC method result type.
1511 ObjCParameterContext,// An ObjC method parameter type.
1512 KNRTypeListContext, // K&R type definition list for formals.
1513 TypeNameContext, // Abstract declarator for types.
1514 MemberContext, // Struct/Union field.
1515 BlockContext, // Declaration within a block in a function.
1516 ForContext, // Declaration within first part of a for loop.
1517 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1518 TemplateParamContext,// Within a template parameter list.
1519 CXXNewContext, // C++ new-expression.
1520 CXXCatchContext, // C++ catch exception-declaration
1521 ObjCCatchContext, // Objective-C catch exception-declaration
1522 BlockLiteralContext, // Block literal declarator.
1523 LambdaExprContext, // Lambda-expression declarator.
1524 LambdaExprParameterContext, // Lambda-expression parameter declarator.
1525 ConversionIdContext, // C++ conversion-type-id.
1526 TrailingReturnContext, // C++11 trailing-type-specifier.
1527 TemplateTypeArgContext, // Template type argument.
1528 AliasDeclContext, // C++11 alias-declaration.
1529 AliasTemplateContext // C++11 alias-declaration template.
1530 };
1531
1532private:
1533 const DeclSpec &DS;
1534 CXXScopeSpec SS;
1535 UnqualifiedId Name;
1536 SourceRange Range;
1537
1538 /// \brief Where we are parsing this declarator.
1539 TheContext Context;
1540
1541 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1542 /// parsed. This is pushed from the identifier out, which means that element
1543 /// #0 will be the most closely bound to the identifier, and
1544 /// DeclTypeInfo.back() will be the least closely bound.
1545 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1546
1547 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1548 bool InvalidType : 1;
1549
1550 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1551 bool GroupingParens : 1;
1552
1553 /// FunctionDefinition - Is this Declarator for a function or member
1554 /// definition and, if so, what kind?
1555 ///
1556 /// Actually a FunctionDefinitionKind.
1557 unsigned FunctionDefinition : 2;
1558
1559 /// \brief Is this Declarator a redeclaration?
1560 bool Redeclaration : 1;
1561
1562 /// Attrs - Attributes.
1563 ParsedAttributes Attrs;
1564
1565 /// \brief The asm label, if specified.
1566 Expr *AsmLabel;
1567
1568 /// InlineParams - This is a local array used for the first function decl
1569 /// chunk to avoid going to the heap for the common case when we have one
1570 /// function chunk in the declarator.
1571 DeclaratorChunk::ParamInfo InlineParams[16];
1572 bool InlineParamsUsed;
1573
1574 /// \brief true if the declaration is preceded by \c __extension__.
1575 bool Extension : 1;
1576
1577 /// \brief If this is the second or subsequent declarator in this declaration,
1578 /// the location of the comma before this declarator.
1579 SourceLocation CommaLoc;
1580
1581 /// \brief If provided, the source location of the ellipsis used to describe
1582 /// this declarator as a parameter pack.
1583 SourceLocation EllipsisLoc;
1584
1585 friend struct DeclaratorChunk;
1586
1587public:
1588 Declarator(const DeclSpec &ds, TheContext C)
1589 : DS(ds), Range(ds.getSourceRange()), Context(C),
1590 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1591 GroupingParens(false), FunctionDefinition(FDK_Declaration),
1592 Redeclaration(false),
1593 Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr),
1594 InlineParamsUsed(false), Extension(false) {
1595 }
1596
1597 ~Declarator() {
1598 clear();
1599 }
1600 /// getDeclSpec - Return the declaration-specifier that this declarator was
1601 /// declared with.
1602 const DeclSpec &getDeclSpec() const { return DS; }
1603
1604 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1605 /// should be used with extreme care: declspecs can often be shared between
1606 /// multiple declarators, so mutating the DeclSpec affects all of the
1607 /// Declarators. This should only be done when the declspec is known to not
1608 /// be shared or when in error recovery etc.
1609 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1610
1611 AttributePool &getAttributePool() const {
1612 return Attrs.getPool();
1613 }
1614
1615 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1616 /// nested-name-specifier) that is part of the declarator-id.
1617 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1618 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1619
1620 /// \brief Retrieve the name specified by this declarator.
1621 UnqualifiedId &getName() { return Name; }
1622
1623 TheContext getContext() const { return Context; }
1624
1625 bool isPrototypeContext() const {
1626 return (Context == PrototypeContext ||
1627 Context == ObjCParameterContext ||
1628 Context == ObjCResultContext ||
1629 Context == LambdaExprParameterContext);
1630 }
1631
1632 /// \brief Get the source range that spans this declarator.
1633 const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
1634 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1635 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1636
1637 void SetSourceRange(SourceRange R) { Range = R; }
1638 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1639 /// invalid.
1640 void SetRangeBegin(SourceLocation Loc) {
1641 if (!Loc.isInvalid())
1642 Range.setBegin(Loc);
1643 }
1644 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1645 void SetRangeEnd(SourceLocation Loc) {
1646 if (!Loc.isInvalid())
1647 Range.setEnd(Loc);
1648 }
1649 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1650 /// given declspec, unless its location is invalid. Adopts the range start if
1651 /// the current range start is invalid.
1652 void ExtendWithDeclSpec(const DeclSpec &DS) {
1653 const SourceRange &SR = DS.getSourceRange();
1654 if (Range.getBegin().isInvalid())
1655 Range.setBegin(SR.getBegin());
1656 if (!SR.getEnd().isInvalid())
1657 Range.setEnd(SR.getEnd());
1658 }
1659
1660 /// \brief Reset the contents of this Declarator.
1661 void clear() {
1662 SS.clear();
1663 Name.clear();
1664 Range = DS.getSourceRange();
1665
1666 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1667 DeclTypeInfo[i].destroy();
1668 DeclTypeInfo.clear();
1669 Attrs.clear();
1670 AsmLabel = nullptr;
1671 InlineParamsUsed = false;
1672 CommaLoc = SourceLocation();
1673 EllipsisLoc = SourceLocation();
1674 }
1675
1676 /// mayOmitIdentifier - Return true if the identifier is either optional or
1677 /// not allowed. This is true for typenames, prototypes, and template
1678 /// parameter lists.
1679 bool mayOmitIdentifier() const {
1680 switch (Context) {
1681 case FileContext:
1682 case KNRTypeListContext:
1683 case MemberContext:
1684 case BlockContext:
1685 case ForContext:
1686 case ConditionContext:
1687 return false;
1688
1689 case TypeNameContext:
1690 case AliasDeclContext:
1691 case AliasTemplateContext:
1692 case PrototypeContext:
1693 case LambdaExprParameterContext:
1694 case ObjCParameterContext:
1695 case ObjCResultContext:
1696 case TemplateParamContext:
1697 case CXXNewContext:
1698 case CXXCatchContext:
1699 case ObjCCatchContext:
1700 case BlockLiteralContext:
1701 case LambdaExprContext:
1702 case ConversionIdContext:
1703 case TemplateTypeArgContext:
1704 case TrailingReturnContext:
1705 return true;
1706 }
1707 llvm_unreachable("unknown context kind!");
1708 }
1709
1710 /// mayHaveIdentifier - Return true if the identifier is either optional or
1711 /// required. This is true for normal declarators and prototypes, but not
1712 /// typenames.
1713 bool mayHaveIdentifier() const {
1714 switch (Context) {
1715 case FileContext:
1716 case KNRTypeListContext:
1717 case MemberContext:
1718 case BlockContext:
1719 case ForContext:
1720 case ConditionContext:
1721 case PrototypeContext:
1722 case LambdaExprParameterContext:
1723 case TemplateParamContext:
1724 case CXXCatchContext:
1725 case ObjCCatchContext:
1726 return true;
1727
1728 case TypeNameContext:
1729 case CXXNewContext:
1730 case AliasDeclContext:
1731 case AliasTemplateContext:
1732 case ObjCParameterContext:
1733 case ObjCResultContext:
1734 case BlockLiteralContext:
1735 case LambdaExprContext:
1736 case ConversionIdContext:
1737 case TemplateTypeArgContext:
1738 case TrailingReturnContext:
1739 return false;
1740 }
1741 llvm_unreachable("unknown context kind!");
1742 }
1743
1744 /// diagnoseIdentifier - Return true if the identifier is prohibited and
1745 /// should be diagnosed (because it cannot be anything else).
1746 bool diagnoseIdentifier() const {
1747 switch (Context) {
1748 case FileContext:
1749 case KNRTypeListContext:
1750 case MemberContext:
1751 case BlockContext:
1752 case ForContext:
1753 case ConditionContext:
1754 case PrototypeContext:
1755 case LambdaExprParameterContext:
1756 case TemplateParamContext:
1757 case CXXCatchContext:
1758 case ObjCCatchContext:
1759 case TypeNameContext:
1760 case ConversionIdContext:
1761 case ObjCParameterContext:
1762 case ObjCResultContext:
1763 case BlockLiteralContext:
1764 case CXXNewContext:
1765 case LambdaExprContext:
1766 return false;
1767
1768 case AliasDeclContext:
1769 case AliasTemplateContext:
1770 case TemplateTypeArgContext:
1771 case TrailingReturnContext:
1772 return true;
1773 }
1774 llvm_unreachable("unknown context kind!");
1775 }
1776
1777 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1778 /// followed by a C++ direct initializer, e.g. "int x(1);".
1779 bool mayBeFollowedByCXXDirectInit() const {
1780 if (hasGroupingParens()) return false;
1781
1782 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1783 return false;
1784
1785 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
1786 Context != FileContext)
1787 return false;
1788
1789 // Special names can't have direct initializers.
1790 if (Name.getKind() != UnqualifiedId::IK_Identifier)
1791 return false;
1792
1793 switch (Context) {
1794 case FileContext:
1795 case BlockContext:
1796 case ForContext:
1797 return true;
1798
1799 case ConditionContext:
1800 // This may not be followed by a direct initializer, but it can't be a
1801 // function declaration either, and we'd prefer to perform a tentative
1802 // parse in order to produce the right diagnostic.
1803 return true;
1804
1805 case KNRTypeListContext:
1806 case MemberContext:
1807 case PrototypeContext:
1808 case LambdaExprParameterContext:
1809 case ObjCParameterContext:
1810 case ObjCResultContext:
1811 case TemplateParamContext:
1812 case CXXCatchContext:
1813 case ObjCCatchContext:
1814 case TypeNameContext:
1815 case CXXNewContext:
1816 case AliasDeclContext:
1817 case AliasTemplateContext:
1818 case BlockLiteralContext:
1819 case LambdaExprContext:
1820 case ConversionIdContext:
1821 case TemplateTypeArgContext:
1822 case TrailingReturnContext:
1823 return false;
1824 }
1825 llvm_unreachable("unknown context kind!");
1826 }
1827
1828 /// isPastIdentifier - Return true if we have parsed beyond the point where
1829 /// the
1830 bool isPastIdentifier() const { return Name.isValid(); }
1831
1832 /// hasName - Whether this declarator has a name, which might be an
1833 /// identifier (accessible via getIdentifier()) or some kind of
1834 /// special C++ name (constructor, destructor, etc.).
1835 bool hasName() const {
1836 return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1837 }
1838
1839 IdentifierInfo *getIdentifier() const {
1840 if (Name.getKind() == UnqualifiedId::IK_Identifier)
1841 return Name.Identifier;
1842
1843 return nullptr;
1844 }
1845 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1846
1847 /// \brief Set the name of this declarator to be the given identifier.
1848 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1849 Name.setIdentifier(Id, IdLoc);
1850 }
1851
1852 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1853 /// EndLoc, which should be the last token of the chunk.
1854 void AddTypeInfo(const DeclaratorChunk &TI,
1855 ParsedAttributes &attrs,
1856 SourceLocation EndLoc) {
1857 DeclTypeInfo.push_back(TI);
1858 DeclTypeInfo.back().getAttrListRef() = attrs.getList();
1859 getAttributePool().takeAllFrom(attrs.getPool());
1860
1861 if (!EndLoc.isInvalid())
1862 SetRangeEnd(EndLoc);
1863 }
1864
1865 /// \brief Add a new innermost chunk to this declarator.
1866 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1867 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1868 }
1869
1870 /// \brief Return the number of types applied to this declarator.
1871 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1872
1873 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
1874 /// closest to the identifier.
1875 const DeclaratorChunk &getTypeObject(unsigned i) const {
1876 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1877 return DeclTypeInfo[i];
1878 }
1879 DeclaratorChunk &getTypeObject(unsigned i) {
1880 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1881 return DeclTypeInfo[i];
1882 }
1883
1884 void DropFirstTypeObject() {
1885 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1886 DeclTypeInfo.front().destroy();
1887 DeclTypeInfo.erase(DeclTypeInfo.begin());
1888 }
1889
1890 /// Return the innermost (closest to the declarator) chunk of this
1891 /// declarator that is not a parens chunk, or null if there are no
1892 /// non-parens chunks.
1893 const DeclaratorChunk *getInnermostNonParenChunk() const {
1894 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1895 if (!DeclTypeInfo[i].isParen())
1896 return &DeclTypeInfo[i];
1897 }
1898 return nullptr;
1899 }
1900
1901 /// Return the outermost (furthest from the declarator) chunk of
1902 /// this declarator that is not a parens chunk, or null if there are
1903 /// no non-parens chunks.
1904 const DeclaratorChunk *getOutermostNonParenChunk() const {
1905 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
1906 if (!DeclTypeInfo[i-1].isParen())
1907 return &DeclTypeInfo[i-1];
1908 }
1909 return nullptr;
1910 }
1911
1912 /// isArrayOfUnknownBound - This method returns true if the declarator
1913 /// is a declarator for an array of unknown bound (looking through
1914 /// parentheses).
1915 bool isArrayOfUnknownBound() const {
1916 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
1917 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
1918 !chunk->Arr.NumElts);
1919 }
1920
1921 /// isFunctionDeclarator - This method returns true if the declarator
1922 /// is a function declarator (looking through parentheses).
1923 /// If true is returned, then the reference type parameter idx is
1924 /// assigned with the index of the declaration chunk.
1925 bool isFunctionDeclarator(unsigned& idx) const {
1926 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1927 switch (DeclTypeInfo[i].Kind) {
1928 case DeclaratorChunk::Function:
1929 idx = i;
1930 return true;
1931 case DeclaratorChunk::Paren:
1932 continue;
1933 case DeclaratorChunk::Pointer:
1934 case DeclaratorChunk::Reference:
1935 case DeclaratorChunk::Array:
1936 case DeclaratorChunk::BlockPointer:
1937 case DeclaratorChunk::MemberPointer:
1938 return false;
1939 }
1940 llvm_unreachable("Invalid type chunk");
1941 }
1942 return false;
1943 }
1944
1945 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1946 /// this method returns true if the identifier is a function declarator
1947 /// (looking through parentheses).
1948 bool isFunctionDeclarator() const {
1949 unsigned index;
1950 return isFunctionDeclarator(index);
1951 }
1952
1953 /// getFunctionTypeInfo - Retrieves the function type info object
1954 /// (looking through parentheses).
1955 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1956 assert(isFunctionDeclarator() && "Not a function declarator!");
1957 unsigned index = 0;
1958 isFunctionDeclarator(index);
1959 return DeclTypeInfo[index].Fun;
1960 }
1961
1962 /// getFunctionTypeInfo - Retrieves the function type info object
1963 /// (looking through parentheses).
1964 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1965 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1966 }
1967
1968 /// \brief Determine whether the declaration that will be produced from
1969 /// this declaration will be a function.
1970 ///
1971 /// A declaration can declare a function even if the declarator itself
1972 /// isn't a function declarator, if the type specifier refers to a function
1973 /// type. This routine checks for both cases.
1974 bool isDeclarationOfFunction() const;
1975
1976 /// \brief Return true if this declaration appears in a context where a
1977 /// function declarator would be a function declaration.
1978 bool isFunctionDeclarationContext() const {
1979 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1980 return false;
1981
1982 switch (Context) {
1983 case FileContext:
1984 case MemberContext:
1985 case BlockContext:
1986 return true;
1987
1988 case ForContext:
1989 case ConditionContext:
1990 case KNRTypeListContext:
1991 case TypeNameContext:
1992 case AliasDeclContext:
1993 case AliasTemplateContext:
1994 case PrototypeContext:
1995 case LambdaExprParameterContext:
1996 case ObjCParameterContext:
1997 case ObjCResultContext:
1998 case TemplateParamContext:
1999 case CXXNewContext:
2000 case CXXCatchContext:
2001 case ObjCCatchContext:
2002 case BlockLiteralContext:
2003 case LambdaExprContext:
2004 case ConversionIdContext:
2005 case TemplateTypeArgContext:
2006 case TrailingReturnContext:
2007 return false;
2008 }
2009 llvm_unreachable("unknown context kind!");
2010 }
2011
2012 /// \brief Return true if a function declarator at this position would be a
2013 /// function declaration.
2014 bool isFunctionDeclaratorAFunctionDeclaration() const {
2015 if (!isFunctionDeclarationContext())
2016 return false;
2017
2018 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2019 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2020 return false;
2021
2022 return true;
2023 }
2024
2025 /// takeAttributes - Takes attributes from the given parsed-attributes
2026 /// set and add them to this declarator.
2027 ///
2028 /// These examples both add 3 attributes to "var":
2029 /// short int var __attribute__((aligned(16),common,deprecated));
2030 /// short int x, __attribute__((aligned(16)) var
2031 /// __attribute__((common,deprecated));
2032 ///
2033 /// Also extends the range of the declarator.
2034 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2035 Attrs.takeAllFrom(attrs);
2036
2037 if (!lastLoc.isInvalid())
2038 SetRangeEnd(lastLoc);
2039 }
2040
2041 const AttributeList *getAttributes() const { return Attrs.getList(); }
2042 AttributeList *getAttributes() { return Attrs.getList(); }
2043
2044 AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
2045
2046 /// hasAttributes - do we contain any attributes?
2047 bool hasAttributes() const {
2048 if (getAttributes() || getDeclSpec().hasAttributes()) return true;
2049 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2050 if (getTypeObject(i).getAttrs())
2051 return true;
2052 return false;
2053 }
2054
2055 /// \brief Return a source range list of C++11 attributes associated
2056 /// with the declarator.
2057 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2058 AttributeList *AttrList = Attrs.getList();
2059 while (AttrList) {
2060 if (AttrList->isCXX11Attribute())
2061 Ranges.push_back(AttrList->getRange());
2062 AttrList = AttrList->getNext();
2063 }
2064 }
2065
2066 void setAsmLabel(Expr *E) { AsmLabel = E; }
2067 Expr *getAsmLabel() const { return AsmLabel; }
2068
2069 void setExtension(bool Val = true) { Extension = Val; }
2070 bool getExtension() const { return Extension; }
2071
2072 void setInvalidType(bool Val = true) { InvalidType = Val; }
2073 bool isInvalidType() const {
2074 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2075 }
2076
2077 void setGroupingParens(bool flag) { GroupingParens = flag; }
2078 bool hasGroupingParens() const { return GroupingParens; }
2079
2080 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2081 SourceLocation getCommaLoc() const { return CommaLoc; }
2082 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2083
2084 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2085 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2086 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2087
2088 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2089 FunctionDefinition = Val;
2090 }
2091
2092 bool isFunctionDefinition() const {
2093 return getFunctionDefinitionKind() != FDK_Declaration;
2094 }
2095
2096 FunctionDefinitionKind getFunctionDefinitionKind() const {
2097 return (FunctionDefinitionKind)FunctionDefinition;
2098 }
2099
2100 /// Returns true if this declares a real member and not a friend.
2101 bool isFirstDeclarationOfMember() {
2102 return getContext() == MemberContext && !getDeclSpec().isFriendSpecified();
2103 }
2104
2105 /// Returns true if this declares a static member. This cannot be called on a
2106 /// declarator outside of a MemberContext because we won't know until
2107 /// redeclaration time if the decl is static.
2108 bool isStaticMember();
2109
2110 void setRedeclaration(bool Val) { Redeclaration = Val; }
2111 bool isRedeclaration() const { return Redeclaration; }
2112};
2113
2114/// \brief This little struct is used to capture information about
2115/// structure field declarators, which is basically just a bitfield size.
2116struct FieldDeclarator {
2117 Declarator D;
2118 Expr *BitfieldSize;
2119 explicit FieldDeclarator(const DeclSpec &DS)
2120 : D(DS, Declarator::MemberContext), BitfieldSize(nullptr) { }
2121};
2122
2123/// \brief Represents a C++11 virt-specifier-seq.
2124class VirtSpecifiers {
2125public:
2126 enum Specifier {
2127 VS_None = 0,
2128 VS_Override = 1,
2129 VS_Final = 2,
2130 VS_Sealed = 4
2131 };
2132
2133 VirtSpecifiers() : Specifiers(0) { }
2134
2135 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2136 const char *&PrevSpec);
2137
2138 bool isUnset() const { return Specifiers == 0; }
2139
2140 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2141 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2142
2143 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed); }
2144 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2145 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2146
2147 void clear() { Specifiers = 0; }
2148
2149 static const char *getSpecifierName(Specifier VS);
2150
2151 SourceLocation getLastLocation() const { return LastLocation; }
2152
2153private:
2154 unsigned Specifiers;
2155
2156 SourceLocation VS_overrideLoc, VS_finalLoc;
2157 SourceLocation LastLocation;
2158};
2159
2160/// \brief Represents a complete lambda introducer.
2161struct LambdaIntroducer {
2162 /// \brief An individual capture in a lambda introducer.
2163 struct LambdaCapture {
2164 LambdaCaptureKind Kind;
2165 SourceLocation Loc;
2166 IdentifierInfo *Id;
2167 SourceLocation EllipsisLoc;
2168 ExprResult Init;
2169 ParsedType InitCaptureType;
2170 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2171 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2172 ExprResult Init, ParsedType InitCaptureType)
2173 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc), Init(Init),
2174 InitCaptureType(InitCaptureType) {}
2175 };
2176
2177 SourceRange Range;
2178 SourceLocation DefaultLoc;
2179 LambdaCaptureDefault Default;
2180 SmallVector<LambdaCapture, 4> Captures;
2181
2182 LambdaIntroducer()
2183 : Default(LCD_None) {}
2184
2185 /// \brief Append a capture in a lambda introducer.
2186 void addCapture(LambdaCaptureKind Kind,
2187 SourceLocation Loc,
2188 IdentifierInfo* Id,
2189 SourceLocation EllipsisLoc,
2190 ExprResult Init,
2191 ParsedType InitCaptureType) {
2192 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, Init,
2193 InitCaptureType));
2194 }
2195};
2196
2197} // end namespace clang
2198
2199#endif