1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
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 implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Parse/Scope.h"
17 #include "clang/Parse/Template.h"
18 #include "RAIIObjectsForParser.h"
19 #include "llvm/ADT/SmallSet.h"
20 using namespace clang;
22 //===----------------------------------------------------------------------===//
23 // C99 6.7: Declarations.
24 //===----------------------------------------------------------------------===//
27 /// type-name: [C99 6.7.6]
28 /// specifier-qualifier-list abstract-declarator[opt]
30 /// Called type-id in C++.
31 Action::TypeResult Parser::ParseTypeName(SourceRange *Range) {
32 // Parse the common declaration-specifiers piece.
34 ParseSpecifierQualifierList(DS);
36 // Parse the abstract-declarator, if present.
37 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
38 ParseDeclarator(DeclaratorInfo);
40 *Range = DeclaratorInfo.getSourceRange();
42 if (DeclaratorInfo.isInvalidType())
45 return Actions.ActOnTypeName(CurScope, DeclaratorInfo);
48 /// ParseGNUAttributes - Parse a non-empty attributes list.
52 /// attributes attribute
55 /// '__attribute__' '(' '(' attribute-list ')' ')'
57 /// [GNU] attribute-list:
59 /// attribute_list ',' attrib
64 /// attrib-name '(' identifier ')'
65 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
66 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
68 /// [GNU] attrib-name:
74 /// FIXME: The GCC grammar/code for this construct implies we need two
75 /// token lookahead. Comment from gcc: "If they start with an identifier
76 /// which is followed by a comma or close parenthesis, then the arguments
77 /// start with that identifier; otherwise they are an expression list."
79 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
80 /// any attributes that don't work (based on my limited testing). Most
81 /// attributes are very simple in practice. Until we find a bug, I don't see
82 /// a pressing need to implement the 2 token lookahead.
84 AttributeList *Parser::ParseGNUAttributes(SourceLocation *EndLoc) {
85 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
87 AttributeList *CurrAttr = 0;
89 while (Tok.is(tok::kw___attribute)) {
91 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
93 SkipUntil(tok::r_paren, true); // skip until ) or ;
96 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
97 SkipUntil(tok::r_paren, true); // skip until ) or ;
100 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
101 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
102 Tok.is(tok::comma)) {
104 if (Tok.is(tok::comma)) {
105 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
109 // we have an identifier or declaration specifier (const, int, etc.)
110 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
111 SourceLocation AttrNameLoc = ConsumeToken();
113 // check if we have a "paramterized" attribute
114 if (Tok.is(tok::l_paren)) {
115 ConsumeParen(); // ignore the left paren loc for now
117 if (Tok.is(tok::identifier)) {
118 IdentifierInfo *ParmName = Tok.getIdentifierInfo();
119 SourceLocation ParmLoc = ConsumeToken();
121 if (Tok.is(tok::r_paren)) {
122 // __attribute__(( mode(byte) ))
123 ConsumeParen(); // ignore the right paren loc for now
124 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
125 ParmName, ParmLoc, 0, 0, CurrAttr);
126 } else if (Tok.is(tok::comma)) {
128 // __attribute__(( format(printf, 1, 2) ))
129 ExprVector ArgExprs(Actions);
130 bool ArgExprsOk = true;
132 // now parse the non-empty comma separated list of expressions
134 OwningExprResult ArgExpr(ParseAssignmentExpression());
135 if (ArgExpr.isInvalid()) {
137 SkipUntil(tok::r_paren);
140 ArgExprs.push_back(ArgExpr.release());
142 if (Tok.isNot(tok::comma))
144 ConsumeToken(); // Eat the comma, move to the next argument
146 if (ArgExprsOk && Tok.is(tok::r_paren)) {
147 ConsumeParen(); // ignore the right paren loc for now
148 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
149 AttrNameLoc, ParmName, ParmLoc,
150 ArgExprs.take(), ArgExprs.size(),
154 } else { // not an identifier
155 switch (Tok.getKind()) {
157 // parse a possibly empty comma separated list of expressions
158 // __attribute__(( nonnull() ))
159 ConsumeParen(); // ignore the right paren loc for now
160 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
161 0, SourceLocation(), 0, 0, CurrAttr);
164 case tok::kw_wchar_t:
165 case tok::kw_char16_t:
166 case tok::kw_char32_t:
172 case tok::kw_unsigned:
177 // If it's a builtin type name, eat it and expect a rparen
178 // __attribute__(( vec_type_hint(char) ))
180 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
181 0, SourceLocation(), 0, 0, CurrAttr);
182 if (Tok.is(tok::r_paren))
186 // __attribute__(( aligned(16) ))
187 ExprVector ArgExprs(Actions);
188 bool ArgExprsOk = true;
190 // now parse the list of expressions
192 OwningExprResult ArgExpr(ParseAssignmentExpression());
193 if (ArgExpr.isInvalid()) {
195 SkipUntil(tok::r_paren);
198 ArgExprs.push_back(ArgExpr.release());
200 if (Tok.isNot(tok::comma))
202 ConsumeToken(); // Eat the comma, move to the next argument
205 if (ArgExprsOk && Tok.is(tok::r_paren)) {
206 ConsumeParen(); // ignore the right paren loc for now
207 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
208 AttrNameLoc, 0, SourceLocation(), ArgExprs.take(),
216 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
217 0, SourceLocation(), 0, 0, CurrAttr);
220 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
221 SkipUntil(tok::r_paren, false);
222 SourceLocation Loc = Tok.getLocation();
223 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
224 SkipUntil(tok::r_paren, false);
232 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
234 /// [MS] decl-specifier:
235 /// __declspec ( extended-decl-modifier-seq )
237 /// [MS] extended-decl-modifier-seq:
238 /// extended-decl-modifier[opt]
239 /// extended-decl-modifier extended-decl-modifier-seq
241 AttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) {
242 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
245 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
247 SkipUntil(tok::r_paren, true); // skip until ) or ;
250 while (Tok.getIdentifierInfo()) {
251 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
252 SourceLocation AttrNameLoc = ConsumeToken();
253 if (Tok.is(tok::l_paren)) {
255 // FIXME: This doesn't parse __declspec(property(get=get_func_name))
257 OwningExprResult ArgExpr(ParseAssignmentExpression());
258 if (!ArgExpr.isInvalid()) {
259 ExprTy* ExprList = ArgExpr.take();
260 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
261 SourceLocation(), &ExprList, 1,
264 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
265 SkipUntil(tok::r_paren, false);
267 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
268 0, SourceLocation(), 0, 0, CurrAttr, true);
271 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
272 SkipUntil(tok::r_paren, false);
276 AttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) {
277 // Treat these like attributes
278 // FIXME: Allow Sema to distinguish between these and real attributes!
279 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
280 Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___ptr64) ||
281 Tok.is(tok::kw___w64)) {
282 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
283 SourceLocation AttrNameLoc = ConsumeToken();
284 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
285 // FIXME: Support these properly!
287 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
288 SourceLocation(), 0, 0, CurrAttr, true);
293 /// ParseDeclaration - Parse a full 'declaration', which consists of
294 /// declaration-specifiers, some number of declarators, and a semicolon.
295 /// 'Context' should be a Declarator::TheContext value. This returns the
296 /// location of the semicolon in DeclEnd.
298 /// declaration: [C99 6.7]
299 /// block-declaration ->
300 /// simple-declaration
302 /// [C++] template-declaration
303 /// [C++] namespace-definition
304 /// [C++] using-directive
305 /// [C++] using-declaration
306 /// [C++0x] static_assert-declaration
307 /// others... [FIXME]
309 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
310 SourceLocation &DeclEnd,
311 CXX0XAttributeList Attr) {
312 DeclPtrTy SingleDecl;
313 switch (Tok.getKind()) {
314 case tok::kw_template:
317 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
319 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
321 case tok::kw_namespace:
323 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
325 SingleDecl = ParseNamespace(Context, DeclEnd);
328 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd, Attr);
330 case tok::kw_static_assert:
332 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
334 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
337 return ParseSimpleDeclaration(Context, DeclEnd, Attr.AttrList);
340 // This routine returns a DeclGroup, if the thing we parsed only contains a
341 // single decl, convert it now.
342 return Actions.ConvertDeclToDeclGroup(SingleDecl);
345 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
346 /// declaration-specifiers init-declarator-list[opt] ';'
347 ///[C90/C++]init-declarator-list ';' [TODO]
348 /// [OMP] threadprivate-directive [TODO]
350 /// If RequireSemi is false, this does not check for a ';' at the end of the
352 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context,
353 SourceLocation &DeclEnd,
354 AttributeList *Attr) {
355 // Parse the common declaration-specifiers piece.
356 ParsingDeclSpec DS(*this);
358 DS.AddAttributes(Attr);
359 ParseDeclarationSpecifiers(DS);
361 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
362 // declaration-specifiers init-declarator-list[opt] ';'
363 if (Tok.is(tok::semi)) {
365 DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
366 DS.complete(TheDecl);
367 return Actions.ConvertDeclToDeclGroup(TheDecl);
370 DeclGroupPtrTy DG = ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false,
375 /// ParseDeclGroup - Having concluded that this is either a function
376 /// definition or a group of object declarations, actually parse the
378 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
380 bool AllowFunctionDefinitions,
381 SourceLocation *DeclEnd) {
382 // Parse the first declarator.
383 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
386 // Bail out if the first declarator didn't seem well-formed.
387 if (!D.hasName() && !D.mayOmitIdentifier()) {
388 // Skip until ; or }.
389 SkipUntil(tok::r_brace, true, true);
390 if (Tok.is(tok::semi))
392 return DeclGroupPtrTy();
395 if (AllowFunctionDefinitions && D.isFunctionDeclarator()) {
396 if (isDeclarationAfterDeclarator()) {
397 // Fall though. We have to check this first, though, because
398 // __attribute__ might be the start of a function definition in
400 } else if (isStartOfFunctionDefinition()) {
401 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
402 Diag(Tok, diag::err_function_declared_typedef);
404 // Recover by treating the 'typedef' as spurious.
405 DS.ClearStorageClassSpecs();
408 DeclPtrTy TheDecl = ParseFunctionDefinition(D);
409 return Actions.ConvertDeclToDeclGroup(TheDecl);
411 Diag(Tok, diag::err_expected_fn_body);
412 SkipUntil(tok::semi);
413 return DeclGroupPtrTy();
417 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
418 DeclPtrTy FirstDecl = ParseDeclarationAfterDeclarator(D);
419 D.complete(FirstDecl);
421 DeclsInGroup.push_back(FirstDecl);
423 // If we don't have a comma, it is either the end of the list (a ';') or an
425 while (Tok.is(tok::comma)) {
426 // Consume the comma.
429 // Parse the next declarator.
432 // Accept attributes in an init-declarator. In the first declarator in a
433 // declaration, these would be part of the declspec. In subsequent
434 // declarators, they become part of the declarator itself, so that they
435 // don't apply to declarators after *this* one. Examples:
436 // short __attribute__((common)) var; -> declspec
437 // short var __attribute__((common)); -> declarator
438 // short x, __attribute__((common)) var; -> declarator
439 if (Tok.is(tok::kw___attribute)) {
441 AttributeList *AttrList = ParseGNUAttributes(&Loc);
442 D.AddAttributes(AttrList, Loc);
447 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D);
448 D.complete(ThisDecl);
450 DeclsInGroup.push_back(ThisDecl);
454 *DeclEnd = Tok.getLocation();
456 if (Context != Declarator::ForContext &&
457 ExpectAndConsume(tok::semi,
458 Context == Declarator::FileContext
459 ? diag::err_invalid_token_after_toplevel_declarator
460 : diag::err_expected_semi_declaration)) {
461 SkipUntil(tok::r_brace, true, true);
462 if (Tok.is(tok::semi))
466 return Actions.FinalizeDeclaratorGroup(CurScope, DS,
468 DeclsInGroup.size());
471 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
472 /// declarator'. This method parses the remainder of the declaration
473 /// (including any attributes or initializer, among other things) and
474 /// finalizes the declaration.
476 /// init-declarator: [C99 6.7]
478 /// declarator '=' initializer
479 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
480 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
481 /// [C++] declarator initializer[opt]
483 /// [C++] initializer:
484 /// [C++] '=' initializer-clause
485 /// [C++] '(' expression-list ')'
486 /// [C++0x] '=' 'default' [TODO]
487 /// [C++0x] '=' 'delete'
489 /// According to the standard grammar, =default and =delete are function
490 /// definitions, but that definitely doesn't fit with the parser here.
492 Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D,
493 const ParsedTemplateInfo &TemplateInfo) {
494 // If a simple-asm-expr is present, parse it.
495 if (Tok.is(tok::kw_asm)) {
497 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
498 if (AsmLabel.isInvalid()) {
499 SkipUntil(tok::semi, true, true);
503 D.setAsmLabel(AsmLabel.release());
507 // If attributes are present, parse them.
508 if (Tok.is(tok::kw___attribute)) {
510 AttributeList *AttrList = ParseGNUAttributes(&Loc);
511 D.AddAttributes(AttrList, Loc);
514 // Inform the current actions module that we just parsed this declarator.
516 switch (TemplateInfo.Kind) {
517 case ParsedTemplateInfo::NonTemplate:
518 ThisDecl = Actions.ActOnDeclarator(CurScope, D);
521 case ParsedTemplateInfo::Template:
522 case ParsedTemplateInfo::ExplicitSpecialization:
523 ThisDecl = Actions.ActOnTemplateDeclarator(CurScope,
524 Action::MultiTemplateParamsArg(Actions,
525 TemplateInfo.TemplateParams->data(),
526 TemplateInfo.TemplateParams->size()),
530 case ParsedTemplateInfo::ExplicitInstantiation: {
531 Action::DeclResult ThisRes
532 = Actions.ActOnExplicitInstantiation(CurScope,
533 TemplateInfo.ExternLoc,
534 TemplateInfo.TemplateLoc,
536 if (ThisRes.isInvalid()) {
537 SkipUntil(tok::semi, true, true);
541 ThisDecl = ThisRes.get();
546 // Parse declarator '=' initializer.
547 if (Tok.is(tok::equal)) {
549 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
550 SourceLocation DelLoc = ConsumeToken();
551 Actions.SetDeclDeleted(ThisDecl, DelLoc);
553 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
555 Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
558 OwningExprResult Init(ParseInitializer());
560 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
561 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
565 if (Init.isInvalid()) {
566 SkipUntil(tok::semi, true, true);
569 Actions.AddInitializerToDecl(ThisDecl, move(Init));
571 } else if (Tok.is(tok::l_paren)) {
572 // Parse C++ direct initializer: '(' expression-list ')'
573 SourceLocation LParenLoc = ConsumeParen();
574 ExprVector Exprs(Actions);
575 CommaLocsTy CommaLocs;
577 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
579 Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
582 if (ParseExpressionList(Exprs, CommaLocs)) {
583 SkipUntil(tok::r_paren);
585 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
586 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
591 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
593 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
594 "Unexpected number of commas!");
596 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
597 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
601 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
603 CommaLocs.data(), RParenLoc);
606 bool TypeContainsUndeducedAuto =
607 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
608 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto);
614 /// ParseSpecifierQualifierList
615 /// specifier-qualifier-list:
616 /// type-specifier specifier-qualifier-list[opt]
617 /// type-qualifier specifier-qualifier-list[opt]
618 /// [GNU] attributes specifier-qualifier-list[opt]
620 void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
621 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
622 /// parse declaration-specifiers and complain about extra stuff.
623 ParseDeclarationSpecifiers(DS);
625 // Validate declspec for type-name.
626 unsigned Specs = DS.getParsedSpecifiers();
627 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
629 Diag(Tok, diag::err_typename_requires_specqual);
631 // Issue diagnostic and remove storage class if present.
632 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
633 if (DS.getStorageClassSpecLoc().isValid())
634 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
636 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
637 DS.ClearStorageClassSpecs();
640 // Issue diagnostic and remove function specfier if present.
641 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
642 if (DS.isInlineSpecified())
643 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
644 if (DS.isVirtualSpecified())
645 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
646 if (DS.isExplicitSpecified())
647 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
648 DS.ClearFunctionSpecs();
652 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
653 /// specified token is valid after the identifier in a declarator which
654 /// immediately follows the declspec. For example, these things are valid:
656 /// int x [ 4]; // direct-declarator
657 /// int x ( int y); // direct-declarator
658 /// int(int x ) // direct-declarator
659 /// int x ; // simple-declaration
660 /// int x = 17; // init-declarator-list
661 /// int x , y; // init-declarator-list
662 /// int x __asm__ ("foo"); // init-declarator-list
663 /// int x : 4; // struct-declarator
664 /// int x { 5}; // C++'0x unified initializers
666 /// This is not, because 'x' does not immediately follow the declspec (though
667 /// ')' happens to be valid anyway).
670 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
671 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
672 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
673 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
677 /// ParseImplicitInt - This method is called when we have an non-typename
678 /// identifier in a declspec (which normally terminates the decl spec) when
679 /// the declspec has no type specifier. In this case, the declspec is either
680 /// malformed or is "implicit int" (in K&R and C89).
682 /// This method handles diagnosing this prettily and returns false if the
683 /// declspec is done being processed. If it recovers and thinks there may be
684 /// other pieces of declspec after it, it returns true.
686 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
687 const ParsedTemplateInfo &TemplateInfo,
688 AccessSpecifier AS) {
689 assert(Tok.is(tok::identifier) && "should have identifier");
691 SourceLocation Loc = Tok.getLocation();
692 // If we see an identifier that is not a type name, we normally would
693 // parse it as the identifer being declared. However, when a typename
694 // is typo'd or the definition is not included, this will incorrectly
695 // parse the typename as the identifier name and fall over misparsing
696 // later parts of the diagnostic.
698 // As such, we try to do some look-ahead in cases where this would
699 // otherwise be an "implicit-int" case to see if this is invalid. For
700 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
701 // an identifier with implicit int, we'd get a parse error because the
702 // next token is obviously invalid for a type. Parse these as a case
703 // with an invalid type specifier.
704 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
706 // Since we know that this either implicit int (which is rare) or an
707 // error, we'd do lookahead to try to do better recovery.
708 if (isValidAfterIdentifierInDeclarator(NextToken())) {
709 // If this token is valid for implicit int, e.g. "static x = 4", then
710 // we just avoid eating the identifier, so it will be parsed as the
711 // identifier in the declarator.
715 // Otherwise, if we don't consume this token, we are going to emit an
716 // error anyway. Try to recover from various common problems. Check
717 // to see if this was a reference to a tag name without a tag specified.
718 // This is a common problem in C (saying 'foo' instead of 'struct foo').
720 // C++ doesn't need this, and isTagName doesn't take SS.
722 const char *TagName = 0;
723 tok::TokenKind TagKind = tok::unknown;
725 switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
727 case DeclSpec::TST_enum: TagName="enum" ;TagKind=tok::kw_enum ;break;
728 case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
729 case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
730 case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
734 Diag(Loc, diag::err_use_of_tag_name_without_tag)
735 << Tok.getIdentifierInfo() << TagName
736 << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName);
738 // Parse this as a tag as if the missing tag were present.
739 if (TagKind == tok::kw_enum)
740 ParseEnumSpecifier(Loc, DS, AS);
742 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
747 // This is almost certainly an invalid type name. Let the action emit a
748 // diagnostic and attempt to recover.
749 Action::TypeTy *T = 0;
750 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
752 // The action emitted a diagnostic, so we don't have to.
754 // The action has suggested that the type T could be used. Set that as
755 // the type in the declaration specifiers, consume the would-be type
756 // name token, and we're done.
757 const char *PrevSpec;
759 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
761 DS.SetRangeEnd(Tok.getLocation());
764 // There may be other declaration specifiers after this.
768 // Fall through; the action had no suggestion for us.
770 // The action did not emit a diagnostic, so emit one now.
772 if (SS) R = SS->getRange();
773 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
776 // Mark this as an error.
777 const char *PrevSpec;
779 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
780 DS.SetRangeEnd(Tok.getLocation());
783 // TODO: Could inject an invalid typedef decl in an enclosing scope to
784 // avoid rippling error messages on subsequent uses of the same type,
785 // could be useful if #include was forgotten.
789 /// ParseDeclarationSpecifiers
790 /// declaration-specifiers: [C99 6.7]
791 /// storage-class-specifier declaration-specifiers[opt]
792 /// type-specifier declaration-specifiers[opt]
793 /// [C99] function-specifier declaration-specifiers[opt]
794 /// [GNU] attributes declaration-specifiers[opt]
796 /// storage-class-specifier: [C99 6.7.1]
804 /// function-specifier: [C99 6.7.4]
808 /// 'friend': [C++ dcl.friend]
809 /// 'constexpr': [C++0x dcl.constexpr]
812 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
813 const ParsedTemplateInfo &TemplateInfo,
815 DeclSpecContext DSContext) {
816 if (Tok.is(tok::code_completion)) {
817 Actions.CodeCompleteOrdinaryName(CurScope);
821 DS.SetRangeStart(Tok.getLocation());
823 bool isInvalid = false;
824 const char *PrevSpec = 0;
827 SourceLocation Loc = Tok.getLocation();
829 switch (Tok.getKind()) {
832 // If this is not a declaration specifier token, we're done reading decl
833 // specifiers. First verify that DeclSpec's are consistent.
834 DS.Finish(Diags, PP);
837 case tok::coloncolon: // ::foo::bar
838 // Annotate C++ scope specifiers. If we get one, loop.
839 if (TryAnnotateCXXScopeToken(true))
841 goto DoneWithDeclSpec;
843 case tok::annot_cxxscope: {
844 if (DS.hasTypeSpecifier())
845 goto DoneWithDeclSpec;
848 SS.setScopeRep(Tok.getAnnotationValue());
849 SS.setRange(Tok.getAnnotationRange());
851 // We are looking for a qualified typename.
852 Token Next = NextToken();
853 if (Next.is(tok::annot_template_id) &&
854 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
855 ->Kind == TNK_Type_template) {
856 // We have a qualified template-id, e.g., N::A<int>
857 DS.getTypeSpecScope() = SS;
858 ConsumeToken(); // The C++ scope.
859 assert(Tok.is(tok::annot_template_id) &&
860 "ParseOptionalCXXScopeSpecifier not working");
861 AnnotateTemplateIdTokenAsType(&SS);
865 if (Next.is(tok::annot_typename)) {
866 DS.getTypeSpecScope() = SS;
867 ConsumeToken(); // The C++ scope.
868 if (Tok.getAnnotationValue())
869 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
871 Tok.getAnnotationValue());
873 DS.SetTypeSpecError();
874 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
875 ConsumeToken(); // The typename
878 if (Next.isNot(tok::identifier))
879 goto DoneWithDeclSpec;
881 // If the next token is the name of the class type that the C++ scope
882 // denotes, followed by a '(', then this is a constructor declaration.
883 // We're done with the decl-specifiers.
884 if (Actions.isCurrentClassName(*Next.getIdentifierInfo(),
886 GetLookAheadToken(2).is(tok::l_paren))
887 goto DoneWithDeclSpec;
889 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
890 Next.getLocation(), CurScope, &SS);
892 // If the referenced identifier is not a type, then this declspec is
893 // erroneous: We already checked about that it has no type specifier, and
894 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
897 ConsumeToken(); // Eat the scope spec so the identifier is current.
898 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
899 goto DoneWithDeclSpec;
902 DS.getTypeSpecScope() = SS;
903 ConsumeToken(); // The C++ scope.
905 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
910 DS.SetRangeEnd(Tok.getLocation());
911 ConsumeToken(); // The typename.
916 case tok::annot_typename: {
917 if (Tok.getAnnotationValue())
918 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
919 DiagID, Tok.getAnnotationValue());
921 DS.SetTypeSpecError();
922 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
923 ConsumeToken(); // The typename
925 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
926 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
927 // Objective-C interface. If we don't have Objective-C or a '<', this is
928 // just a normal reference to a typedef name.
929 if (!Tok.is(tok::less) || !getLang().ObjC1)
932 SourceLocation LAngleLoc, EndProtoLoc;
933 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
934 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
935 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
936 LAngleLoc, EndProtoLoc);
937 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
938 ProtocolLocs.data(), LAngleLoc);
940 DS.SetRangeEnd(EndProtoLoc);
945 case tok::identifier: {
946 // In C++, check to see if this is a scope specifier like foo::bar::, if
947 // so handle it as such. This is important for ctor parsing.
948 if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true))
951 // This identifier can only be a typedef name if we haven't already seen
952 // a type-specifier. Without this check we misparse:
953 // typedef int X; struct Y { short X; }; as 'short int'.
954 if (DS.hasTypeSpecifier())
955 goto DoneWithDeclSpec;
957 // It has to be available as a typedef too!
958 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
959 Tok.getLocation(), CurScope);
961 // If this is not a typedef name, don't parse it as part of the declspec,
962 // it must be an implicit int or an error.
964 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
965 goto DoneWithDeclSpec;
968 // C++: If the identifier is actually the name of the class type
969 // being defined and the next token is a '(', then this is a
970 // constructor declaration. We're done with the decl-specifiers
971 // and will treat this token as an identifier.
972 if (getLang().CPlusPlus &&
973 (CurScope->isClassScope() ||
974 (CurScope->isTemplateParamScope() &&
975 CurScope->getParent()->isClassScope())) &&
976 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
977 NextToken().getKind() == tok::l_paren)
978 goto DoneWithDeclSpec;
980 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
985 DS.SetRangeEnd(Tok.getLocation());
986 ConsumeToken(); // The identifier
988 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
989 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
990 // Objective-C interface. If we don't have Objective-C or a '<', this is
991 // just a normal reference to a typedef name.
992 if (!Tok.is(tok::less) || !getLang().ObjC1)
995 SourceLocation LAngleLoc, EndProtoLoc;
996 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
997 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
998 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
999 LAngleLoc, EndProtoLoc);
1000 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1001 ProtocolLocs.data(), LAngleLoc);
1003 DS.SetRangeEnd(EndProtoLoc);
1005 // Need to support trailing type qualifiers (e.g. "id<p> const").
1006 // If a type specifier follows, it will be diagnosed elsewhere.
1011 case tok::annot_template_id: {
1012 TemplateIdAnnotation *TemplateId
1013 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1014 if (TemplateId->Kind != TNK_Type_template) {
1015 // This template-id does not refer to a type name, so we're
1016 // done with the type-specifiers.
1017 goto DoneWithDeclSpec;
1020 // Turn the template-id annotation token into a type annotation
1021 // token, then try again to parse it as a type-specifier.
1022 AnnotateTemplateIdTokenAsType();
1026 // GNU attributes support.
1027 case tok::kw___attribute:
1028 DS.AddAttributes(ParseGNUAttributes());
1031 // Microsoft declspec support.
1032 case tok::kw___declspec:
1033 DS.AddAttributes(ParseMicrosoftDeclSpec());
1036 // Microsoft single token adornments.
1037 case tok::kw___forceinline:
1038 // FIXME: Add handling here!
1041 case tok::kw___ptr64:
1043 case tok::kw___cdecl:
1044 case tok::kw___stdcall:
1045 case tok::kw___fastcall:
1046 DS.AddAttributes(ParseMicrosoftTypeAttributes());
1049 // storage-class-specifier
1050 case tok::kw_typedef:
1051 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1054 case tok::kw_extern:
1055 if (DS.isThreadSpecified())
1056 Diag(Tok, diag::ext_thread_before) << "extern";
1057 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1060 case tok::kw___private_extern__:
1061 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1064 case tok::kw_static:
1065 if (DS.isThreadSpecified())
1066 Diag(Tok, diag::ext_thread_before) << "static";
1067 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1071 if (getLang().CPlusPlus0x)
1072 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1075 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1078 case tok::kw_register:
1079 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1082 case tok::kw_mutable:
1083 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1086 case tok::kw___thread:
1087 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1090 // function-specifier
1091 case tok::kw_inline:
1092 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1094 case tok::kw_virtual:
1095 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1097 case tok::kw_explicit:
1098 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1102 case tok::kw_friend:
1103 if (DSContext == DSC_class)
1104 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1106 PrevSpec = ""; // not actually used by the diagnostic
1107 DiagID = diag::err_friend_invalid_in_context;
1113 case tok::kw_constexpr:
1114 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1119 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1123 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1124 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1127 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1130 case tok::kw_signed:
1131 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1134 case tok::kw_unsigned:
1135 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1138 case tok::kw__Complex:
1139 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1142 case tok::kw__Imaginary:
1143 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1147 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1151 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1155 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1159 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1162 case tok::kw_double:
1163 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1166 case tok::kw_wchar_t:
1167 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1170 case tok::kw_char16_t:
1171 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1174 case tok::kw_char32_t:
1175 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1180 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1183 case tok::kw__Decimal32:
1184 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1187 case tok::kw__Decimal64:
1188 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1191 case tok::kw__Decimal128:
1192 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1198 case tok::kw_struct:
1199 case tok::kw_union: {
1200 tok::TokenKind Kind = Tok.getKind();
1202 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1209 ParseEnumSpecifier(Loc, DS, AS);
1214 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1217 case tok::kw_volatile:
1218 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1221 case tok::kw_restrict:
1222 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1226 // C++ typename-specifier:
1227 case tok::kw_typename:
1228 if (TryAnnotateTypeOrScopeToken())
1232 // GNU typeof support.
1233 case tok::kw_typeof:
1234 ParseTypeofSpecifier(DS);
1237 case tok::kw_decltype:
1238 ParseDecltypeSpecifier(DS);
1242 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1243 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
1244 // but we support it.
1245 if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1246 goto DoneWithDeclSpec;
1249 SourceLocation LAngleLoc, EndProtoLoc;
1250 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1251 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1252 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1253 LAngleLoc, EndProtoLoc);
1254 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1255 ProtocolLocs.data(), LAngleLoc);
1256 DS.SetRangeEnd(EndProtoLoc);
1258 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1259 << CodeModificationHint::CreateInsertion(Loc, "id")
1260 << SourceRange(Loc, EndProtoLoc);
1261 // Need to support trailing type qualifiers (e.g. "id<p> const").
1262 // If a type specifier follows, it will be diagnosed elsewhere.
1266 // If the specifier wasn't legal, issue a diagnostic.
1268 assert(PrevSpec && "Method did not return previous specifier!");
1270 Diag(Tok, DiagID) << PrevSpec;
1272 DS.SetRangeEnd(Tok.getLocation());
1277 /// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1278 /// primarily follow the C++ grammar with additions for C99 and GNU,
1279 /// which together subsume the C grammar. Note that the C++
1280 /// type-specifier also includes the C type-qualifier (for const,
1281 /// volatile, and C99 restrict). Returns true if a type-specifier was
1282 /// found (and parsed), false otherwise.
1284 /// type-specifier: [C++ 7.1.5]
1285 /// simple-type-specifier
1288 /// elaborated-type-specifier [TODO]
1291 /// cv-qualifier: [C++ 7.1.5.1]
1294 /// [C99] 'restrict'
1296 /// simple-type-specifier: [ C++ 7.1.5.2]
1297 /// '::'[opt] nested-name-specifier[opt] type-name [TODO]
1298 /// '::'[opt] nested-name-specifier 'template' template-id [TODO]
1311 /// [C99] '_Complex'
1312 /// [C99] '_Imaginary' // Removed in TC2?
1313 /// [GNU] '_Decimal32'
1314 /// [GNU] '_Decimal64'
1315 /// [GNU] '_Decimal128'
1316 /// [GNU] typeof-specifier
1317 /// [OBJC] class-name objc-protocol-refs[opt] [TODO]
1318 /// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
1319 /// [C++0x] 'decltype' ( expression )
1320 bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1321 const char *&PrevSpec,
1323 const ParsedTemplateInfo &TemplateInfo) {
1324 SourceLocation Loc = Tok.getLocation();
1326 switch (Tok.getKind()) {
1327 case tok::identifier: // foo::bar
1328 case tok::kw_typename: // typename foo::bar
1329 // Annotate typenames and C++ scope specifiers. If we get one, just
1330 // recurse to handle whatever we get.
1331 if (TryAnnotateTypeOrScopeToken())
1332 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1334 // Otherwise, not a type specifier.
1336 case tok::coloncolon: // ::foo::bar
1337 if (NextToken().is(tok::kw_new) || // ::new
1338 NextToken().is(tok::kw_delete)) // ::delete
1341 // Annotate typenames and C++ scope specifiers. If we get one, just
1342 // recurse to handle whatever we get.
1343 if (TryAnnotateTypeOrScopeToken())
1344 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1346 // Otherwise, not a type specifier.
1349 // simple-type-specifier:
1350 case tok::annot_typename: {
1351 if (Tok.getAnnotationValue())
1352 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1353 DiagID, Tok.getAnnotationValue());
1355 DS.SetTypeSpecError();
1356 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1357 ConsumeToken(); // The typename
1359 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1360 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1361 // Objective-C interface. If we don't have Objective-C or a '<', this is
1362 // just a normal reference to a typedef name.
1363 if (!Tok.is(tok::less) || !getLang().ObjC1)
1366 SourceLocation LAngleLoc, EndProtoLoc;
1367 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1368 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1369 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1370 LAngleLoc, EndProtoLoc);
1371 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1372 ProtocolLocs.data(), LAngleLoc);
1374 DS.SetRangeEnd(EndProtoLoc);
1379 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1382 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1383 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1386 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1389 case tok::kw_signed:
1390 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1392 case tok::kw_unsigned:
1393 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1396 case tok::kw__Complex:
1397 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1400 case tok::kw__Imaginary:
1401 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1405 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1408 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1411 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1414 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1416 case tok::kw_double:
1417 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1419 case tok::kw_wchar_t:
1420 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1422 case tok::kw_char16_t:
1423 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1425 case tok::kw_char32_t:
1426 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1430 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1432 case tok::kw__Decimal32:
1433 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1436 case tok::kw__Decimal64:
1437 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1440 case tok::kw__Decimal128:
1441 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1447 case tok::kw_struct:
1448 case tok::kw_union: {
1449 tok::TokenKind Kind = Tok.getKind();
1451 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo);
1458 ParseEnumSpecifier(Loc, DS);
1463 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
1466 case tok::kw_volatile:
1467 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1470 case tok::kw_restrict:
1471 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1475 // GNU typeof support.
1476 case tok::kw_typeof:
1477 ParseTypeofSpecifier(DS);
1480 // C++0x decltype support.
1481 case tok::kw_decltype:
1482 ParseDecltypeSpecifier(DS);
1485 // C++0x auto support.
1487 if (!getLang().CPlusPlus0x)
1490 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1492 case tok::kw___ptr64:
1494 case tok::kw___cdecl:
1495 case tok::kw___stdcall:
1496 case tok::kw___fastcall:
1497 DS.AddAttributes(ParseMicrosoftTypeAttributes());
1501 // Not a type-specifier; do nothing.
1505 // If the specifier combination wasn't legal, issue a diagnostic.
1507 assert(PrevSpec && "Method did not return previous specifier!");
1508 // Pick between error or extwarn.
1509 Diag(Tok, DiagID) << PrevSpec;
1511 DS.SetRangeEnd(Tok.getLocation());
1512 ConsumeToken(); // whatever we parsed above.
1516 /// ParseStructDeclaration - Parse a struct declaration without the terminating
1519 /// struct-declaration:
1520 /// specifier-qualifier-list struct-declarator-list
1521 /// [GNU] __extension__ struct-declaration
1522 /// [GNU] specifier-qualifier-list
1523 /// struct-declarator-list:
1524 /// struct-declarator
1525 /// struct-declarator-list ',' struct-declarator
1526 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
1527 /// struct-declarator:
1529 /// [GNU] declarator attributes[opt]
1530 /// declarator[opt] ':' constant-expression
1531 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
1534 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
1535 if (Tok.is(tok::kw___extension__)) {
1536 // __extension__ silences extension warnings in the subexpression.
1537 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1539 return ParseStructDeclaration(DS, Fields);
1542 // Parse the common specifier-qualifiers-list piece.
1543 SourceLocation DSStart = Tok.getLocation();
1544 ParseSpecifierQualifierList(DS);
1546 // If there are no declarators, this is a free-standing declaration
1547 // specifier. Let the actions module cope with it.
1548 if (Tok.is(tok::semi)) {
1549 Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1553 // Read struct-declarators until we find the semicolon.
1554 bool FirstDeclarator = true;
1556 ParsingDeclRAIIObject PD(*this);
1557 FieldDeclarator DeclaratorInfo(DS);
1559 // Attributes are only allowed here on successive declarators.
1560 if (!FirstDeclarator && Tok.is(tok::kw___attribute)) {
1562 AttributeList *AttrList = ParseGNUAttributes(&Loc);
1563 DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1566 /// struct-declarator: declarator
1567 /// struct-declarator: declarator[opt] ':' constant-expression
1568 if (Tok.isNot(tok::colon)) {
1569 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1570 ColonProtectionRAIIObject X(*this);
1571 ParseDeclarator(DeclaratorInfo.D);
1574 if (Tok.is(tok::colon)) {
1576 OwningExprResult Res(ParseConstantExpression());
1577 if (Res.isInvalid())
1578 SkipUntil(tok::semi, true, true);
1580 DeclaratorInfo.BitfieldSize = Res.release();
1583 // If attributes exist after the declarator, parse them.
1584 if (Tok.is(tok::kw___attribute)) {
1586 AttributeList *AttrList = ParseGNUAttributes(&Loc);
1587 DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1590 // We're done with this declarator; invoke the callback.
1591 DeclPtrTy D = Fields.invoke(DeclaratorInfo);
1594 // If we don't have a comma, it is either the end of the list (a ';')
1595 // or an error, bail out.
1596 if (Tok.isNot(tok::comma))
1599 // Consume the comma.
1602 FirstDeclarator = false;
1606 /// ParseStructUnionBody
1607 /// struct-contents:
1608 /// struct-declaration-list
1610 /// [GNU] "struct-declaration-list" without terminatoring ';'
1611 /// struct-declaration-list:
1612 /// struct-declaration
1613 /// struct-declaration-list struct-declaration
1614 /// [OBC] '@' 'defs' '(' class-name ')'
1616 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1617 unsigned TagType, DeclPtrTy TagDecl) {
1618 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1619 PP.getSourceManager(),
1620 "parsing struct/union body");
1622 SourceLocation LBraceLoc = ConsumeBrace();
1624 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1625 Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1627 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1629 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1630 Diag(Tok, diag::ext_empty_struct_union_enum)
1631 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1633 llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1635 // While we still have something to read, read the declarations in the struct.
1636 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1637 // Each iteration of this loop reads one struct-declaration.
1639 // Check for extraneous top-level semicolon.
1640 if (Tok.is(tok::semi)) {
1641 Diag(Tok, diag::ext_extra_struct_semi)
1642 << CodeModificationHint::CreateRemoval(Tok.getLocation());
1647 // Parse all the comma separated declarators.
1650 if (!Tok.is(tok::at)) {
1651 struct CFieldCallback : FieldCallback {
1654 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls;
1656 CFieldCallback(Parser &P, DeclPtrTy TagDecl,
1657 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) :
1658 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
1660 virtual DeclPtrTy invoke(FieldDeclarator &FD) {
1661 // Install the declarator into the current TagDecl.
1662 DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl,
1663 FD.D.getDeclSpec().getSourceRange().getBegin(),
1664 FD.D, FD.BitfieldSize);
1665 FieldDecls.push_back(Field);
1668 } Callback(*this, TagDecl, FieldDecls);
1670 ParseStructDeclaration(DS, Callback);
1671 } else { // Handle @defs
1673 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1674 Diag(Tok, diag::err_unexpected_at);
1675 SkipUntil(tok::semi, true, true);
1679 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1680 if (!Tok.is(tok::identifier)) {
1681 Diag(Tok, diag::err_expected_ident);
1682 SkipUntil(tok::semi, true, true);
1685 llvm::SmallVector<DeclPtrTy, 16> Fields;
1686 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1687 Tok.getIdentifierInfo(), Fields);
1688 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1690 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1693 if (Tok.is(tok::semi)) {
1695 } else if (Tok.is(tok::r_brace)) {
1696 Diag(Tok, diag::ext_expected_semi_decl_list);
1699 Diag(Tok, diag::err_expected_semi_decl_list);
1700 // Skip to end of block or statement
1701 SkipUntil(tok::r_brace, true, true);
1705 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1707 AttributeList *AttrList = 0;
1708 // If attributes exist after struct contents, parse them.
1709 if (Tok.is(tok::kw___attribute))
1710 AttrList = ParseGNUAttributes();
1712 Actions.ActOnFields(CurScope,
1713 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1714 LBraceLoc, RBraceLoc,
1717 Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1721 /// ParseEnumSpecifier
1722 /// enum-specifier: [C99 6.7.2.2]
1723 /// 'enum' identifier[opt] '{' enumerator-list '}'
1724 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1725 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1726 /// '}' attributes[opt]
1727 /// 'enum' identifier
1728 /// [GNU] 'enum' attributes[opt] identifier
1730 /// [C++] elaborated-type-specifier:
1731 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
1733 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1734 AccessSpecifier AS) {
1735 // Parse the tag portion of this.
1736 if (Tok.is(tok::code_completion)) {
1737 // Code completion for an enum name.
1738 Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1742 AttributeList *Attr = 0;
1743 // If attributes exist after tag, parse them.
1744 if (Tok.is(tok::kw___attribute))
1745 Attr = ParseGNUAttributes();
1748 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, 0, false)) {
1749 if (Tok.isNot(tok::identifier)) {
1750 Diag(Tok, diag::err_expected_ident);
1751 if (Tok.isNot(tok::l_brace)) {
1752 // Has no name and is not a definition.
1753 // Skip the rest of this declarator, up until the comma or semicolon.
1754 SkipUntil(tok::comma, true);
1760 // Must have either 'enum name' or 'enum {...}'.
1761 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1762 Diag(Tok, diag::err_expected_ident_lbrace);
1764 // Skip the rest of this declarator, up until the comma or semicolon.
1765 SkipUntil(tok::comma, true);
1769 // If an identifier is present, consume and remember it.
1770 IdentifierInfo *Name = 0;
1771 SourceLocation NameLoc;
1772 if (Tok.is(tok::identifier)) {
1773 Name = Tok.getIdentifierInfo();
1774 NameLoc = ConsumeToken();
1777 // There are three options here. If we have 'enum foo;', then this is a
1778 // forward declaration. If we have 'enum foo {...' then this is a
1779 // definition. Otherwise we have something like 'enum foo xyz', a reference.
1781 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1782 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
1783 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
1785 Action::TagUseKind TUK;
1786 if (Tok.is(tok::l_brace))
1787 TUK = Action::TUK_Definition;
1788 else if (Tok.is(tok::semi))
1789 TUK = Action::TUK_Declaration;
1791 TUK = Action::TUK_Reference;
1793 bool IsDependent = false;
1794 DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1795 StartLoc, SS, Name, NameLoc, Attr, AS,
1796 Action::MultiTemplateParamsArg(Actions),
1797 Owned, IsDependent);
1798 assert(!IsDependent && "didn't expect dependent enum");
1800 if (Tok.is(tok::l_brace))
1801 ParseEnumBody(StartLoc, TagDecl);
1803 // TODO: semantic analysis on the declspec for enums.
1804 const char *PrevSpec = 0;
1806 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, DiagID,
1807 TagDecl.getAs<void>(), Owned))
1808 Diag(StartLoc, DiagID) << PrevSpec;
1811 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
1812 /// enumerator-list:
1814 /// enumerator-list ',' enumerator
1816 /// enumeration-constant
1817 /// enumeration-constant '=' constant-expression
1818 /// enumeration-constant:
1821 void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1822 // Enter the scope of the enum body and start the definition.
1823 ParseScope EnumScope(this, Scope::DeclScope);
1824 Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1826 SourceLocation LBraceLoc = ConsumeBrace();
1828 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1829 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1830 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1832 llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1834 DeclPtrTy LastEnumConstDecl;
1836 // Parse the enumerator-list.
1837 while (Tok.is(tok::identifier)) {
1838 IdentifierInfo *Ident = Tok.getIdentifierInfo();
1839 SourceLocation IdentLoc = ConsumeToken();
1841 SourceLocation EqualLoc;
1842 OwningExprResult AssignedVal(Actions);
1843 if (Tok.is(tok::equal)) {
1844 EqualLoc = ConsumeToken();
1845 AssignedVal = ParseConstantExpression();
1846 if (AssignedVal.isInvalid())
1847 SkipUntil(tok::comma, tok::r_brace, true, true);
1850 // Install the enumerator constant into EnumDecl.
1851 DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1855 AssignedVal.release());
1856 EnumConstantDecls.push_back(EnumConstDecl);
1857 LastEnumConstDecl = EnumConstDecl;
1859 if (Tok.isNot(tok::comma))
1861 SourceLocation CommaLoc = ConsumeToken();
1863 if (Tok.isNot(tok::identifier) &&
1864 !(getLang().C99 || getLang().CPlusPlus0x))
1865 Diag(CommaLoc, diag::ext_enumerator_list_comma)
1866 << getLang().CPlusPlus
1867 << CodeModificationHint::CreateRemoval(CommaLoc);
1871 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1873 AttributeList *Attr = 0;
1874 // If attributes exist after the identifier list, parse them.
1875 if (Tok.is(tok::kw___attribute))
1876 Attr = ParseGNUAttributes(); // FIXME: where do they do?
1878 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
1879 EnumConstantDecls.data(), EnumConstantDecls.size(),
1883 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
1886 /// isTypeSpecifierQualifier - Return true if the current token could be the
1887 /// start of a type-qualifier-list.
1888 bool Parser::isTypeQualifier() const {
1889 switch (Tok.getKind()) {
1890 default: return false;
1893 case tok::kw_volatile:
1894 case tok::kw_restrict:
1899 /// isTypeSpecifierQualifier - Return true if the current token could be the
1900 /// start of a specifier-qualifier-list.
1901 bool Parser::isTypeSpecifierQualifier() {
1902 switch (Tok.getKind()) {
1903 default: return false;
1905 case tok::identifier: // foo::bar
1906 case tok::kw_typename: // typename T::type
1907 // Annotate typenames and C++ scope specifiers. If we get one, just
1908 // recurse to handle whatever we get.
1909 if (TryAnnotateTypeOrScopeToken())
1910 return isTypeSpecifierQualifier();
1911 // Otherwise, not a type specifier.
1914 case tok::coloncolon: // ::foo::bar
1915 if (NextToken().is(tok::kw_new) || // ::new
1916 NextToken().is(tok::kw_delete)) // ::delete
1919 // Annotate typenames and C++ scope specifiers. If we get one, just
1920 // recurse to handle whatever we get.
1921 if (TryAnnotateTypeOrScopeToken())
1922 return isTypeSpecifierQualifier();
1923 // Otherwise, not a type specifier.
1926 // GNU attributes support.
1927 case tok::kw___attribute:
1928 // GNU typeof support.
1929 case tok::kw_typeof:
1934 case tok::kw_signed:
1935 case tok::kw_unsigned:
1936 case tok::kw__Complex:
1937 case tok::kw__Imaginary:
1940 case tok::kw_wchar_t:
1941 case tok::kw_char16_t:
1942 case tok::kw_char32_t:
1945 case tok::kw_double:
1948 case tok::kw__Decimal32:
1949 case tok::kw__Decimal64:
1950 case tok::kw__Decimal128:
1952 // struct-or-union-specifier (C99) or class-specifier (C++)
1954 case tok::kw_struct:
1961 case tok::kw_volatile:
1962 case tok::kw_restrict:
1965 case tok::annot_typename:
1968 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1970 return getLang().ObjC1;
1972 case tok::kw___cdecl:
1973 case tok::kw___stdcall:
1974 case tok::kw___fastcall:
1976 case tok::kw___ptr64:
1981 /// isDeclarationSpecifier() - Return true if the current token is part of a
1982 /// declaration specifier.
1983 bool Parser::isDeclarationSpecifier() {
1984 switch (Tok.getKind()) {
1985 default: return false;
1987 case tok::identifier: // foo::bar
1988 // Unfortunate hack to support "Class.factoryMethod" notation.
1989 if (getLang().ObjC1 && NextToken().is(tok::period))
1993 case tok::kw_typename: // typename T::type
1994 // Annotate typenames and C++ scope specifiers. If we get one, just
1995 // recurse to handle whatever we get.
1996 if (TryAnnotateTypeOrScopeToken())
1997 return isDeclarationSpecifier();
1998 // Otherwise, not a declaration specifier.
2000 case tok::coloncolon: // ::foo::bar
2001 if (NextToken().is(tok::kw_new) || // ::new
2002 NextToken().is(tok::kw_delete)) // ::delete
2005 // Annotate typenames and C++ scope specifiers. If we get one, just
2006 // recurse to handle whatever we get.
2007 if (TryAnnotateTypeOrScopeToken())
2008 return isDeclarationSpecifier();
2009 // Otherwise, not a declaration specifier.
2012 // storage-class-specifier
2013 case tok::kw_typedef:
2014 case tok::kw_extern:
2015 case tok::kw___private_extern__:
2016 case tok::kw_static:
2018 case tok::kw_register:
2019 case tok::kw___thread:
2024 case tok::kw_signed:
2025 case tok::kw_unsigned:
2026 case tok::kw__Complex:
2027 case tok::kw__Imaginary:
2030 case tok::kw_wchar_t:
2031 case tok::kw_char16_t:
2032 case tok::kw_char32_t:
2036 case tok::kw_double:
2039 case tok::kw__Decimal32:
2040 case tok::kw__Decimal64:
2041 case tok::kw__Decimal128:
2043 // struct-or-union-specifier (C99) or class-specifier (C++)
2045 case tok::kw_struct:
2052 case tok::kw_volatile:
2053 case tok::kw_restrict:
2055 // function-specifier
2056 case tok::kw_inline:
2057 case tok::kw_virtual:
2058 case tok::kw_explicit:
2061 case tok::annot_typename:
2063 // GNU typeof support.
2064 case tok::kw_typeof:
2067 case tok::kw___attribute:
2070 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2072 return getLang().ObjC1;
2074 case tok::kw___declspec:
2075 case tok::kw___cdecl:
2076 case tok::kw___stdcall:
2077 case tok::kw___fastcall:
2079 case tok::kw___ptr64:
2080 case tok::kw___forceinline:
2086 /// ParseTypeQualifierListOpt
2087 /// type-qualifier-list: [C99 6.7.5]
2089 /// [GNU] attributes [ only if AttributesAllowed=true ]
2090 /// type-qualifier-list type-qualifier
2091 /// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ]
2092 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2093 /// if CXX0XAttributesAllowed = true
2095 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed,
2096 bool CXX0XAttributesAllowed) {
2097 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2098 SourceLocation Loc = Tok.getLocation();
2099 CXX0XAttributeList Attr = ParseCXX0XAttributes();
2100 if (CXX0XAttributesAllowed)
2101 DS.AddAttributes(Attr.AttrList);
2103 Diag(Loc, diag::err_attributes_not_allowed);
2107 bool isInvalid = false;
2108 const char *PrevSpec = 0;
2109 unsigned DiagID = 0;
2110 SourceLocation Loc = Tok.getLocation();
2112 switch (Tok.getKind()) {
2114 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
2117 case tok::kw_volatile:
2118 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2121 case tok::kw_restrict:
2122 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2126 case tok::kw___ptr64:
2127 case tok::kw___cdecl:
2128 case tok::kw___stdcall:
2129 case tok::kw___fastcall:
2130 if (GNUAttributesAllowed) {
2131 DS.AddAttributes(ParseMicrosoftTypeAttributes());
2134 goto DoneWithTypeQuals;
2135 case tok::kw___attribute:
2136 if (GNUAttributesAllowed) {
2137 DS.AddAttributes(ParseGNUAttributes());
2138 continue; // do *not* consume the next token!
2140 // otherwise, FALL THROUGH!
2143 // If this is not a type-qualifier token, we're done reading type
2144 // qualifiers. First verify that DeclSpec's are consistent.
2145 DS.Finish(Diags, PP);
2149 // If the specifier combination wasn't legal, issue a diagnostic.
2151 assert(PrevSpec && "Method did not return previous specifier!");
2152 Diag(Tok, DiagID) << PrevSpec;
2159 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2161 void Parser::ParseDeclarator(Declarator &D) {
2162 /// This implements the 'declarator' production in the C grammar, then checks
2163 /// for well-formedness and issues diagnostics.
2164 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2167 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2168 /// is parsed by the function passed to it. Pass null, and the direct-declarator
2169 /// isn't parsed at all, making this function effectively parse the C++
2170 /// ptr-operator production.
2172 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2173 /// [C] pointer[opt] direct-declarator
2174 /// [C++] direct-declarator
2175 /// [C++] ptr-operator declarator
2177 /// pointer: [C99 6.7.5]
2178 /// '*' type-qualifier-list[opt]
2179 /// '*' type-qualifier-list[opt] pointer
2182 /// '*' cv-qualifier-seq[opt]
2185 /// [GNU] '&' restrict[opt] attributes[opt]
2186 /// [GNU?] '&&' restrict[opt] attributes[opt]
2187 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2188 void Parser::ParseDeclaratorInternal(Declarator &D,
2189 DirectDeclParseFunction DirectDeclParser) {
2190 if (Diags.hasAllExtensionsSilenced())
2192 // C++ member pointers start with a '::' or a nested-name.
2193 // Member pointers get special handling, since there's no place for the
2194 // scope spec in the generic path below.
2195 if (getLang().CPlusPlus &&
2196 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2197 Tok.is(tok::annot_cxxscope))) {
2199 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) {
2200 if (Tok.isNot(tok::star)) {
2201 // The scope spec really belongs to the direct-declarator.
2202 D.getCXXScopeSpec() = SS;
2203 if (DirectDeclParser)
2204 (this->*DirectDeclParser)(D);
2208 SourceLocation Loc = ConsumeToken();
2211 ParseTypeQualifierListOpt(DS);
2212 D.ExtendWithDeclSpec(DS);
2214 // Recurse to parse whatever is left.
2215 ParseDeclaratorInternal(D, DirectDeclParser);
2217 // Sema will have to catch (syntactically invalid) pointers into global
2218 // scope. It has to catch pointers into namespace scope anyway.
2219 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2220 Loc, DS.TakeAttributes()),
2221 /* Don't replace range end. */SourceLocation());
2226 tok::TokenKind Kind = Tok.getKind();
2227 // Not a pointer, C++ reference, or block.
2228 if (Kind != tok::star && Kind != tok::caret &&
2229 (Kind != tok::amp || !getLang().CPlusPlus) &&
2230 // We parse rvalue refs in C++03, because otherwise the errors are scary.
2231 (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2232 if (DirectDeclParser)
2233 (this->*DirectDeclParser)(D);
2237 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2238 // '&&' -> rvalue reference
2239 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
2242 if (Kind == tok::star || Kind == tok::caret) {
2246 ParseTypeQualifierListOpt(DS);
2247 D.ExtendWithDeclSpec(DS);
2249 // Recursively parse the declarator.
2250 ParseDeclaratorInternal(D, DirectDeclParser);
2251 if (Kind == tok::star)
2252 // Remember that we parsed a pointer type, and remember the type-quals.
2253 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2254 DS.TakeAttributes()),
2257 // Remember that we parsed a Block type, and remember the type-quals.
2258 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2259 Loc, DS.TakeAttributes()),
2265 // Complain about rvalue references in C++03, but then go on and build
2267 if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2268 Diag(Loc, diag::err_rvalue_reference);
2270 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2271 // cv-qualifiers are introduced through the use of a typedef or of a
2272 // template type argument, in which case the cv-qualifiers are ignored.
2274 // [GNU] Retricted references are allowed.
2275 // [GNU] Attributes on references are allowed.
2276 // [C++0x] Attributes on references are not allowed.
2277 ParseTypeQualifierListOpt(DS, true, false);
2278 D.ExtendWithDeclSpec(DS);
2280 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2281 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2282 Diag(DS.getConstSpecLoc(),
2283 diag::err_invalid_reference_qualifier_application) << "const";
2284 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2285 Diag(DS.getVolatileSpecLoc(),
2286 diag::err_invalid_reference_qualifier_application) << "volatile";
2289 // Recursively parse the declarator.
2290 ParseDeclaratorInternal(D, DirectDeclParser);
2292 if (D.getNumTypeObjects() > 0) {
2293 // C++ [dcl.ref]p4: There shall be no references to references.
2294 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2295 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2296 if (const IdentifierInfo *II = D.getIdentifier())
2297 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2300 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2303 // Once we've complained about the reference-to-reference, we
2304 // can go ahead and build the (technically ill-formed)
2305 // declarator: reference collapsing will take care of it.
2309 // Remember that we parsed a reference type. It doesn't have type-quals.
2310 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2311 DS.TakeAttributes(),
2317 /// ParseDirectDeclarator
2318 /// direct-declarator: [C99 6.7.5]
2319 /// [C99] identifier
2320 /// '(' declarator ')'
2321 /// [GNU] '(' attributes declarator ')'
2322 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2323 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2324 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2325 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2326 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2327 /// direct-declarator '(' parameter-type-list ')'
2328 /// direct-declarator '(' identifier-list[opt] ')'
2329 /// [GNU] direct-declarator '(' parameter-forward-declarations
2330 /// parameter-type-list[opt] ')'
2331 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2332 /// cv-qualifier-seq[opt] exception-specification[opt]
2333 /// [C++] declarator-id
2335 /// declarator-id: [C++ 8]
2337 /// '::'[opt] nested-name-specifier[opt] type-name
2339 /// id-expression: [C++ 5.1]
2343 /// unqualified-id: [C++ 5.1]
2345 /// operator-function-id
2346 /// conversion-function-id
2350 void Parser::ParseDirectDeclarator(Declarator &D) {
2351 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2353 if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
2354 // ParseDeclaratorInternal might already have parsed the scope.
2355 bool afterCXXScope = D.getCXXScopeSpec().isSet() ||
2356 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2358 if (afterCXXScope) {
2359 if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2360 // Change the declaration context for name lookup, until this function
2361 // is exited (and the declarator has been parsed).
2362 DeclScopeObj.EnterDeclaratorScope();
2365 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
2366 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
2367 // We found something that indicates the start of an unqualified-id.
2368 // Parse that unqualified-id.
2369 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
2370 /*EnteringContext=*/true,
2371 /*AllowDestructorName=*/true,
2372 /*AllowConstructorName=*/!D.getDeclSpec().hasTypeSpecifier(),
2375 D.SetIdentifier(0, Tok.getLocation());
2376 D.setInvalidType(true);
2378 // Parsed the unqualified-id; update range information and move along.
2379 if (D.getSourceRange().getBegin().isInvalid())
2380 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
2381 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
2383 goto PastIdentifier;
2385 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2386 assert(!getLang().CPlusPlus &&
2387 "There's a C++-specific check for tok::identifier above");
2388 assert(Tok.getIdentifierInfo() && "Not an identifier?");
2389 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2391 goto PastIdentifier;
2394 if (Tok.is(tok::l_paren)) {
2395 // direct-declarator: '(' declarator ')'
2396 // direct-declarator: '(' attributes declarator ')'
2397 // Example: 'char (*X)' or 'int (*XX)(void)'
2398 ParseParenDeclarator(D);
2399 } else if (D.mayOmitIdentifier()) {
2400 // This could be something simple like "int" (in which case the declarator
2401 // portion is empty), if an abstract-declarator is allowed.
2402 D.SetIdentifier(0, Tok.getLocation());
2404 if (D.getContext() == Declarator::MemberContext)
2405 Diag(Tok, diag::err_expected_member_name_or_semi)
2406 << D.getDeclSpec().getSourceRange();
2407 else if (getLang().CPlusPlus)
2408 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
2410 Diag(Tok, diag::err_expected_ident_lparen);
2411 D.SetIdentifier(0, Tok.getLocation());
2412 D.setInvalidType(true);
2416 assert(D.isPastIdentifier() &&
2417 "Haven't past the location of the identifier yet?");
2419 // Don't parse attributes unless we have an identifier.
2420 if (D.getIdentifier() && getLang().CPlusPlus
2421 && isCXX0XAttributeSpecifier(true)) {
2422 SourceLocation AttrEndLoc;
2423 CXX0XAttributeList Attr = ParseCXX0XAttributes();
2424 D.AddAttributes(Attr.AttrList, AttrEndLoc);
2428 if (Tok.is(tok::l_paren)) {
2429 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2430 // In such a case, check if we actually have a function declarator; if it
2431 // is not, the declarator has been fully parsed.
2432 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2433 // When not in file scope, warn for ambiguous function declarators, just
2434 // in case the author intended it as a variable definition.
2435 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2436 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2439 ParseFunctionDeclarator(ConsumeParen(), D);
2440 } else if (Tok.is(tok::l_square)) {
2441 ParseBracketDeclarator(D);
2448 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2449 /// only called before the identifier, so these are most likely just grouping
2450 /// parens for precedence. If we find that these are actually function
2451 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2453 /// direct-declarator:
2454 /// '(' declarator ')'
2455 /// [GNU] '(' attributes declarator ')'
2456 /// direct-declarator '(' parameter-type-list ')'
2457 /// direct-declarator '(' identifier-list[opt] ')'
2458 /// [GNU] direct-declarator '(' parameter-forward-declarations
2459 /// parameter-type-list[opt] ')'
2461 void Parser::ParseParenDeclarator(Declarator &D) {
2462 SourceLocation StartLoc = ConsumeParen();
2463 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2465 // Eat any attributes before we look at whether this is a grouping or function
2466 // declarator paren. If this is a grouping paren, the attribute applies to
2467 // the type being built up, for example:
2468 // int (__attribute__(()) *x)(long y)
2469 // If this ends up not being a grouping paren, the attribute applies to the
2470 // first argument, for example:
2471 // int (__attribute__(()) int x)
2472 // In either case, we need to eat any attributes to be able to determine what
2473 // sort of paren this is.
2475 AttributeList *AttrList = 0;
2476 bool RequiresArg = false;
2477 if (Tok.is(tok::kw___attribute)) {
2478 AttrList = ParseGNUAttributes();
2480 // We require that the argument list (if this is a non-grouping paren) be
2481 // present even if the attribute list was empty.
2484 // Eat any Microsoft extensions.
2485 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2486 Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2487 Tok.is(tok::kw___ptr64)) {
2488 AttrList = ParseMicrosoftTypeAttributes(AttrList);
2491 // If we haven't past the identifier yet (or where the identifier would be
2492 // stored, if this is an abstract declarator), then this is probably just
2493 // grouping parens. However, if this could be an abstract-declarator, then
2494 // this could also be the start of function arguments (consider 'void()').
2497 if (!D.mayOmitIdentifier()) {
2498 // If this can't be an abstract-declarator, this *must* be a grouping
2499 // paren, because we haven't seen the identifier yet.
2501 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
2502 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2503 isDeclarationSpecifier()) { // 'int(int)' is a function.
2504 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2505 // considered to be a type, not a K&R identifier-list.
2508 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2512 // If this is a grouping paren, handle:
2513 // direct-declarator: '(' declarator ')'
2514 // direct-declarator: '(' attributes declarator ')'
2516 bool hadGroupingParens = D.hasGroupingParens();
2517 D.setGroupingParens(true);
2519 D.AddAttributes(AttrList, SourceLocation());
2521 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2523 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2525 D.setGroupingParens(hadGroupingParens);
2530 // Okay, if this wasn't a grouping paren, it must be the start of a function
2531 // argument list. Recognize that this declarator will never have an
2532 // identifier (and remember where it would have been), then call into
2533 // ParseFunctionDeclarator to handle of argument list.
2534 D.SetIdentifier(0, Tok.getLocation());
2536 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
2539 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
2540 /// declarator D up to a paren, which indicates that we are parsing function
2543 /// If AttrList is non-null, then the caller parsed those arguments immediately
2544 /// after the open paren - they should be considered to be the first argument of
2545 /// a parameter. If RequiresArg is true, then the first argument of the
2546 /// function is required to be present and required to not be an identifier
2549 /// This method also handles this portion of the grammar:
2550 /// parameter-type-list: [C99 6.7.5]
2552 /// parameter-list ',' '...'
2553 /// [C++] parameter-list '...'
2555 /// parameter-list: [C99 6.7.5]
2556 /// parameter-declaration
2557 /// parameter-list ',' parameter-declaration
2559 /// parameter-declaration: [C99 6.7.5]
2560 /// declaration-specifiers declarator
2561 /// [C++] declaration-specifiers declarator '=' assignment-expression
2562 /// [GNU] declaration-specifiers declarator attributes
2563 /// declaration-specifiers abstract-declarator[opt]
2564 /// [C++] declaration-specifiers abstract-declarator[opt]
2565 /// '=' assignment-expression
2566 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
2568 /// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2569 /// and "exception-specification[opt]".
2571 void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2572 AttributeList *AttrList,
2574 // lparen is already consumed!
2575 assert(D.isPastIdentifier() && "Should not call before identifier!");
2577 // This parameter list may be empty.
2578 if (Tok.is(tok::r_paren)) {
2580 Diag(Tok, diag::err_argument_required_after_attribute);
2584 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'.
2585 SourceLocation EndLoc = RParenLoc;
2587 // cv-qualifier-seq[opt].
2589 bool hasExceptionSpec = false;
2590 SourceLocation ThrowLoc;
2591 bool hasAnyExceptionSpec = false;
2592 llvm::SmallVector<TypeTy*, 2> Exceptions;
2593 llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2594 if (getLang().CPlusPlus) {
2595 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2596 if (!DS.getSourceRange().getEnd().isInvalid())
2597 EndLoc = DS.getSourceRange().getEnd();
2599 // Parse exception-specification[opt].
2600 if (Tok.is(tok::kw_throw)) {
2601 hasExceptionSpec = true;
2602 ThrowLoc = Tok.getLocation();
2603 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2604 hasAnyExceptionSpec);
2605 assert(Exceptions.size() == ExceptionRanges.size() &&
2606 "Produced different number of exception types and ranges.");
2610 // Remember that we parsed a function type, and remember the attributes.
2611 // int() -> no prototype, no '...'.
2612 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2616 DS.getTypeQualifiers(),
2617 hasExceptionSpec, ThrowLoc,
2618 hasAnyExceptionSpec,
2620 ExceptionRanges.data(),
2622 LParenLoc, RParenLoc, D),
2627 // Alternatively, this parameter list may be an identifier list form for a
2628 // K&R-style function: void foo(a,b,c)
2629 if (!getLang().CPlusPlus && Tok.is(tok::identifier)) {
2630 if (!TryAnnotateTypeOrScopeToken()) {
2631 // K&R identifier lists can't have typedefs as identifiers, per
2634 Diag(Tok, diag::err_argument_required_after_attribute);
2637 // Identifier list. Note that '(' identifier-list ')' is only allowed for
2638 // normal declarators, not for abstract-declarators.
2639 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2643 // Finally, a normal, non-empty parameter type list.
2645 // Build up an array of information about the parsed arguments.
2646 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2648 // Enter function-declaration scope, limiting any declarators to the
2649 // function prototype scope, including parameter declarators.
2650 ParseScope PrototypeScope(this,
2651 Scope::FunctionPrototypeScope|Scope::DeclScope);
2653 bool IsVariadic = false;
2654 SourceLocation EllipsisLoc;
2656 if (Tok.is(tok::ellipsis)) {
2658 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
2662 SourceLocation DSStart = Tok.getLocation();
2664 // Parse the declaration-specifiers.
2665 // Just use the ParsingDeclaration "scope" of the declarator.
2668 // If the caller parsed attributes for the first argument, add them now.
2670 DS.AddAttributes(AttrList);
2671 AttrList = 0; // Only apply the attributes to the first parameter.
2673 ParseDeclarationSpecifiers(DS);
2675 // Parse the declarator. This is "PrototypeContext", because we must
2676 // accept either 'declarator' or 'abstract-declarator' here.
2677 Declarator ParmDecl(DS, Declarator::PrototypeContext);
2678 ParseDeclarator(ParmDecl);
2680 // Parse GNU attributes, if present.
2681 if (Tok.is(tok::kw___attribute)) {
2683 AttributeList *AttrList = ParseGNUAttributes(&Loc);
2684 ParmDecl.AddAttributes(AttrList, Loc);
2687 // Remember this parsed parameter in ParamInfo.
2688 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2690 // DefArgToks is used when the parsing of default arguments needs
2692 CachedTokens *DefArgToks = 0;
2694 // If no parameter was specified, verify that *something* was specified,
2695 // otherwise we have a missing type and identifier.
2696 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2697 ParmDecl.getNumTypeObjects() == 0) {
2698 // Completely missing, emit error.
2699 Diag(DSStart, diag::err_missing_param);
2701 // Otherwise, we have something. Add it and let semantic analysis try
2702 // to grok it and add the result to the ParamInfo we are building.
2704 // Inform the actions module about the parameter declarator, so it gets
2705 // added to the current scope.
2706 DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2708 // Parse the default argument, if any. We parse the default
2709 // arguments in all dialects; the semantic analysis in
2710 // ActOnParamDefaultArgument will reject the default argument in
2712 if (Tok.is(tok::equal)) {
2713 SourceLocation EqualLoc = Tok.getLocation();
2715 // Parse the default argument
2716 if (D.getContext() == Declarator::MemberContext) {
2717 // If we're inside a class definition, cache the tokens
2718 // corresponding to the default argument. We'll actually parse
2719 // them when we see the end of the class definition.
2720 // FIXME: Templates will require something similar.
2721 // FIXME: Can we use a smart pointer for Toks?
2722 DefArgToks = new CachedTokens;
2724 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2725 tok::semi, false)) {
2728 Actions.ActOnParamDefaultArgumentError(Param);
2730 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2731 (*DefArgToks)[1].getLocation());
2736 OwningExprResult DefArgResult(ParseAssignmentExpression());
2737 if (DefArgResult.isInvalid()) {
2738 Actions.ActOnParamDefaultArgumentError(Param);
2739 SkipUntil(tok::comma, tok::r_paren, true, true);
2741 // Inform the actions module about the default argument
2742 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2743 move(DefArgResult));
2748 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2749 ParmDecl.getIdentifierLoc(), Param,
2753 // If the next token is a comma, consume it and keep reading arguments.
2754 if (Tok.isNot(tok::comma)) {
2755 if (Tok.is(tok::ellipsis)) {
2757 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
2759 if (!getLang().CPlusPlus) {
2760 // We have ellipsis without a preceding ',', which is ill-formed
2761 // in C. Complain and provide the fix.
2762 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
2763 << CodeModificationHint::CreateInsertion(EllipsisLoc, ", ");
2770 // Consume the comma.
2774 // Leave prototype scope.
2775 PrototypeScope.Exit();
2777 // If we have the closing ')', eat it.
2778 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2779 SourceLocation EndLoc = RParenLoc;
2782 bool hasExceptionSpec = false;
2783 SourceLocation ThrowLoc;
2784 bool hasAnyExceptionSpec = false;
2785 llvm::SmallVector<TypeTy*, 2> Exceptions;
2786 llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2788 if (getLang().CPlusPlus) {
2789 // Parse cv-qualifier-seq[opt].
2790 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2791 if (!DS.getSourceRange().getEnd().isInvalid())
2792 EndLoc = DS.getSourceRange().getEnd();
2794 // Parse exception-specification[opt].
2795 if (Tok.is(tok::kw_throw)) {
2796 hasExceptionSpec = true;
2797 ThrowLoc = Tok.getLocation();
2798 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2799 hasAnyExceptionSpec);
2800 assert(Exceptions.size() == ExceptionRanges.size() &&
2801 "Produced different number of exception types and ranges.");
2805 // Remember that we parsed a function type, and remember the attributes.
2806 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
2808 ParamInfo.data(), ParamInfo.size(),
2809 DS.getTypeQualifiers(),
2810 hasExceptionSpec, ThrowLoc,
2811 hasAnyExceptionSpec,
2813 ExceptionRanges.data(),
2815 LParenLoc, RParenLoc, D),
2819 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2820 /// we found a K&R-style identifier list instead of a type argument list. The
2821 /// current token is known to be the first identifier in the list.
2823 /// identifier-list: [C99 6.7.5]
2825 /// identifier-list ',' identifier
2827 void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2829 // Build up an array of information about the parsed arguments.
2830 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2831 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2833 // If there was no identifier specified for the declarator, either we are in
2834 // an abstract-declarator, or we are in a parameter declarator which was found
2835 // to be abstract. In abstract-declarators, identifier lists are not valid:
2837 if (!D.getIdentifier())
2838 Diag(Tok, diag::ext_ident_list_in_param);
2840 // Tok is known to be the first identifier in the list. Remember this
2841 // identifier in ParamInfo.
2842 ParamsSoFar.insert(Tok.getIdentifierInfo());
2843 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2847 ConsumeToken(); // eat the first identifier.
2849 while (Tok.is(tok::comma)) {
2853 // If this isn't an identifier, report the error and skip until ')'.
2854 if (Tok.isNot(tok::identifier)) {
2855 Diag(Tok, diag::err_expected_ident);
2856 SkipUntil(tok::r_paren);
2860 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
2862 // Reject 'typedef int y; int test(x, y)', but continue parsing.
2863 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
2864 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
2866 // Verify that the argument identifier has not already been mentioned.
2867 if (!ParamsSoFar.insert(ParmII)) {
2868 Diag(Tok, diag::err_param_redefinition) << ParmII;
2870 // Remember this identifier in ParamInfo.
2871 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2876 // Eat the identifier.
2880 // If we have the closing ')', eat it and we're done.
2881 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2883 // Remember that we parsed a function type, and remember the attributes. This
2884 // function type is always a K&R style function type, which is not varargs and
2885 // has no prototype.
2886 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
2888 &ParamInfo[0], ParamInfo.size(),
2891 SourceLocation(), false, 0, 0, 0,
2892 LParenLoc, RLoc, D),
2896 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2897 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2898 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2899 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2900 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2901 void Parser::ParseBracketDeclarator(Declarator &D) {
2902 SourceLocation StartLoc = ConsumeBracket();
2904 // C array syntax has many features, but by-far the most common is [] and [4].
2905 // This code does a fast path to handle some of the most obvious cases.
2906 if (Tok.getKind() == tok::r_square) {
2907 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2909 CXX0XAttributeList Attr;
2910 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) {
2911 Attr = ParseCXX0XAttributes();
2914 // Remember that we parsed the empty array type.
2915 OwningExprResult NumElements(Actions);
2916 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
2920 } else if (Tok.getKind() == tok::numeric_constant &&
2921 GetLookAheadToken(1).is(tok::r_square)) {
2922 // [4] is very common. Parse the numeric constant expression.
2923 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
2926 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2928 CXX0XAttributeList Attr;
2929 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2930 Attr = ParseCXX0XAttributes();
2933 // If there was an error parsing the assignment-expression, recover.
2934 if (ExprRes.isInvalid())
2935 ExprRes.release(); // Deallocate expr, just use [].
2937 // Remember that we parsed a array type, and remember its features.
2938 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
2944 // If valid, this location is the position where we read the 'static' keyword.
2945 SourceLocation StaticLoc;
2946 if (Tok.is(tok::kw_static))
2947 StaticLoc = ConsumeToken();
2949 // If there is a type-qualifier-list, read it now.
2950 // Type qualifiers in an array subscript are a C99 feature.
2952 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2954 // If we haven't already read 'static', check to see if there is one after the
2955 // type-qualifier-list.
2956 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
2957 StaticLoc = ConsumeToken();
2959 // Handle "direct-declarator [ type-qual-list[opt] * ]".
2960 bool isStar = false;
2961 OwningExprResult NumElements(Actions);
2963 // Handle the case where we have '[*]' as the array size. However, a leading
2964 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
2965 // the the token after the star is a ']'. Since stars in arrays are
2966 // infrequent, use of lookahead is not costly here.
2967 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
2968 ConsumeToken(); // Eat the '*'.
2970 if (StaticLoc.isValid()) {
2971 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
2972 StaticLoc = SourceLocation(); // Drop the static.
2975 } else if (Tok.isNot(tok::r_square)) {
2976 // Note, in C89, this production uses the constant-expr production instead
2977 // of assignment-expr. The only difference is that assignment-expr allows
2978 // things like '=' and '*='. Sema rejects these in C89 mode because they
2979 // are not i-c-e's, so we don't need to distinguish between the two here.
2981 // Parse the constant-expression or assignment-expression now (depending
2983 if (getLang().CPlusPlus)
2984 NumElements = ParseConstantExpression();
2986 NumElements = ParseAssignmentExpression();
2989 // If there was an error parsing the assignment-expression, recover.
2990 if (NumElements.isInvalid()) {
2991 D.setInvalidType(true);
2992 // If the expression was invalid, skip it.
2993 SkipUntil(tok::r_square);
2997 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3000 CXX0XAttributeList Attr;
3001 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3002 Attr = ParseCXX0XAttributes();
3005 // Remember that we parsed a array type, and remember its features.
3006 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
3007 StaticLoc.isValid(), isStar,
3008 NumElements.release(),
3013 /// [GNU] typeof-specifier:
3014 /// typeof ( expressions )
3015 /// typeof ( type-name )
3016 /// [GNU/C++] typeof unary-expression
3018 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
3019 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
3021 SourceLocation StartLoc = ConsumeToken();
3025 SourceRange CastRange;
3026 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
3031 if (CastRange.getEnd().isInvalid())
3032 // FIXME: Not accurate, the range gets one token more than it should.
3033 DS.SetRangeEnd(Tok.getLocation());
3035 DS.SetRangeEnd(CastRange.getEnd());
3039 DS.SetTypeSpecError();
3043 const char *PrevSpec = 0;
3045 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3046 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
3048 Diag(StartLoc, DiagID) << PrevSpec;
3052 // If we get here, the operand to the typeof was an expresion.
3053 if (Operand.isInvalid()) {
3054 DS.SetTypeSpecError();
3058 const char *PrevSpec = 0;
3060 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3061 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3062 DiagID, Operand.release()))
3063 Diag(StartLoc, DiagID) << PrevSpec;