1 //===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the classes used to store parsed information about
11 // declaration-specifiers and declarators.
13 // static const int volatile x, *y, *(*(*z)[10])(const void *x);
14 // ------------------------- - -- ---------------------------
15 // declaration-specifiers \ | /
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CLANG_SEMA_DECLSPEC_H
21 #define LLVM_CLANG_SEMA_DECLSPEC_H
23 #include "clang/Sema/AttributeList.h"
24 #include "clang/Sema/Ownership.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/Lex/Token.h"
27 #include "clang/Basic/ExceptionSpecificationType.h"
28 #include "clang/Basic/OperatorKinds.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/ErrorHandling.h"
39 class NamespaceAliasDecl;
41 class NestedNameSpecifier;
42 class NestedNameSpecifierLoc;
46 struct TemplateIdAnnotation;
48 /// CXXScopeSpec - Represents a C++ nested-name-specifier or a global scope
49 /// specifier. These can be in 3 states:
50 /// 1) Not present, identified by isEmpty()
51 /// 2) Present, identified by isNotEmpty()
52 /// 2.a) Valid, idenified by isValid()
53 /// 2.b) Invalid, identified by isInvalid().
55 /// isSet() is deprecated because it mostly corresponded to "valid" but was
56 /// often used as if it meant "present".
58 /// The actual scope is described by getScopeRep().
61 NestedNameSpecifierLocBuilder Builder;
64 const SourceRange &getRange() const { return Range; }
65 void setRange(const SourceRange &R) { Range = R; }
66 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
67 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
68 SourceLocation getBeginLoc() const { return Range.getBegin(); }
69 SourceLocation getEndLoc() const { return Range.getEnd(); }
71 /// \brief Retrieve the representation of the nested-name-specifier.
72 NestedNameSpecifier *getScopeRep() const {
73 return Builder.getRepresentation();
76 /// \brief Extend the current nested-name-specifier by another
77 /// nested-name-specifier component of the form 'type::'.
79 /// \param Context The AST context in which this nested-name-specifier
82 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
84 /// \param TL The TypeLoc that describes the type preceding the '::'.
86 /// \param ColonColonLoc The location of the trailing '::'.
87 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
88 SourceLocation ColonColonLoc);
90 /// \brief Extend the current nested-name-specifier by another
91 /// nested-name-specifier component of the form 'identifier::'.
93 /// \param Context The AST context in which this nested-name-specifier
96 /// \param Identifier The identifier.
98 /// \param IdentifierLoc The location of the identifier.
100 /// \param ColonColonLoc The location of the trailing '::'.
101 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
102 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
104 /// \brief Extend the current nested-name-specifier by another
105 /// nested-name-specifier component of the form 'namespace::'.
107 /// \param Context The AST context in which this nested-name-specifier
110 /// \param Namespace The namespace.
112 /// \param NamespaceLoc The location of the namespace name.
114 /// \param ColonColonLoc The location of the trailing '::'.
115 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
116 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
118 /// \brief Extend the current nested-name-specifier by another
119 /// nested-name-specifier component of the form 'namespace-alias::'.
121 /// \param Context The AST context in which this nested-name-specifier
124 /// \param Alias The namespace alias.
126 /// \param AliasLoc The location of the namespace alias
129 /// \param ColonColonLoc The location of the trailing '::'.
130 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
131 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
133 /// \brief Turn this (empty) nested-name-specifier into the global
134 /// nested-name-specifier '::'.
135 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
137 /// \brief Make a new nested-name-specifier from incomplete source-location
140 /// FIXME: This routine should be used very, very rarely, in cases where we
141 /// need to synthesize a nested-name-specifier. Most code should instead use
142 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
143 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
146 /// \brief Adopt an existing nested-name-specifier (with source-range
148 void Adopt(NestedNameSpecifierLoc Other);
150 /// \brief Retrieve a nested-name-specifier with location information, copied
151 /// into the given AST context.
153 /// \param Context The context into which this nested-name-specifier will be
155 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
157 /// \brief Retrieve the location of the name in the last qualifier
158 /// in this nested name specifier. For example:
161 SourceLocation getLastQualifierNameLoc() const;
163 /// No scope specifier.
164 bool isEmpty() const { return !Range.isValid(); }
165 /// A scope specifier is present, but may be valid or invalid.
166 bool isNotEmpty() const { return !isEmpty(); }
168 /// An error occurred during parsing of the scope specifier.
169 bool isInvalid() const { return isNotEmpty() && getScopeRep() == 0; }
170 /// A scope specifier is present, and it refers to a real scope.
171 bool isValid() const { return isNotEmpty() && getScopeRep() != 0; }
173 /// \brief Indicate that this nested-name-specifier is invalid.
174 void SetInvalid(SourceRange R) {
175 assert(R.isValid() && "Must have a valid source range");
176 if (Range.getBegin().isInvalid())
177 Range.setBegin(R.getBegin());
178 Range.setEnd(R.getEnd());
182 /// Deprecated. Some call sites intend isNotEmpty() while others intend
184 bool isSet() const { return getScopeRep() != 0; }
187 Range = SourceRange();
191 /// \brief Retrieve the data associated with the source-location information.
192 char *location_data() const { return Builder.getBuffer().first; }
194 /// \brief Retrieve the size of the data associated with source-location
196 unsigned location_size() const { return Builder.getBuffer().second; }
199 /// DeclSpec - This class captures information about "declaration specifiers",
200 /// which encompasses storage-class-specifiers, type-specifiers,
201 /// type-qualifiers, and function-specifiers.
204 // storage-class-specifier
205 // Note: The order of these enumerators is important for diagnostics.
217 // Import type specifier width enumeration and constants.
218 typedef TypeSpecifierWidth TSW;
219 static const TSW TSW_unspecified = clang::TSW_unspecified;
220 static const TSW TSW_short = clang::TSW_short;
221 static const TSW TSW_long = clang::TSW_long;
222 static const TSW TSW_longlong = clang::TSW_longlong;
230 // Import type specifier sign enumeration and constants.
231 typedef TypeSpecifierSign TSS;
232 static const TSS TSS_unspecified = clang::TSS_unspecified;
233 static const TSS TSS_signed = clang::TSS_signed;
234 static const TSS TSS_unsigned = clang::TSS_unsigned;
236 // Import type specifier type enumeration and constants.
237 typedef TypeSpecifierType TST;
238 static const TST TST_unspecified = clang::TST_unspecified;
239 static const TST TST_void = clang::TST_void;
240 static const TST TST_char = clang::TST_char;
241 static const TST TST_wchar = clang::TST_wchar;
242 static const TST TST_char16 = clang::TST_char16;
243 static const TST TST_char32 = clang::TST_char32;
244 static const TST TST_int = clang::TST_int;
245 static const TST TST_float = clang::TST_float;
246 static const TST TST_double = clang::TST_double;
247 static const TST TST_bool = clang::TST_bool;
248 static const TST TST_decimal32 = clang::TST_decimal32;
249 static const TST TST_decimal64 = clang::TST_decimal64;
250 static const TST TST_decimal128 = clang::TST_decimal128;
251 static const TST TST_enum = clang::TST_enum;
252 static const TST TST_union = clang::TST_union;
253 static const TST TST_struct = clang::TST_struct;
254 static const TST TST_class = clang::TST_class;
255 static const TST TST_typename = clang::TST_typename;
256 static const TST TST_typeofType = clang::TST_typeofType;
257 static const TST TST_typeofExpr = clang::TST_typeofExpr;
258 static const TST TST_decltype = clang::TST_decltype;
259 static const TST TST_underlyingType = clang::TST_underlyingType;
260 static const TST TST_auto = clang::TST_auto;
261 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
262 static const TST TST_error = clang::TST_error;
265 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
272 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
273 /// returned by getParsedSpecifiers.
274 enum ParsedSpecifiers {
276 PQ_StorageClassSpecifier = 1,
277 PQ_TypeSpecifier = 2,
278 PQ_TypeQualifier = 4,
279 PQ_FunctionSpecifier = 8
283 // storage-class-specifier
284 /*SCS*/unsigned StorageClassSpec : 3;
285 unsigned SCS_thread_specified : 1;
286 unsigned SCS_extern_in_linkage_spec : 1;
289 /*TSW*/unsigned TypeSpecWidth : 2;
290 /*TSC*/unsigned TypeSpecComplex : 2;
291 /*TSS*/unsigned TypeSpecSign : 2;
292 /*TST*/unsigned TypeSpecType : 5;
293 unsigned TypeAltiVecVector : 1;
294 unsigned TypeAltiVecPixel : 1;
295 unsigned TypeAltiVecBool : 1;
296 unsigned TypeSpecOwned : 1;
299 unsigned TypeQualifiers : 3; // Bitwise OR of TQ.
301 // function-specifier
302 unsigned FS_inline_specified : 1;
303 unsigned FS_virtual_specified : 1;
304 unsigned FS_explicit_specified : 1;
307 unsigned Friend_specified : 1;
309 // constexpr-specifier
310 unsigned Constexpr_specified : 1;
312 /*SCS*/unsigned StorageClassSpecAsWritten : 3;
315 UnionParsedType TypeRep;
321 ParsedAttributes Attrs;
323 // Scope specifier for the type spec, if applicable.
324 CXXScopeSpec TypeScope;
326 // List of protocol qualifiers for objective-c classes. Used for
327 // protocol-qualified interfaces "NString<foo>" and protocol-qualified id
329 Decl * const *ProtocolQualifiers;
330 unsigned NumProtocolQualifiers;
331 SourceLocation ProtocolLAngleLoc;
332 SourceLocation *ProtocolLocs;
334 // SourceLocation info. These are null if the item wasn't specified or if
335 // the setting was synthesized.
338 SourceLocation StorageClassSpecLoc, SCS_threadLoc;
339 SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
340 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
341 /// typename, then this is the location of the named type (if present);
342 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
343 /// TSTNameLoc provides source range info for tag types.
344 SourceLocation TSTNameLoc;
345 SourceRange TypeofParensRange;
346 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc;
347 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc;
348 SourceLocation FriendLoc, ConstexprLoc;
350 WrittenBuiltinSpecs writtenBS;
351 void SaveWrittenBuiltinSpecs();
352 void SaveStorageSpecifierAsWritten();
354 ObjCDeclSpec *ObjCQualifiers;
356 static bool isTypeRep(TST T) {
357 return (T == TST_typename || T == TST_typeofType ||
358 T == TST_underlyingType);
360 static bool isExprRep(TST T) {
361 return (T == TST_typeofExpr || T == TST_decltype);
363 static bool isDeclRep(TST T) {
364 return (T == TST_enum || T == TST_struct ||
365 T == TST_union || T == TST_class);
368 DeclSpec(const DeclSpec&); // DO NOT IMPLEMENT
369 void operator=(const DeclSpec&); // DO NOT IMPLEMENT
372 DeclSpec(AttributeFactory &attrFactory)
373 : StorageClassSpec(SCS_unspecified),
374 SCS_thread_specified(false),
375 SCS_extern_in_linkage_spec(false),
376 TypeSpecWidth(TSW_unspecified),
377 TypeSpecComplex(TSC_unspecified),
378 TypeSpecSign(TSS_unspecified),
379 TypeSpecType(TST_unspecified),
380 TypeAltiVecVector(false),
381 TypeAltiVecPixel(false),
382 TypeAltiVecBool(false),
383 TypeSpecOwned(false),
384 TypeQualifiers(TSS_unspecified),
385 FS_inline_specified(false),
386 FS_virtual_specified(false),
387 FS_explicit_specified(false),
388 Friend_specified(false),
389 Constexpr_specified(false),
390 StorageClassSpecAsWritten(SCS_unspecified),
392 ProtocolQualifiers(0),
393 NumProtocolQualifiers(0),
399 delete [] ProtocolQualifiers;
400 delete [] ProtocolLocs;
402 // storage-class-specifier
403 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
404 bool isThreadSpecified() const { return SCS_thread_specified; }
405 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
406 void setExternInLinkageSpec(bool Value) {
407 SCS_extern_in_linkage_spec = Value;
410 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
411 SourceLocation getThreadSpecLoc() const { return SCS_threadLoc; }
413 void ClearStorageClassSpecs() {
414 StorageClassSpec = DeclSpec::SCS_unspecified;
415 SCS_thread_specified = false;
416 SCS_extern_in_linkage_spec = false;
417 StorageClassSpecLoc = SourceLocation();
418 SCS_threadLoc = SourceLocation();
422 TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
423 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
424 TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
425 TST getTypeSpecType() const { return (TST)TypeSpecType; }
426 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
427 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
428 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
429 bool isTypeSpecOwned() const { return TypeSpecOwned; }
430 ParsedType getRepAsType() const {
431 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
434 Decl *getRepAsDecl() const {
435 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
438 Expr *getRepAsExpr() const {
439 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
442 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
443 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
445 const SourceRange &getSourceRange() const { return Range; }
446 SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
447 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
448 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
449 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
450 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
452 SourceLocation getTypeSpecTypeNameLoc() const {
453 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
457 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
458 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
460 /// getSpecifierName - Turn a type-specifier-type into a string like "_Bool"
462 static const char *getSpecifierName(DeclSpec::TST T);
463 static const char *getSpecifierName(DeclSpec::TQ Q);
464 static const char *getSpecifierName(DeclSpec::TSS S);
465 static const char *getSpecifierName(DeclSpec::TSC C);
466 static const char *getSpecifierName(DeclSpec::TSW W);
467 static const char *getSpecifierName(DeclSpec::SCS S);
471 /// getTypeQualifiers - Return a set of TQs.
472 unsigned getTypeQualifiers() const { return TypeQualifiers; }
473 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
474 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
475 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
477 /// \brief Clear out all of the type qualifiers.
478 void ClearTypeQualifiers() {
480 TQ_constLoc = SourceLocation();
481 TQ_restrictLoc = SourceLocation();
482 TQ_volatileLoc = SourceLocation();
485 // function-specifier
486 bool isInlineSpecified() const { return FS_inline_specified; }
487 SourceLocation getInlineSpecLoc() const { return FS_inlineLoc; }
489 bool isVirtualSpecified() const { return FS_virtual_specified; }
490 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
492 bool isExplicitSpecified() const { return FS_explicit_specified; }
493 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
495 void ClearFunctionSpecs() {
496 FS_inline_specified = false;
497 FS_inlineLoc = SourceLocation();
498 FS_virtual_specified = false;
499 FS_virtualLoc = SourceLocation();
500 FS_explicit_specified = false;
501 FS_explicitLoc = SourceLocation();
504 /// hasTypeSpecifier - Return true if any type-specifier has been found.
505 bool hasTypeSpecifier() const {
506 return getTypeSpecType() != DeclSpec::TST_unspecified ||
507 getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
508 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
509 getTypeSpecSign() != DeclSpec::TSS_unspecified;
512 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
513 /// DeclSpec includes.
515 unsigned getParsedSpecifiers() const;
517 SCS getStorageClassSpecAsWritten() const {
518 return (SCS)StorageClassSpecAsWritten;
521 /// isEmpty - Return true if this declaration specifier is completely empty:
522 /// no tokens were parsed in the production of it.
523 bool isEmpty() const {
524 return getParsedSpecifiers() == DeclSpec::PQ_None;
527 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
528 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
530 /// These methods set the specified attribute of the DeclSpec and
531 /// return false if there was no error. If an error occurs (for
532 /// example, if we tried to set "auto" on a spec with "extern"
533 /// already set), they return true and set PrevSpec and DiagID
535 /// Diag(Loc, DiagID) << PrevSpec;
536 /// will yield a useful result.
538 /// TODO: use a more general approach that still allows these
539 /// diagnostics to be ignored when desired.
540 bool SetStorageClassSpec(SCS S, SourceLocation Loc, const char *&PrevSpec,
541 unsigned &DiagID, const LangOptions &Lang);
542 bool SetStorageClassSpecThread(SourceLocation Loc, const char *&PrevSpec,
544 bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
546 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
548 bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
550 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
552 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
553 unsigned &DiagID, ParsedType Rep);
554 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
555 unsigned &DiagID, Decl *Rep, bool Owned);
556 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
557 SourceLocation TagNameLoc, const char *&PrevSpec,
558 unsigned &DiagID, ParsedType Rep);
559 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
560 SourceLocation TagNameLoc, const char *&PrevSpec,
561 unsigned &DiagID, Decl *Rep, bool Owned);
563 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
564 unsigned &DiagID, Expr *Rep);
565 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
566 const char *&PrevSpec, unsigned &DiagID);
567 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
568 const char *&PrevSpec, unsigned &DiagID);
569 bool SetTypeSpecError();
570 void UpdateDeclRep(Decl *Rep) {
571 assert(isDeclRep((TST) TypeSpecType));
574 void UpdateTypeRep(ParsedType Rep) {
575 assert(isTypeRep((TST) TypeSpecType));
578 void UpdateExprRep(Expr *Rep) {
579 assert(isExprRep((TST) TypeSpecType));
583 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
584 unsigned &DiagID, const LangOptions &Lang);
586 bool SetFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
588 bool SetFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
590 bool SetFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
593 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
596 bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
599 bool isFriendSpecified() const { return Friend_specified; }
600 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
602 bool isConstexprSpecified() const { return Constexpr_specified; }
603 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
605 AttributePool &getAttributePool() const {
606 return Attrs.getPool();
609 /// AddAttributes - contatenates two attribute lists.
610 /// The GCC attribute syntax allows for the following:
612 /// short __attribute__(( unused, deprecated ))
613 /// int __attribute__(( may_alias, aligned(16) )) var;
615 /// This declares 4 attributes using 2 lists. The following syntax is
616 /// also allowed and equivalent to the previous declaration.
618 /// short __attribute__((unused)) __attribute__((deprecated))
619 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
621 void addAttributes(AttributeList *AL) {
624 void setAttributes(AttributeList *AL) {
628 bool hasAttributes() const { return !Attrs.empty(); }
630 ParsedAttributes &getAttributes() { return Attrs; }
631 const ParsedAttributes &getAttributes() const { return Attrs; }
633 /// TakeAttributes - Return the current attribute list and remove them from
634 /// the DeclSpec so that it doesn't own them.
635 ParsedAttributes takeAttributes() {
636 // The non-const "copy" constructor clears the operand automatically.
640 void takeAttributesFrom(ParsedAttributes &attrs) {
641 Attrs.takeAllFrom(attrs);
644 typedef Decl * const *ProtocolQualifierListTy;
645 ProtocolQualifierListTy getProtocolQualifiers() const {
646 return ProtocolQualifiers;
648 SourceLocation *getProtocolLocs() const { return ProtocolLocs; }
649 unsigned getNumProtocolQualifiers() const {
650 return NumProtocolQualifiers;
652 SourceLocation getProtocolLAngleLoc() const { return ProtocolLAngleLoc; }
653 void setProtocolQualifiers(Decl * const *Protos, unsigned NP,
654 SourceLocation *ProtoLocs,
655 SourceLocation LAngleLoc);
657 /// Finish - This does final analysis of the declspec, issuing diagnostics for
658 /// things like "_Imaginary" (lacking an FP type). After calling this method,
659 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
660 void Finish(Diagnostic &D, Preprocessor &PP);
662 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
666 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
667 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
669 /// isMissingDeclaratorOk - This checks if this DeclSpec can stand alone,
670 /// without a Declarator. Only tag declspecs can stand alone.
671 bool isMissingDeclaratorOk();
674 /// ObjCDeclSpec - This class captures information about
675 /// "declaration specifiers" specific to objective-c
678 /// ObjCDeclQualifier - Qualifier used on types in method
679 /// declarations. Not all combinations are sensible. Parameters
680 /// can be one of { in, out, inout } with one of { bycopy, byref }.
681 /// Returns can either be { oneway } or not.
683 /// This should be kept in sync with Decl::ObjCDeclQualifier.
684 enum ObjCDeclQualifier {
694 /// PropertyAttributeKind - list of property attributes.
695 enum ObjCPropertyAttributeKind {
697 DQ_PR_readonly = 0x01,
700 DQ_PR_readwrite = 0x08,
703 DQ_PR_nonatomic = 0x40,
705 DQ_PR_atomic = 0x100,
707 DQ_PR_strong = 0x400,
708 DQ_PR_unsafe_unretained = 0x800
713 : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
714 GetterName(0), SetterName(0) { }
715 ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
716 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
717 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
720 ObjCPropertyAttributeKind getPropertyAttributes() const {
721 return ObjCPropertyAttributeKind(PropertyAttributes);
723 void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
725 (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
728 const IdentifierInfo *getGetterName() const { return GetterName; }
729 IdentifierInfo *getGetterName() { return GetterName; }
730 void setGetterName(IdentifierInfo *name) { GetterName = name; }
732 const IdentifierInfo *getSetterName() const { return SetterName; }
733 IdentifierInfo *getSetterName() { return SetterName; }
734 void setSetterName(IdentifierInfo *name) { SetterName = name; }
736 // FIXME: These two are unrelated and mutially exclusive. So perhaps
737 // we can put them in a union to reflect their mutual exclusiveness
738 // (space saving is negligible).
739 ObjCDeclQualifier objcDeclQualifier : 6;
741 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
742 unsigned PropertyAttributes : 12;
743 IdentifierInfo *GetterName; // getter name of NULL if no getter
744 IdentifierInfo *SetterName; // setter name of NULL if no setter
747 /// \brief Represents a C++ unqualified-id that has been parsed.
748 class UnqualifiedId {
750 const UnqualifiedId &operator=(const UnqualifiedId &); // DO NOT IMPLEMENT
753 /// \brief Describes the kind of unqualified-id parsed.
755 /// \brief An identifier.
757 /// \brief An overloaded operator name, e.g., operator+.
758 IK_OperatorFunctionId,
759 /// \brief A conversion function name, e.g., operator int.
760 IK_ConversionFunctionId,
761 /// \brief A user-defined literal name, e.g., operator "" _i.
762 IK_LiteralOperatorId,
763 /// \brief A constructor name.
765 /// \brief A constructor named via a template-id.
766 IK_ConstructorTemplateId,
767 /// \brief A destructor name.
769 /// \brief A template-id, e.g., f<int>.
771 /// \brief An implicit 'self' parameter
775 /// \brief Anonymous union that holds extra data associated with the
776 /// parsed unqualified-id.
778 /// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
779 /// == IK_UserLiteralId, the identifier suffix.
780 IdentifierInfo *Identifier;
782 /// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
785 /// \brief The kind of overloaded operator.
786 OverloadedOperatorKind Operator;
788 /// \brief The source locations of the individual tokens that name
789 /// the operator, e.g., the "new", "[", and "]" tokens in
792 /// Different operators have different numbers of tokens in their name,
793 /// up to three. Any remaining source locations in this array will be
794 /// set to an invalid value for operators with fewer than three tokens.
795 unsigned SymbolLocations[3];
796 } OperatorFunctionId;
798 /// \brief When Kind == IK_ConversionFunctionId, the type that the
799 /// conversion function names.
800 UnionParsedType ConversionFunctionId;
802 /// \brief When Kind == IK_ConstructorName, the class-name of the type
803 /// whose constructor is being referenced.
804 UnionParsedType ConstructorName;
806 /// \brief When Kind == IK_DestructorName, the type referred to by the
808 UnionParsedType DestructorName;
810 /// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
811 /// the template-id annotation that contains the template name and
812 /// template arguments.
813 TemplateIdAnnotation *TemplateId;
816 /// \brief The location of the first token that describes this unqualified-id,
817 /// which will be the location of the identifier, "operator" keyword,
818 /// tilde (for a destructor), or the template name of a template-id.
819 SourceLocation StartLocation;
821 /// \brief The location of the last token that describes this unqualified-id.
822 SourceLocation EndLocation;
824 UnqualifiedId() : Kind(IK_Identifier), Identifier(0) { }
826 /// \brief Do not use this copy constructor. It is temporary, and only
827 /// exists because we are holding FieldDeclarators in a SmallVector when we
828 /// don't actually need them.
830 /// FIXME: Kill this copy constructor.
831 UnqualifiedId(const UnqualifiedId &Other)
832 : Kind(IK_Identifier), Identifier(Other.Identifier),
833 StartLocation(Other.StartLocation), EndLocation(Other.EndLocation) {
834 assert(Other.Kind == IK_Identifier && "Cannot copy non-identifiers");
837 /// \brief Destroy this unqualified-id.
838 ~UnqualifiedId() { clear(); }
840 /// \brief Clear out this unqualified-id, setting it to default (invalid)
844 /// \brief Determine whether this unqualified-id refers to a valid name.
845 bool isValid() const { return StartLocation.isValid(); }
847 /// \brief Determine whether this unqualified-id refers to an invalid name.
848 bool isInvalid() const { return !isValid(); }
850 /// \brief Determine what kind of name we have.
851 IdKind getKind() const { return Kind; }
852 void setKind(IdKind kind) { Kind = kind; }
854 /// \brief Specify that this unqualified-id was parsed as an identifier.
856 /// \param Id the parsed identifier.
857 /// \param IdLoc the location of the parsed identifier.
858 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
859 Kind = IK_Identifier;
860 Identifier = const_cast<IdentifierInfo *>(Id);
861 StartLocation = EndLocation = IdLoc;
864 /// \brief Specify that this unqualified-id was parsed as an
865 /// operator-function-id.
867 /// \param OperatorLoc the location of the 'operator' keyword.
869 /// \param Op the overloaded operator.
871 /// \param SymbolLocations the locations of the individual operator symbols
873 void setOperatorFunctionId(SourceLocation OperatorLoc,
874 OverloadedOperatorKind Op,
875 SourceLocation SymbolLocations[3]);
877 /// \brief Specify that this unqualified-id was parsed as a
878 /// conversion-function-id.
880 /// \param OperatorLoc the location of the 'operator' keyword.
882 /// \param Ty the type to which this conversion function is converting.
884 /// \param EndLoc the location of the last token that makes up the type name.
885 void setConversionFunctionId(SourceLocation OperatorLoc,
887 SourceLocation EndLoc) {
888 Kind = IK_ConversionFunctionId;
889 StartLocation = OperatorLoc;
890 EndLocation = EndLoc;
891 ConversionFunctionId = Ty;
894 /// \brief Specific that this unqualified-id was parsed as a
895 /// literal-operator-id.
897 /// \param Id the parsed identifier.
899 /// \param OpLoc the location of the 'operator' keyword.
901 /// \param IdLoc the location of the identifier.
902 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
903 SourceLocation IdLoc) {
904 Kind = IK_LiteralOperatorId;
905 Identifier = const_cast<IdentifierInfo *>(Id);
906 StartLocation = OpLoc;
910 /// \brief Specify that this unqualified-id was parsed as a constructor name.
912 /// \param ClassType the class type referred to by the constructor name.
914 /// \param ClassNameLoc the location of the class name.
916 /// \param EndLoc the location of the last token that makes up the type name.
917 void setConstructorName(ParsedType ClassType,
918 SourceLocation ClassNameLoc,
919 SourceLocation EndLoc) {
920 Kind = IK_ConstructorName;
921 StartLocation = ClassNameLoc;
922 EndLocation = EndLoc;
923 ConstructorName = ClassType;
926 /// \brief Specify that this unqualified-id was parsed as a
927 /// template-id that names a constructor.
929 /// \param TemplateId the template-id annotation that describes the parsed
930 /// template-id. This UnqualifiedId instance will take ownership of the
931 /// \p TemplateId and will free it on destruction.
932 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
934 /// \brief Specify that this unqualified-id was parsed as a destructor name.
936 /// \param TildeLoc the location of the '~' that introduces the destructor
939 /// \param ClassType the name of the class referred to by the destructor name.
940 void setDestructorName(SourceLocation TildeLoc,
941 ParsedType ClassType,
942 SourceLocation EndLoc) {
943 Kind = IK_DestructorName;
944 StartLocation = TildeLoc;
945 EndLocation = EndLoc;
946 DestructorName = ClassType;
949 /// \brief Specify that this unqualified-id was parsed as a template-id.
951 /// \param TemplateId the template-id annotation that describes the parsed
952 /// template-id. This UnqualifiedId instance will take ownership of the
953 /// \p TemplateId and will free it on destruction.
954 void setTemplateId(TemplateIdAnnotation *TemplateId);
956 /// \brief Return the source range that covers this unqualified-id.
957 SourceRange getSourceRange() const {
958 return SourceRange(StartLocation, EndLocation);
962 /// CachedTokens - A set of tokens that has been cached for later
964 typedef llvm::SmallVector<Token, 4> CachedTokens;
966 /// DeclaratorChunk - One instance of this struct is used for each type in a
967 /// declarator that is parsed.
969 /// This is intended to be a small value object.
970 struct DeclaratorChunk {
972 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
975 /// Loc - The place where this type was defined.
977 /// EndLoc - If valid, the place where this chunck ends.
978 SourceLocation EndLoc;
980 struct TypeInfoCommon {
981 AttributeList *AttrList;
984 struct PointerTypeInfo : TypeInfoCommon {
985 /// The type qualifiers: const/volatile/restrict.
986 unsigned TypeQuals : 3;
988 /// The location of the const-qualifier, if any.
989 unsigned ConstQualLoc;
991 /// The location of the volatile-qualifier, if any.
992 unsigned VolatileQualLoc;
994 /// The location of the restrict-qualifier, if any.
995 unsigned RestrictQualLoc;
1001 struct ReferenceTypeInfo : TypeInfoCommon {
1002 /// The type qualifier: restrict. [GNU] C++ extension
1003 bool HasRestrict : 1;
1004 /// True if this is an lvalue reference, false if it's an rvalue reference.
1010 struct ArrayTypeInfo : TypeInfoCommon {
1011 /// The type qualifiers for the array: const/volatile/restrict.
1012 unsigned TypeQuals : 3;
1014 /// True if this dimension included the 'static' keyword.
1017 /// True if this dimension was [*]. In this case, NumElts is null.
1020 /// This is the size of the array, or null if [] or [*] was specified.
1021 /// Since the parser is multi-purpose, and we don't want to impose a root
1022 /// expression class on all clients, NumElts is untyped.
1028 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1029 /// declarator is parsed. There are two interesting styles of arguments here:
1030 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1031 /// lists will have information about the identifier, but no type information.
1032 /// Parameter type lists will have type info (if the actions module provides
1033 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1035 IdentifierInfo *Ident;
1036 SourceLocation IdentLoc;
1039 /// DefaultArgTokens - When the parameter's default argument
1040 /// cannot be parsed immediately (because it occurs within the
1041 /// declaration of a member function), it will be stored here as a
1042 /// sequence of tokens to be parsed once the class definition is
1043 /// complete. Non-NULL indicates that there is a default argument.
1044 CachedTokens *DefaultArgTokens;
1047 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1049 CachedTokens *DefArgTokens = 0)
1050 : Ident(ident), IdentLoc(iloc), Param(param),
1051 DefaultArgTokens(DefArgTokens) {}
1054 struct TypeAndRange {
1059 struct FunctionTypeInfo : TypeInfoCommon {
1060 /// hasPrototype - This is true if the function had at least one typed
1061 /// argument. If the function is () or (a,b,c), then it has no prototype,
1062 /// and is treated as a K&R-style function.
1063 unsigned hasPrototype : 1;
1065 /// isVariadic - If this function has a prototype, and if that
1066 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1067 /// contains the location of the ellipsis.
1068 unsigned isVariadic : 1;
1070 /// \brief Whether the ref-qualifier (if any) is an lvalue reference.
1071 /// Otherwise, it's an rvalue reference.
1072 unsigned RefQualifierIsLValueRef : 1;
1074 /// The type qualifiers: const/volatile/restrict.
1075 /// The qualifier bitmask values are the same as in QualType.
1076 unsigned TypeQuals : 3;
1078 /// ExceptionSpecType - An ExceptionSpecificationType value.
1079 unsigned ExceptionSpecType : 3;
1081 /// DeleteArgInfo - If this is true, we need to delete[] ArgInfo.
1082 unsigned DeleteArgInfo : 1;
1084 /// When isVariadic is true, the location of the ellipsis in the source.
1085 unsigned EllipsisLoc;
1087 /// NumArgs - This is the number of formal arguments provided for the
1091 /// NumExceptions - This is the number of types in the dynamic-exception-
1092 /// decl, if the function has one.
1093 unsigned NumExceptions;
1095 /// \brief The location of the ref-qualifier, if any.
1097 /// If this is an invalid location, there is no ref-qualifier.
1098 unsigned RefQualifierLoc;
1100 /// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
1102 unsigned MutableLoc;
1104 /// \brief When ExceptionSpecType isn't EST_None or EST_Delayed, the
1105 /// location of the keyword introducing the spec.
1106 unsigned ExceptionSpecLoc;
1108 /// ArgInfo - This is a pointer to a new[]'d array of ParamInfo objects that
1109 /// describe the arguments for this function declarator. This is null if
1110 /// there are no arguments specified.
1114 /// \brief Pointer to a new[]'d array of TypeAndRange objects that
1115 /// contain the types in the function's dynamic exception specification
1116 /// and their locations, if there is one.
1117 TypeAndRange *Exceptions;
1119 /// \brief Pointer to the expression in the noexcept-specifier of this
1120 /// function, if it has one.
1124 /// TrailingReturnType - If this isn't null, it's the trailing return type
1125 /// specified. This is actually a ParsedType, but stored as void* to
1126 /// allow union storage.
1127 void *TrailingReturnType;
1129 /// freeArgs - reset the argument list to having zero arguments. This is
1130 /// used in various places for error recovery.
1132 if (DeleteArgInfo) {
1134 DeleteArgInfo = false;
1142 if (getExceptionSpecType() == EST_Dynamic)
1143 delete[] Exceptions;
1146 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1147 /// like "void foo(a,b,c)". In a function definition, this will be followed
1148 /// by the argument type definitions.
1149 bool isKNRPrototype() const {
1150 return !hasPrototype && NumArgs != 0;
1153 SourceLocation getEllipsisLoc() const {
1154 return SourceLocation::getFromRawEncoding(EllipsisLoc);
1156 SourceLocation getExceptionSpecLoc() const {
1157 return SourceLocation::getFromRawEncoding(ExceptionSpecLoc);
1160 /// \brief Retrieve the location of the ref-qualifier, if any.
1161 SourceLocation getRefQualifierLoc() const {
1162 return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1165 /// \brief Retrieve the location of the 'mutable' qualifier, if any.
1166 SourceLocation getMutableLoc() const {
1167 return SourceLocation::getFromRawEncoding(MutableLoc);
1170 /// \brief Determine whether this function declaration contains a
1172 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1174 /// \brief Determine whether this lambda-declarator contains a 'mutable'
1176 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1178 /// \brief Get the type of exception specification this function has.
1179 ExceptionSpecificationType getExceptionSpecType() const {
1180 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1184 struct BlockPointerTypeInfo : TypeInfoCommon {
1185 /// For now, sema will catch these as invalid.
1186 /// The type qualifiers: const/volatile/restrict.
1187 unsigned TypeQuals : 3;
1193 struct MemberPointerTypeInfo : TypeInfoCommon {
1194 /// The type qualifiers: const/volatile/restrict.
1195 unsigned TypeQuals : 3;
1196 // CXXScopeSpec has a constructor, so it can't be a direct member.
1197 // So we need some pointer-aligned storage and a bit of trickery.
1200 char Mem[sizeof(CXXScopeSpec)];
1202 CXXScopeSpec &Scope() {
1203 return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
1205 const CXXScopeSpec &Scope() const {
1206 return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
1209 Scope().~CXXScopeSpec();
1214 TypeInfoCommon Common;
1215 PointerTypeInfo Ptr;
1216 ReferenceTypeInfo Ref;
1218 FunctionTypeInfo Fun;
1219 BlockPointerTypeInfo Cls;
1220 MemberPointerTypeInfo Mem;
1225 default: assert(0 && "Unknown decl type!");
1226 case DeclaratorChunk::Function: return Fun.destroy();
1227 case DeclaratorChunk::Pointer: return Ptr.destroy();
1228 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1229 case DeclaratorChunk::Reference: return Ref.destroy();
1230 case DeclaratorChunk::Array: return Arr.destroy();
1231 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1232 case DeclaratorChunk::Paren: return;
1236 /// getAttrs - If there are attributes applied to this declaratorchunk, return
1238 const AttributeList *getAttrs() const {
1239 return Common.AttrList;
1242 AttributeList *&getAttrListRef() {
1243 return Common.AttrList;
1246 /// getPointer - Return a DeclaratorChunk for a pointer.
1248 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1249 SourceLocation ConstQualLoc,
1250 SourceLocation VolatileQualLoc,
1251 SourceLocation RestrictQualLoc) {
1255 I.Ptr.TypeQuals = TypeQuals;
1256 I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
1257 I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1258 I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1263 /// getReference - Return a DeclaratorChunk for a reference.
1265 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1270 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1271 I.Ref.LValueRef = lvalue;
1276 /// getArray - Return a DeclaratorChunk for an array.
1278 static DeclaratorChunk getArray(unsigned TypeQuals,
1279 bool isStatic, bool isStar, Expr *NumElts,
1280 SourceLocation LBLoc, SourceLocation RBLoc) {
1286 I.Arr.TypeQuals = TypeQuals;
1287 I.Arr.hasStatic = isStatic;
1288 I.Arr.isStar = isStar;
1289 I.Arr.NumElts = NumElts;
1293 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1294 /// "TheDeclarator" is the declarator that this will be added to.
1295 static DeclaratorChunk getFunction(bool hasProto, bool isVariadic,
1296 SourceLocation EllipsisLoc,
1297 ParamInfo *ArgInfo, unsigned NumArgs,
1299 bool RefQualifierIsLvalueRef,
1300 SourceLocation RefQualifierLoc,
1301 SourceLocation MutableLoc,
1302 ExceptionSpecificationType ESpecType,
1303 SourceLocation ESpecLoc,
1304 ParsedType *Exceptions,
1305 SourceRange *ExceptionRanges,
1306 unsigned NumExceptions,
1308 SourceLocation LocalRangeBegin,
1309 SourceLocation LocalRangeEnd,
1310 Declarator &TheDeclarator,
1311 ParsedType TrailingReturnType =
1314 /// getBlockPointer - Return a DeclaratorChunk for a block.
1316 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1317 SourceLocation Loc) {
1319 I.Kind = BlockPointer;
1321 I.Cls.TypeQuals = TypeQuals;
1326 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1328 SourceLocation Loc) {
1330 I.Kind = MemberPointer;
1332 I.Mem.TypeQuals = TypeQuals;
1334 new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
1338 /// getParen - Return a DeclaratorChunk for a paren.
1340 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1341 SourceLocation RParenLoc) {
1345 I.EndLoc = RParenLoc;
1346 I.Common.AttrList = 0;
1352 /// Declarator - Information about one declarator, including the parsed type
1353 /// information and the identifier. When the declarator is fully formed, this
1354 /// is turned into the appropriate Decl object.
1356 /// Declarators come in two types: normal declarators and abstract declarators.
1357 /// Abstract declarators are used when parsing types, and don't have an
1358 /// identifier. Normal declarators do have ID's.
1360 /// Instances of this class should be a transient object that lives on the
1361 /// stack, not objects that are allocated in large quantities on the heap.
1365 FileContext, // File scope declaration.
1366 PrototypeContext, // Within a function prototype.
1367 ObjCPrototypeContext,// Within a method prototype.
1368 KNRTypeListContext, // K&R type definition list for formals.
1369 TypeNameContext, // Abstract declarator for types.
1370 MemberContext, // Struct/Union field.
1371 BlockContext, // Declaration within a block in a function.
1372 ForContext, // Declaration within first part of a for loop.
1373 ConditionContext, // Condition declaration in a C++ if/switch/while/for.
1374 TemplateParamContext,// Within a template parameter list.
1375 CXXNewContext, // C++ new-expression.
1376 CXXCatchContext, // C++ catch exception-declaration
1377 ObjCCatchContext, // Objective-C catch exception-declaration
1378 BlockLiteralContext, // Block literal declarator.
1379 TemplateTypeArgContext, // Template type argument.
1380 AliasDeclContext, // C++0x alias-declaration.
1381 AliasTemplateContext // C++0x alias-declaration template.
1390 /// Context - Where we are parsing this declarator.
1394 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1395 /// parsed. This is pushed from the identifier out, which means that element
1396 /// #0 will be the most closely bound to the identifier, and
1397 /// DeclTypeInfo.back() will be the least closely bound.
1398 llvm::SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1400 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1401 bool InvalidType : 1;
1403 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1404 bool GroupingParens : 1;
1406 /// Attrs - Attributes.
1407 ParsedAttributes Attrs;
1409 /// AsmLabel - The asm label, if specified.
1412 /// InlineParams - This is a local array used for the first function decl
1413 /// chunk to avoid going to the heap for the common case when we have one
1414 /// function chunk in the declarator.
1415 DeclaratorChunk::ParamInfo InlineParams[16];
1416 bool InlineParamsUsed;
1418 /// Extension - true if the declaration is preceded by __extension__.
1421 /// \brief If provided, the source location of the ellipsis used to describe
1422 /// this declarator as a parameter pack.
1423 SourceLocation EllipsisLoc;
1425 friend struct DeclaratorChunk;
1428 Declarator(const DeclSpec &ds, TheContext C)
1429 : DS(ds), Range(ds.getSourceRange()), Context(C),
1430 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1431 GroupingParens(false), Attrs(ds.getAttributePool().getFactory()),
1432 AsmLabel(0), InlineParamsUsed(false), Extension(false) {
1439 /// getDeclSpec - Return the declaration-specifier that this declarator was
1441 const DeclSpec &getDeclSpec() const { return DS; }
1443 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1444 /// should be used with extreme care: declspecs can often be shared between
1445 /// multiple declarators, so mutating the DeclSpec affects all of the
1446 /// Declarators. This should only be done when the declspec is known to not
1447 /// be shared or when in error recovery etc.
1448 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1450 AttributePool &getAttributePool() const {
1451 return Attrs.getPool();
1454 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1455 /// nested-name-specifier) that is part of the declarator-id.
1456 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1457 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1459 /// \brief Retrieve the name specified by this declarator.
1460 UnqualifiedId &getName() { return Name; }
1462 TheContext getContext() const { return Context; }
1464 bool isPrototypeContext() const {
1465 return (Context == PrototypeContext || Context == ObjCPrototypeContext);
1468 /// getSourceRange - Get the source range that spans this declarator.
1469 const SourceRange &getSourceRange() const { return Range; }
1471 void SetSourceRange(SourceRange R) { Range = R; }
1472 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1474 void SetRangeBegin(SourceLocation Loc) {
1475 if (!Loc.isInvalid())
1476 Range.setBegin(Loc);
1478 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1479 void SetRangeEnd(SourceLocation Loc) {
1480 if (!Loc.isInvalid())
1483 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1484 /// given declspec, unless its location is invalid. Adopts the range start if
1485 /// the current range start is invalid.
1486 void ExtendWithDeclSpec(const DeclSpec &DS) {
1487 const SourceRange &SR = DS.getSourceRange();
1488 if (Range.getBegin().isInvalid())
1489 Range.setBegin(SR.getBegin());
1490 if (!SR.getEnd().isInvalid())
1491 Range.setEnd(SR.getEnd());
1494 /// clear - Reset the contents of this Declarator.
1498 Range = DS.getSourceRange();
1500 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1501 DeclTypeInfo[i].destroy();
1502 DeclTypeInfo.clear();
1505 InlineParamsUsed = false;
1508 /// mayOmitIdentifier - Return true if the identifier is either optional or
1509 /// not allowed. This is true for typenames, prototypes, and template
1510 /// parameter lists.
1511 bool mayOmitIdentifier() const {
1514 case KNRTypeListContext:
1518 case ConditionContext:
1521 case TypeNameContext:
1522 case AliasDeclContext:
1523 case AliasTemplateContext:
1524 case PrototypeContext:
1525 case ObjCPrototypeContext:
1526 case TemplateParamContext:
1528 case CXXCatchContext:
1529 case ObjCCatchContext:
1530 case BlockLiteralContext:
1531 case TemplateTypeArgContext:
1534 llvm_unreachable("unknown context kind!");
1537 /// mayHaveIdentifier - Return true if the identifier is either optional or
1538 /// required. This is true for normal declarators and prototypes, but not
1540 bool mayHaveIdentifier() const {
1543 case KNRTypeListContext:
1547 case ConditionContext:
1548 case PrototypeContext:
1549 case TemplateParamContext:
1550 case CXXCatchContext:
1551 case ObjCCatchContext:
1554 case TypeNameContext:
1556 case AliasDeclContext:
1557 case AliasTemplateContext:
1558 case ObjCPrototypeContext:
1559 case BlockLiteralContext:
1560 case TemplateTypeArgContext:
1563 llvm_unreachable("unknown context kind!");
1566 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
1567 /// followed by a C++ direct initializer, e.g. "int x(1);".
1568 bool mayBeFollowedByCXXDirectInit() const {
1569 if (hasGroupingParens()) return false;
1577 case KNRTypeListContext:
1579 case ConditionContext:
1580 case PrototypeContext:
1581 case ObjCPrototypeContext:
1582 case TemplateParamContext:
1583 case CXXCatchContext:
1584 case ObjCCatchContext:
1585 case TypeNameContext:
1587 case AliasDeclContext:
1588 case AliasTemplateContext:
1589 case BlockLiteralContext:
1590 case TemplateTypeArgContext:
1593 llvm_unreachable("unknown context kind!");
1596 /// isPastIdentifier - Return true if we have parsed beyond the point where
1598 bool isPastIdentifier() const { return Name.isValid(); }
1600 /// hasName - Whether this declarator has a name, which might be an
1601 /// identifier (accessible via getIdentifier()) or some kind of
1602 /// special C++ name (constructor, destructor, etc.).
1603 bool hasName() const {
1604 return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
1607 IdentifierInfo *getIdentifier() const {
1608 if (Name.getKind() == UnqualifiedId::IK_Identifier)
1609 return Name.Identifier;
1613 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
1615 /// \brief Set the name of this declarator to be the given identifier.
1616 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
1617 Name.setIdentifier(Id, IdLoc);
1620 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
1621 /// EndLoc, which should be the last token of the chunk.
1622 void AddTypeInfo(const DeclaratorChunk &TI,
1623 ParsedAttributes &attrs,
1624 SourceLocation EndLoc) {
1625 DeclTypeInfo.push_back(TI);
1626 DeclTypeInfo.back().getAttrListRef() = attrs.getList();
1627 getAttributePool().takeAllFrom(attrs.getPool());
1629 if (!EndLoc.isInvalid())
1630 SetRangeEnd(EndLoc);
1633 /// AddInnermostTypeInfo - Add a new innermost chunk to this declarator.
1634 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
1635 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
1638 /// getNumTypeObjects() - Return the number of types applied to this
1640 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
1642 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
1643 /// closest to the identifier.
1644 const DeclaratorChunk &getTypeObject(unsigned i) const {
1645 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1646 return DeclTypeInfo[i];
1648 DeclaratorChunk &getTypeObject(unsigned i) {
1649 assert(i < DeclTypeInfo.size() && "Invalid type chunk");
1650 return DeclTypeInfo[i];
1653 void DropFirstTypeObject()
1655 assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
1656 DeclTypeInfo.front().destroy();
1657 DeclTypeInfo.erase(DeclTypeInfo.begin());
1660 /// isArrayOfUnknownBound - This method returns true if the declarator
1661 /// is a declarator for an array of unknown bound (looking through
1663 bool isArrayOfUnknownBound() const {
1664 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1665 switch (DeclTypeInfo[i].Kind) {
1666 case DeclaratorChunk::Paren:
1668 case DeclaratorChunk::Function:
1669 case DeclaratorChunk::Pointer:
1670 case DeclaratorChunk::Reference:
1671 case DeclaratorChunk::BlockPointer:
1672 case DeclaratorChunk::MemberPointer:
1674 case DeclaratorChunk::Array:
1675 return !DeclTypeInfo[i].Arr.NumElts;
1677 llvm_unreachable("Invalid type chunk");
1683 /// isFunctionDeclarator - This method returns true if the declarator
1684 /// is a function declarator (looking through parentheses).
1685 /// If true is returned, then the reference type parameter idx is
1686 /// assigned with the index of the declaration chunk.
1687 bool isFunctionDeclarator(unsigned& idx) const {
1688 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
1689 switch (DeclTypeInfo[i].Kind) {
1690 case DeclaratorChunk::Function:
1693 case DeclaratorChunk::Paren:
1695 case DeclaratorChunk::Pointer:
1696 case DeclaratorChunk::Reference:
1697 case DeclaratorChunk::Array:
1698 case DeclaratorChunk::BlockPointer:
1699 case DeclaratorChunk::MemberPointer:
1702 llvm_unreachable("Invalid type chunk");
1708 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
1709 /// this method returns true if the identifier is a function declarator
1710 /// (looking through parentheses).
1711 bool isFunctionDeclarator() const {
1713 return isFunctionDeclarator(index);
1716 /// getFunctionTypeInfo - Retrieves the function type info object
1717 /// (looking through parentheses).
1718 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
1719 assert(isFunctionDeclarator() && "Not a function declarator!");
1721 isFunctionDeclarator(index);
1722 return DeclTypeInfo[index].Fun;
1725 /// getFunctionTypeInfo - Retrieves the function type info object
1726 /// (looking through parentheses).
1727 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
1728 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
1731 /// \brief Determine whether the declaration that will be produced from
1732 /// this declaration will be a function.
1734 /// A declaration can declare a function even if the declarator itself
1735 /// isn't a function declarator, if the type specifier refers to a function
1736 /// type. This routine checks for both cases.
1737 bool isDeclarationOfFunction() const;
1739 /// takeAttributes - Takes attributes from the given parsed-attributes
1740 /// set and add them to this declarator.
1742 /// These examples both add 3 attributes to "var":
1743 /// short int var __attribute__((aligned(16),common,deprecated));
1744 /// short int x, __attribute__((aligned(16)) var
1745 /// __attribute__((common,deprecated));
1747 /// Also extends the range of the declarator.
1748 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
1749 Attrs.takeAllFrom(attrs);
1751 if (!lastLoc.isInvalid())
1752 SetRangeEnd(lastLoc);
1755 const AttributeList *getAttributes() const { return Attrs.getList(); }
1756 AttributeList *getAttributes() { return Attrs.getList(); }
1758 AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
1760 /// hasAttributes - do we contain any attributes?
1761 bool hasAttributes() const {
1762 if (getAttributes() || getDeclSpec().hasAttributes()) return true;
1763 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
1764 if (getTypeObject(i).getAttrs())
1769 void setAsmLabel(Expr *E) { AsmLabel = E; }
1770 Expr *getAsmLabel() const { return AsmLabel; }
1772 void setExtension(bool Val = true) { Extension = Val; }
1773 bool getExtension() const { return Extension; }
1775 void setInvalidType(bool Val = true) { InvalidType = Val; }
1776 bool isInvalidType() const {
1777 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
1780 void setGroupingParens(bool flag) { GroupingParens = flag; }
1781 bool hasGroupingParens() const { return GroupingParens; }
1783 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
1784 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1785 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
1788 /// FieldDeclarator - This little struct is used to capture information about
1789 /// structure field declarators, which is basically just a bitfield size.
1790 struct FieldDeclarator {
1793 explicit FieldDeclarator(DeclSpec &DS) : D(DS, Declarator::MemberContext) {
1798 /// VirtSpecifiers - Represents a C++0x virt-specifier-seq.
1799 class VirtSpecifiers {
1807 VirtSpecifiers() : Specifiers(0) { }
1809 bool SetSpecifier(Specifier VS, SourceLocation Loc,
1810 const char *&PrevSpec);
1812 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
1813 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
1815 bool isFinalSpecified() const { return Specifiers & VS_Final; }
1816 SourceLocation getFinalLoc() const { return VS_finalLoc; }
1818 void clear() { Specifiers = 0; }
1820 static const char *getSpecifierName(Specifier VS);
1822 SourceLocation getLastLocation() const { return LastLocation; }
1825 unsigned Specifiers;
1827 SourceLocation VS_overrideLoc, VS_finalLoc;
1828 SourceLocation LastLocation;
1831 } // end namespace clang