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, ParsedTemplateInfo(), AS_none,
360 getDeclSpecContextFromDeclaratorContext(Context));
362 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
363 // declaration-specifiers init-declarator-list[opt] ';'
364 if (Tok.is(tok::semi)) {
366 DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
367 DS.complete(TheDecl);
368 return Actions.ConvertDeclToDeclGroup(TheDecl);
371 DeclGroupPtrTy DG = ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false,
376 /// ParseDeclGroup - Having concluded that this is either a function
377 /// definition or a group of object declarations, actually parse the
379 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
381 bool AllowFunctionDefinitions,
382 SourceLocation *DeclEnd) {
383 // Parse the first declarator.
384 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
387 // Bail out if the first declarator didn't seem well-formed.
388 if (!D.hasName() && !D.mayOmitIdentifier()) {
389 // Skip until ; or }.
390 SkipUntil(tok::r_brace, true, true);
391 if (Tok.is(tok::semi))
393 return DeclGroupPtrTy();
396 if (AllowFunctionDefinitions && D.isFunctionDeclarator()) {
397 if (isDeclarationAfterDeclarator()) {
398 // Fall though. We have to check this first, though, because
399 // __attribute__ might be the start of a function definition in
401 } else if (isStartOfFunctionDefinition()) {
402 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
403 Diag(Tok, diag::err_function_declared_typedef);
405 // Recover by treating the 'typedef' as spurious.
406 DS.ClearStorageClassSpecs();
409 DeclPtrTy TheDecl = ParseFunctionDefinition(D);
410 return Actions.ConvertDeclToDeclGroup(TheDecl);
412 Diag(Tok, diag::err_expected_fn_body);
413 SkipUntil(tok::semi);
414 return DeclGroupPtrTy();
418 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
419 DeclPtrTy FirstDecl = ParseDeclarationAfterDeclarator(D);
420 D.complete(FirstDecl);
422 DeclsInGroup.push_back(FirstDecl);
424 // If we don't have a comma, it is either the end of the list (a ';') or an
426 while (Tok.is(tok::comma)) {
427 // Consume the comma.
430 // Parse the next declarator.
433 // Accept attributes in an init-declarator. In the first declarator in a
434 // declaration, these would be part of the declspec. In subsequent
435 // declarators, they become part of the declarator itself, so that they
436 // don't apply to declarators after *this* one. Examples:
437 // short __attribute__((common)) var; -> declspec
438 // short var __attribute__((common)); -> declarator
439 // short x, __attribute__((common)) var; -> declarator
440 if (Tok.is(tok::kw___attribute)) {
442 AttributeList *AttrList = ParseGNUAttributes(&Loc);
443 D.AddAttributes(AttrList, Loc);
448 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D);
449 D.complete(ThisDecl);
451 DeclsInGroup.push_back(ThisDecl);
455 *DeclEnd = Tok.getLocation();
457 if (Context != Declarator::ForContext &&
458 ExpectAndConsume(tok::semi,
459 Context == Declarator::FileContext
460 ? diag::err_invalid_token_after_toplevel_declarator
461 : diag::err_expected_semi_declaration)) {
462 SkipUntil(tok::r_brace, true, true);
463 if (Tok.is(tok::semi))
467 return Actions.FinalizeDeclaratorGroup(CurScope, DS,
469 DeclsInGroup.size());
472 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
473 /// declarator'. This method parses the remainder of the declaration
474 /// (including any attributes or initializer, among other things) and
475 /// finalizes the declaration.
477 /// init-declarator: [C99 6.7]
479 /// declarator '=' initializer
480 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
481 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
482 /// [C++] declarator initializer[opt]
484 /// [C++] initializer:
485 /// [C++] '=' initializer-clause
486 /// [C++] '(' expression-list ')'
487 /// [C++0x] '=' 'default' [TODO]
488 /// [C++0x] '=' 'delete'
490 /// According to the standard grammar, =default and =delete are function
491 /// definitions, but that definitely doesn't fit with the parser here.
493 Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D,
494 const ParsedTemplateInfo &TemplateInfo) {
495 // If a simple-asm-expr is present, parse it.
496 if (Tok.is(tok::kw_asm)) {
498 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
499 if (AsmLabel.isInvalid()) {
500 SkipUntil(tok::semi, true, true);
504 D.setAsmLabel(AsmLabel.release());
508 // If attributes are present, parse them.
509 if (Tok.is(tok::kw___attribute)) {
511 AttributeList *AttrList = ParseGNUAttributes(&Loc);
512 D.AddAttributes(AttrList, Loc);
515 // Inform the current actions module that we just parsed this declarator.
517 switch (TemplateInfo.Kind) {
518 case ParsedTemplateInfo::NonTemplate:
519 ThisDecl = Actions.ActOnDeclarator(CurScope, D);
522 case ParsedTemplateInfo::Template:
523 case ParsedTemplateInfo::ExplicitSpecialization:
524 ThisDecl = Actions.ActOnTemplateDeclarator(CurScope,
525 Action::MultiTemplateParamsArg(Actions,
526 TemplateInfo.TemplateParams->data(),
527 TemplateInfo.TemplateParams->size()),
531 case ParsedTemplateInfo::ExplicitInstantiation: {
532 Action::DeclResult ThisRes
533 = Actions.ActOnExplicitInstantiation(CurScope,
534 TemplateInfo.ExternLoc,
535 TemplateInfo.TemplateLoc,
537 if (ThisRes.isInvalid()) {
538 SkipUntil(tok::semi, true, true);
542 ThisDecl = ThisRes.get();
547 // Parse declarator '=' initializer.
548 if (Tok.is(tok::equal)) {
550 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
551 SourceLocation DelLoc = ConsumeToken();
552 Actions.SetDeclDeleted(ThisDecl, DelLoc);
554 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
556 Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
559 OwningExprResult Init(ParseInitializer());
561 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
562 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
566 if (Init.isInvalid()) {
567 SkipUntil(tok::comma, true, true);
568 Actions.ActOnInitializerError(ThisDecl);
570 Actions.AddInitializerToDecl(ThisDecl, move(Init));
572 } else if (Tok.is(tok::l_paren)) {
573 // Parse C++ direct initializer: '(' expression-list ')'
574 SourceLocation LParenLoc = ConsumeParen();
575 ExprVector Exprs(Actions);
576 CommaLocsTy CommaLocs;
578 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
580 Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
583 if (ParseExpressionList(Exprs, CommaLocs)) {
584 SkipUntil(tok::r_paren);
586 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
587 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
592 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
594 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
595 "Unexpected number of commas!");
597 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
598 Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
602 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
604 CommaLocs.data(), RParenLoc);
607 bool TypeContainsUndeducedAuto =
608 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
609 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto);
615 /// ParseSpecifierQualifierList
616 /// specifier-qualifier-list:
617 /// type-specifier specifier-qualifier-list[opt]
618 /// type-qualifier specifier-qualifier-list[opt]
619 /// [GNU] attributes specifier-qualifier-list[opt]
621 void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
622 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
623 /// parse declaration-specifiers and complain about extra stuff.
624 ParseDeclarationSpecifiers(DS);
626 // Validate declspec for type-name.
627 unsigned Specs = DS.getParsedSpecifiers();
628 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
630 Diag(Tok, diag::err_typename_requires_specqual);
632 // Issue diagnostic and remove storage class if present.
633 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
634 if (DS.getStorageClassSpecLoc().isValid())
635 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
637 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
638 DS.ClearStorageClassSpecs();
641 // Issue diagnostic and remove function specfier if present.
642 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
643 if (DS.isInlineSpecified())
644 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
645 if (DS.isVirtualSpecified())
646 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
647 if (DS.isExplicitSpecified())
648 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
649 DS.ClearFunctionSpecs();
653 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
654 /// specified token is valid after the identifier in a declarator which
655 /// immediately follows the declspec. For example, these things are valid:
657 /// int x [ 4]; // direct-declarator
658 /// int x ( int y); // direct-declarator
659 /// int(int x ) // direct-declarator
660 /// int x ; // simple-declaration
661 /// int x = 17; // init-declarator-list
662 /// int x , y; // init-declarator-list
663 /// int x __asm__ ("foo"); // init-declarator-list
664 /// int x : 4; // struct-declarator
665 /// int x { 5}; // C++'0x unified initializers
667 /// This is not, because 'x' does not immediately follow the declspec (though
668 /// ')' happens to be valid anyway).
671 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
672 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
673 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
674 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
678 /// ParseImplicitInt - This method is called when we have an non-typename
679 /// identifier in a declspec (which normally terminates the decl spec) when
680 /// the declspec has no type specifier. In this case, the declspec is either
681 /// malformed or is "implicit int" (in K&R and C89).
683 /// This method handles diagnosing this prettily and returns false if the
684 /// declspec is done being processed. If it recovers and thinks there may be
685 /// other pieces of declspec after it, it returns true.
687 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
688 const ParsedTemplateInfo &TemplateInfo,
689 AccessSpecifier AS) {
690 assert(Tok.is(tok::identifier) && "should have identifier");
692 SourceLocation Loc = Tok.getLocation();
693 // If we see an identifier that is not a type name, we normally would
694 // parse it as the identifer being declared. However, when a typename
695 // is typo'd or the definition is not included, this will incorrectly
696 // parse the typename as the identifier name and fall over misparsing
697 // later parts of the diagnostic.
699 // As such, we try to do some look-ahead in cases where this would
700 // otherwise be an "implicit-int" case to see if this is invalid. For
701 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
702 // an identifier with implicit int, we'd get a parse error because the
703 // next token is obviously invalid for a type. Parse these as a case
704 // with an invalid type specifier.
705 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
707 // Since we know that this either implicit int (which is rare) or an
708 // error, we'd do lookahead to try to do better recovery.
709 if (isValidAfterIdentifierInDeclarator(NextToken())) {
710 // If this token is valid for implicit int, e.g. "static x = 4", then
711 // we just avoid eating the identifier, so it will be parsed as the
712 // identifier in the declarator.
716 // Otherwise, if we don't consume this token, we are going to emit an
717 // error anyway. Try to recover from various common problems. Check
718 // to see if this was a reference to a tag name without a tag specified.
719 // This is a common problem in C (saying 'foo' instead of 'struct foo').
721 // C++ doesn't need this, and isTagName doesn't take SS.
723 const char *TagName = 0;
724 tok::TokenKind TagKind = tok::unknown;
726 switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
728 case DeclSpec::TST_enum: TagName="enum" ;TagKind=tok::kw_enum ;break;
729 case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
730 case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
731 case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
735 Diag(Loc, diag::err_use_of_tag_name_without_tag)
736 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
737 << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName);
739 // Parse this as a tag as if the missing tag were present.
740 if (TagKind == tok::kw_enum)
741 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
743 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
748 // This is almost certainly an invalid type name. Let the action emit a
749 // diagnostic and attempt to recover.
750 Action::TypeTy *T = 0;
751 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
753 // The action emitted a diagnostic, so we don't have to.
755 // The action has suggested that the type T could be used. Set that as
756 // the type in the declaration specifiers, consume the would-be type
757 // name token, and we're done.
758 const char *PrevSpec;
760 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
762 DS.SetRangeEnd(Tok.getLocation());
765 // There may be other declaration specifiers after this.
769 // Fall through; the action had no suggestion for us.
771 // The action did not emit a diagnostic, so emit one now.
773 if (SS) R = SS->getRange();
774 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
777 // Mark this as an error.
778 const char *PrevSpec;
780 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
781 DS.SetRangeEnd(Tok.getLocation());
784 // TODO: Could inject an invalid typedef decl in an enclosing scope to
785 // avoid rippling error messages on subsequent uses of the same type,
786 // could be useful if #include was forgotten.
790 /// \brief Determine the declaration specifier context from the declarator
793 /// \param Context the declarator context, which is one of the
794 /// Declarator::TheContext enumerator values.
795 Parser::DeclSpecContext
796 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
797 if (Context == Declarator::MemberContext)
799 if (Context == Declarator::FileContext)
800 return DSC_top_level;
804 /// ParseDeclarationSpecifiers
805 /// declaration-specifiers: [C99 6.7]
806 /// storage-class-specifier declaration-specifiers[opt]
807 /// type-specifier declaration-specifiers[opt]
808 /// [C99] function-specifier declaration-specifiers[opt]
809 /// [GNU] attributes declaration-specifiers[opt]
811 /// storage-class-specifier: [C99 6.7.1]
819 /// function-specifier: [C99 6.7.4]
823 /// 'friend': [C++ dcl.friend]
824 /// 'constexpr': [C++0x dcl.constexpr]
827 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
828 const ParsedTemplateInfo &TemplateInfo,
830 DeclSpecContext DSContext) {
831 if (Tok.is(tok::code_completion)) {
832 Action::CodeCompletionContext CCC = Action::CCC_Namespace;
833 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
834 CCC = DSContext == DSC_class? Action::CCC_MemberTemplate
835 : Action::CCC_Template;
836 else if (DSContext == DSC_class)
837 CCC = Action::CCC_Class;
838 else if (ObjCImpDecl)
839 CCC = Action::CCC_ObjCImplementation;
841 Actions.CodeCompleteOrdinaryName(CurScope, CCC);
845 DS.SetRangeStart(Tok.getLocation());
847 bool isInvalid = false;
848 const char *PrevSpec = 0;
851 SourceLocation Loc = Tok.getLocation();
853 switch (Tok.getKind()) {
856 // If this is not a declaration specifier token, we're done reading decl
857 // specifiers. First verify that DeclSpec's are consistent.
858 DS.Finish(Diags, PP);
861 case tok::coloncolon: // ::foo::bar
862 // C++ scope specifier. Annotate and loop, or bail out on error.
863 if (TryAnnotateCXXScopeToken(true)) {
864 if (!DS.hasTypeSpecifier())
865 DS.SetTypeSpecError();
866 goto DoneWithDeclSpec;
868 if (Tok.is(tok::coloncolon)) // ::new or ::delete
869 goto DoneWithDeclSpec;
872 case tok::annot_cxxscope: {
873 if (DS.hasTypeSpecifier())
874 goto DoneWithDeclSpec;
877 SS.setScopeRep(Tok.getAnnotationValue());
878 SS.setRange(Tok.getAnnotationRange());
880 // We are looking for a qualified typename.
881 Token Next = NextToken();
882 if (Next.is(tok::annot_template_id) &&
883 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
884 ->Kind == TNK_Type_template) {
885 // We have a qualified template-id, e.g., N::A<int>
887 // C++ [class.qual]p2:
888 // In a lookup in which the constructor is an acceptable lookup
889 // result and the nested-name-specifier nominates a class C:
891 // - if the name specified after the
892 // nested-name-specifier, when looked up in C, is the
893 // injected-class-name of C (Clause 9), or
895 // - if the name specified after the nested-name-specifier
896 // is the same as the identifier or the
897 // simple-template-id's template-name in the last
898 // component of the nested-name-specifier,
900 // the name is instead considered to name the constructor of
903 // Thus, if the template-name is actually the constructor
904 // name, then the code is ill-formed; this interpretation is
905 // reinforced by the NAD status of core issue 635.
906 TemplateIdAnnotation *TemplateId
907 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
908 if (DSContext == DSC_top_level && TemplateId->Name &&
909 Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) {
910 if (isConstructorDeclarator()) {
911 // The user meant this to be an out-of-line constructor
912 // definition, but template arguments are not allowed
913 // there. Just allow this as a constructor; we'll
914 // complain about it later.
915 goto DoneWithDeclSpec;
918 // The user meant this to name a type, but it actually names
919 // a constructor with some extraneous template
920 // arguments. Complain, then parse it as a type as the user
922 Diag(TemplateId->TemplateNameLoc,
923 diag::err_out_of_line_template_id_names_constructor)
927 DS.getTypeSpecScope() = SS;
928 ConsumeToken(); // The C++ scope.
929 assert(Tok.is(tok::annot_template_id) &&
930 "ParseOptionalCXXScopeSpecifier not working");
931 AnnotateTemplateIdTokenAsType(&SS);
935 if (Next.is(tok::annot_typename)) {
936 DS.getTypeSpecScope() = SS;
937 ConsumeToken(); // The C++ scope.
938 if (Tok.getAnnotationValue())
939 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
941 Tok.getAnnotationValue());
943 DS.SetTypeSpecError();
944 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
945 ConsumeToken(); // The typename
948 if (Next.isNot(tok::identifier))
949 goto DoneWithDeclSpec;
951 // If we're in a context where the identifier could be a class name,
952 // check whether this is a constructor declaration.
953 if (DSContext == DSC_top_level &&
954 Actions.isCurrentClassName(*Next.getIdentifierInfo(), CurScope,
956 if (isConstructorDeclarator())
957 goto DoneWithDeclSpec;
959 // As noted in C++ [class.qual]p2 (cited above), when the name
960 // of the class is qualified in a context where it could name
961 // a constructor, its a constructor name. However, we've
962 // looked at the declarator, and the user probably meant this
963 // to be a type. Complain that it isn't supposed to be treated
964 // as a type, then proceed to parse it as a type.
965 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
966 << Next.getIdentifierInfo();
969 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
970 Next.getLocation(), CurScope, &SS);
972 // If the referenced identifier is not a type, then this declspec is
973 // erroneous: We already checked about that it has no type specifier, and
974 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
977 ConsumeToken(); // Eat the scope spec so the identifier is current.
978 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
979 goto DoneWithDeclSpec;
982 DS.getTypeSpecScope() = SS;
983 ConsumeToken(); // The C++ scope.
985 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
990 DS.SetRangeEnd(Tok.getLocation());
991 ConsumeToken(); // The typename.
996 case tok::annot_typename: {
997 if (Tok.getAnnotationValue())
998 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
999 DiagID, Tok.getAnnotationValue());
1001 DS.SetTypeSpecError();
1002 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1003 ConsumeToken(); // The typename
1005 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1006 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1007 // Objective-C interface. If we don't have Objective-C or a '<', this is
1008 // just a normal reference to a typedef name.
1009 if (!Tok.is(tok::less) || !getLang().ObjC1)
1012 SourceLocation LAngleLoc, EndProtoLoc;
1013 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1014 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1015 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1016 LAngleLoc, EndProtoLoc);
1017 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1018 ProtocolLocs.data(), LAngleLoc);
1020 DS.SetRangeEnd(EndProtoLoc);
1025 case tok::identifier: {
1026 // In C++, check to see if this is a scope specifier like foo::bar::, if
1027 // so handle it as such. This is important for ctor parsing.
1028 if (getLang().CPlusPlus) {
1029 if (TryAnnotateCXXScopeToken(true)) {
1030 if (!DS.hasTypeSpecifier())
1031 DS.SetTypeSpecError();
1032 goto DoneWithDeclSpec;
1034 if (!Tok.is(tok::identifier))
1038 // This identifier can only be a typedef name if we haven't already seen
1039 // a type-specifier. Without this check we misparse:
1040 // typedef int X; struct Y { short X; }; as 'short int'.
1041 if (DS.hasTypeSpecifier())
1042 goto DoneWithDeclSpec;
1044 // Check for need to substitute AltiVec keyword tokens.
1045 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1048 // It has to be available as a typedef too!
1049 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
1050 Tok.getLocation(), CurScope);
1052 // If this is not a typedef name, don't parse it as part of the declspec,
1053 // it must be an implicit int or an error.
1055 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1056 goto DoneWithDeclSpec;
1059 // If we're in a context where the identifier could be a class name,
1060 // check whether this is a constructor declaration.
1061 if (getLang().CPlusPlus && DSContext == DSC_class &&
1062 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
1063 isConstructorDeclarator())
1064 goto DoneWithDeclSpec;
1066 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1071 DS.SetRangeEnd(Tok.getLocation());
1072 ConsumeToken(); // The identifier
1074 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1075 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1076 // Objective-C interface. If we don't have Objective-C or a '<', this is
1077 // just a normal reference to a typedef name.
1078 if (!Tok.is(tok::less) || !getLang().ObjC1)
1081 SourceLocation LAngleLoc, EndProtoLoc;
1082 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1083 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1084 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1085 LAngleLoc, EndProtoLoc);
1086 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1087 ProtocolLocs.data(), LAngleLoc);
1089 DS.SetRangeEnd(EndProtoLoc);
1091 // Need to support trailing type qualifiers (e.g. "id<p> const").
1092 // If a type specifier follows, it will be diagnosed elsewhere.
1097 case tok::annot_template_id: {
1098 TemplateIdAnnotation *TemplateId
1099 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1100 if (TemplateId->Kind != TNK_Type_template) {
1101 // This template-id does not refer to a type name, so we're
1102 // done with the type-specifiers.
1103 goto DoneWithDeclSpec;
1106 // If we're in a context where the template-id could be a
1107 // constructor name or specialization, check whether this is a
1108 // constructor declaration.
1109 if (getLang().CPlusPlus && DSContext == DSC_class &&
1110 Actions.isCurrentClassName(*TemplateId->Name, CurScope) &&
1111 isConstructorDeclarator())
1112 goto DoneWithDeclSpec;
1114 // Turn the template-id annotation token into a type annotation
1115 // token, then try again to parse it as a type-specifier.
1116 AnnotateTemplateIdTokenAsType();
1120 // GNU attributes support.
1121 case tok::kw___attribute:
1122 DS.AddAttributes(ParseGNUAttributes());
1125 // Microsoft declspec support.
1126 case tok::kw___declspec:
1127 DS.AddAttributes(ParseMicrosoftDeclSpec());
1130 // Microsoft single token adornments.
1131 case tok::kw___forceinline:
1132 // FIXME: Add handling here!
1135 case tok::kw___ptr64:
1137 case tok::kw___cdecl:
1138 case tok::kw___stdcall:
1139 case tok::kw___fastcall:
1140 DS.AddAttributes(ParseMicrosoftTypeAttributes());
1143 // storage-class-specifier
1144 case tok::kw_typedef:
1145 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1148 case tok::kw_extern:
1149 if (DS.isThreadSpecified())
1150 Diag(Tok, diag::ext_thread_before) << "extern";
1151 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1154 case tok::kw___private_extern__:
1155 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1158 case tok::kw_static:
1159 if (DS.isThreadSpecified())
1160 Diag(Tok, diag::ext_thread_before) << "static";
1161 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1165 if (getLang().CPlusPlus0x)
1166 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1169 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1172 case tok::kw_register:
1173 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1176 case tok::kw_mutable:
1177 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1180 case tok::kw___thread:
1181 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1184 // function-specifier
1185 case tok::kw_inline:
1186 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1188 case tok::kw_virtual:
1189 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1191 case tok::kw_explicit:
1192 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1196 case tok::kw_friend:
1197 if (DSContext == DSC_class)
1198 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1200 PrevSpec = ""; // not actually used by the diagnostic
1201 DiagID = diag::err_friend_invalid_in_context;
1207 case tok::kw_constexpr:
1208 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1213 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1217 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1218 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1221 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1224 case tok::kw_signed:
1225 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1228 case tok::kw_unsigned:
1229 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1232 case tok::kw__Complex:
1233 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1236 case tok::kw__Imaginary:
1237 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1241 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1245 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1249 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1253 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1256 case tok::kw_double:
1257 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1260 case tok::kw_wchar_t:
1261 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1264 case tok::kw_char16_t:
1265 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1268 case tok::kw_char32_t:
1269 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1274 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1277 case tok::kw__Decimal32:
1278 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1281 case tok::kw__Decimal64:
1282 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1285 case tok::kw__Decimal128:
1286 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1289 case tok::kw___vector:
1290 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1292 case tok::kw___pixel:
1293 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1298 case tok::kw_struct:
1299 case tok::kw_union: {
1300 tok::TokenKind Kind = Tok.getKind();
1302 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1309 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1314 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1317 case tok::kw_volatile:
1318 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1321 case tok::kw_restrict:
1322 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1326 // C++ typename-specifier:
1327 case tok::kw_typename:
1328 if (TryAnnotateTypeOrScopeToken()) {
1329 DS.SetTypeSpecError();
1330 goto DoneWithDeclSpec;
1332 if (!Tok.is(tok::kw_typename))
1336 // GNU typeof support.
1337 case tok::kw_typeof:
1338 ParseTypeofSpecifier(DS);
1341 case tok::kw_decltype:
1342 ParseDecltypeSpecifier(DS);
1346 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1347 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
1348 // but we support it.
1349 if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1350 goto DoneWithDeclSpec;
1353 SourceLocation LAngleLoc, EndProtoLoc;
1354 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1355 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1356 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1357 LAngleLoc, EndProtoLoc);
1358 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1359 ProtocolLocs.data(), LAngleLoc);
1360 DS.SetRangeEnd(EndProtoLoc);
1362 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1363 << CodeModificationHint::CreateInsertion(Loc, "id")
1364 << SourceRange(Loc, EndProtoLoc);
1365 // Need to support trailing type qualifiers (e.g. "id<p> const").
1366 // If a type specifier follows, it will be diagnosed elsewhere.
1370 // If the specifier wasn't legal, issue a diagnostic.
1372 assert(PrevSpec && "Method did not return previous specifier!");
1374 Diag(Tok, DiagID) << PrevSpec;
1376 DS.SetRangeEnd(Tok.getLocation());
1381 /// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1382 /// primarily follow the C++ grammar with additions for C99 and GNU,
1383 /// which together subsume the C grammar. Note that the C++
1384 /// type-specifier also includes the C type-qualifier (for const,
1385 /// volatile, and C99 restrict). Returns true if a type-specifier was
1386 /// found (and parsed), false otherwise.
1388 /// type-specifier: [C++ 7.1.5]
1389 /// simple-type-specifier
1392 /// elaborated-type-specifier [TODO]
1395 /// cv-qualifier: [C++ 7.1.5.1]
1398 /// [C99] 'restrict'
1400 /// simple-type-specifier: [ C++ 7.1.5.2]
1401 /// '::'[opt] nested-name-specifier[opt] type-name [TODO]
1402 /// '::'[opt] nested-name-specifier 'template' template-id [TODO]
1415 /// [C99] '_Complex'
1416 /// [C99] '_Imaginary' // Removed in TC2?
1417 /// [GNU] '_Decimal32'
1418 /// [GNU] '_Decimal64'
1419 /// [GNU] '_Decimal128'
1420 /// [GNU] typeof-specifier
1421 /// [OBJC] class-name objc-protocol-refs[opt] [TODO]
1422 /// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
1423 /// [C++0x] 'decltype' ( expression )
1424 /// [AltiVec] '__vector'
1425 bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1426 const char *&PrevSpec,
1428 const ParsedTemplateInfo &TemplateInfo,
1429 bool SuppressDeclarations) {
1430 SourceLocation Loc = Tok.getLocation();
1432 switch (Tok.getKind()) {
1433 case tok::identifier: // foo::bar
1434 // Check for need to substitute AltiVec keyword tokens.
1435 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1438 case tok::kw_typename: // typename foo::bar
1439 // Annotate typenames and C++ scope specifiers. If we get one, just
1440 // recurse to handle whatever we get.
1441 if (TryAnnotateTypeOrScopeToken())
1443 if (Tok.is(tok::identifier))
1445 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1446 TemplateInfo, SuppressDeclarations);
1447 case tok::coloncolon: // ::foo::bar
1448 if (NextToken().is(tok::kw_new) || // ::new
1449 NextToken().is(tok::kw_delete)) // ::delete
1452 // Annotate typenames and C++ scope specifiers. If we get one, just
1453 // recurse to handle whatever we get.
1454 if (TryAnnotateTypeOrScopeToken())
1456 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1457 TemplateInfo, SuppressDeclarations);
1459 // simple-type-specifier:
1460 case tok::annot_typename: {
1461 if (Tok.getAnnotationValue())
1462 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1463 DiagID, Tok.getAnnotationValue());
1465 DS.SetTypeSpecError();
1466 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1467 ConsumeToken(); // The typename
1469 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1470 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1471 // Objective-C interface. If we don't have Objective-C or a '<', this is
1472 // just a normal reference to a typedef name.
1473 if (!Tok.is(tok::less) || !getLang().ObjC1)
1476 SourceLocation LAngleLoc, EndProtoLoc;
1477 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1478 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1479 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1480 LAngleLoc, EndProtoLoc);
1481 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1482 ProtocolLocs.data(), LAngleLoc);
1484 DS.SetRangeEnd(EndProtoLoc);
1489 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1492 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1493 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1496 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1499 case tok::kw_signed:
1500 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1502 case tok::kw_unsigned:
1503 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1506 case tok::kw__Complex:
1507 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1510 case tok::kw__Imaginary:
1511 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1515 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1518 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1521 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1524 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1526 case tok::kw_double:
1527 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1529 case tok::kw_wchar_t:
1530 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1532 case tok::kw_char16_t:
1533 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1535 case tok::kw_char32_t:
1536 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1540 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1542 case tok::kw__Decimal32:
1543 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1546 case tok::kw__Decimal64:
1547 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1550 case tok::kw__Decimal128:
1551 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1554 case tok::kw___vector:
1555 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1557 case tok::kw___pixel:
1558 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1563 case tok::kw_struct:
1564 case tok::kw_union: {
1565 tok::TokenKind Kind = Tok.getKind();
1567 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
1568 SuppressDeclarations);
1575 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
1580 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
1583 case tok::kw_volatile:
1584 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1587 case tok::kw_restrict:
1588 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1592 // GNU typeof support.
1593 case tok::kw_typeof:
1594 ParseTypeofSpecifier(DS);
1597 // C++0x decltype support.
1598 case tok::kw_decltype:
1599 ParseDecltypeSpecifier(DS);
1602 // C++0x auto support.
1604 if (!getLang().CPlusPlus0x)
1607 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1609 case tok::kw___ptr64:
1611 case tok::kw___cdecl:
1612 case tok::kw___stdcall:
1613 case tok::kw___fastcall:
1614 DS.AddAttributes(ParseMicrosoftTypeAttributes());
1618 // Not a type-specifier; do nothing.
1622 // If the specifier combination wasn't legal, issue a diagnostic.
1624 assert(PrevSpec && "Method did not return previous specifier!");
1625 // Pick between error or extwarn.
1626 Diag(Tok, DiagID) << PrevSpec;
1628 DS.SetRangeEnd(Tok.getLocation());
1629 ConsumeToken(); // whatever we parsed above.
1633 /// ParseStructDeclaration - Parse a struct declaration without the terminating
1636 /// struct-declaration:
1637 /// specifier-qualifier-list struct-declarator-list
1638 /// [GNU] __extension__ struct-declaration
1639 /// [GNU] specifier-qualifier-list
1640 /// struct-declarator-list:
1641 /// struct-declarator
1642 /// struct-declarator-list ',' struct-declarator
1643 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
1644 /// struct-declarator:
1646 /// [GNU] declarator attributes[opt]
1647 /// declarator[opt] ':' constant-expression
1648 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
1651 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
1652 if (Tok.is(tok::kw___extension__)) {
1653 // __extension__ silences extension warnings in the subexpression.
1654 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1656 return ParseStructDeclaration(DS, Fields);
1659 // Parse the common specifier-qualifiers-list piece.
1660 SourceLocation DSStart = Tok.getLocation();
1661 ParseSpecifierQualifierList(DS);
1663 // If there are no declarators, this is a free-standing declaration
1664 // specifier. Let the actions module cope with it.
1665 if (Tok.is(tok::semi)) {
1666 Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1670 // Read struct-declarators until we find the semicolon.
1671 bool FirstDeclarator = true;
1673 ParsingDeclRAIIObject PD(*this);
1674 FieldDeclarator DeclaratorInfo(DS);
1676 // Attributes are only allowed here on successive declarators.
1677 if (!FirstDeclarator && Tok.is(tok::kw___attribute)) {
1679 AttributeList *AttrList = ParseGNUAttributes(&Loc);
1680 DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1683 /// struct-declarator: declarator
1684 /// struct-declarator: declarator[opt] ':' constant-expression
1685 if (Tok.isNot(tok::colon)) {
1686 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1687 ColonProtectionRAIIObject X(*this);
1688 ParseDeclarator(DeclaratorInfo.D);
1691 if (Tok.is(tok::colon)) {
1693 OwningExprResult Res(ParseConstantExpression());
1694 if (Res.isInvalid())
1695 SkipUntil(tok::semi, true, true);
1697 DeclaratorInfo.BitfieldSize = Res.release();
1700 // If attributes exist after the declarator, parse them.
1701 if (Tok.is(tok::kw___attribute)) {
1703 AttributeList *AttrList = ParseGNUAttributes(&Loc);
1704 DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1707 // We're done with this declarator; invoke the callback.
1708 DeclPtrTy D = Fields.invoke(DeclaratorInfo);
1711 // If we don't have a comma, it is either the end of the list (a ';')
1712 // or an error, bail out.
1713 if (Tok.isNot(tok::comma))
1716 // Consume the comma.
1719 FirstDeclarator = false;
1723 /// ParseStructUnionBody
1724 /// struct-contents:
1725 /// struct-declaration-list
1727 /// [GNU] "struct-declaration-list" without terminatoring ';'
1728 /// struct-declaration-list:
1729 /// struct-declaration
1730 /// struct-declaration-list struct-declaration
1731 /// [OBC] '@' 'defs' '(' class-name ')'
1733 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1734 unsigned TagType, DeclPtrTy TagDecl) {
1735 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1736 PP.getSourceManager(),
1737 "parsing struct/union body");
1739 SourceLocation LBraceLoc = ConsumeBrace();
1741 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1742 Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1744 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1746 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1747 Diag(Tok, diag::ext_empty_struct_union_enum)
1748 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1750 llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1752 // While we still have something to read, read the declarations in the struct.
1753 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1754 // Each iteration of this loop reads one struct-declaration.
1756 // Check for extraneous top-level semicolon.
1757 if (Tok.is(tok::semi)) {
1758 Diag(Tok, diag::ext_extra_struct_semi)
1759 << CodeModificationHint::CreateRemoval(Tok.getLocation());
1764 // Parse all the comma separated declarators.
1767 if (!Tok.is(tok::at)) {
1768 struct CFieldCallback : FieldCallback {
1771 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls;
1773 CFieldCallback(Parser &P, DeclPtrTy TagDecl,
1774 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) :
1775 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
1777 virtual DeclPtrTy invoke(FieldDeclarator &FD) {
1778 // Install the declarator into the current TagDecl.
1779 DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl,
1780 FD.D.getDeclSpec().getSourceRange().getBegin(),
1781 FD.D, FD.BitfieldSize);
1782 FieldDecls.push_back(Field);
1785 } Callback(*this, TagDecl, FieldDecls);
1787 ParseStructDeclaration(DS, Callback);
1788 } else { // Handle @defs
1790 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1791 Diag(Tok, diag::err_unexpected_at);
1792 SkipUntil(tok::semi, true);
1796 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1797 if (!Tok.is(tok::identifier)) {
1798 Diag(Tok, diag::err_expected_ident);
1799 SkipUntil(tok::semi, true);
1802 llvm::SmallVector<DeclPtrTy, 16> Fields;
1803 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1804 Tok.getIdentifierInfo(), Fields);
1805 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1807 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1810 if (Tok.is(tok::semi)) {
1812 } else if (Tok.is(tok::r_brace)) {
1813 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
1816 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
1817 // Skip to end of block or statement to avoid ext-warning on extra ';'.
1818 SkipUntil(tok::r_brace, true, true);
1819 // If we stopped at a ';', eat it.
1820 if (Tok.is(tok::semi)) ConsumeToken();
1824 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1826 llvm::OwningPtr<AttributeList> AttrList;
1827 // If attributes exist after struct contents, parse them.
1828 if (Tok.is(tok::kw___attribute))
1829 AttrList.reset(ParseGNUAttributes());
1831 Actions.ActOnFields(CurScope,
1832 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1833 LBraceLoc, RBraceLoc,
1836 Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1840 /// ParseEnumSpecifier
1841 /// enum-specifier: [C99 6.7.2.2]
1842 /// 'enum' identifier[opt] '{' enumerator-list '}'
1843 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1844 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1845 /// '}' attributes[opt]
1846 /// 'enum' identifier
1847 /// [GNU] 'enum' attributes[opt] identifier
1849 /// [C++] elaborated-type-specifier:
1850 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
1852 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1853 const ParsedTemplateInfo &TemplateInfo,
1854 AccessSpecifier AS) {
1855 // Parse the tag portion of this.
1856 if (Tok.is(tok::code_completion)) {
1857 // Code completion for an enum name.
1858 Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1862 llvm::OwningPtr<AttributeList> Attr;
1863 // If attributes exist after tag, parse them.
1864 if (Tok.is(tok::kw___attribute))
1865 Attr.reset(ParseGNUAttributes());
1868 if (getLang().CPlusPlus) {
1869 if (ParseOptionalCXXScopeSpecifier(SS, 0, false))
1872 if (SS.isSet() && Tok.isNot(tok::identifier)) {
1873 Diag(Tok, diag::err_expected_ident);
1874 if (Tok.isNot(tok::l_brace)) {
1875 // Has no name and is not a definition.
1876 // Skip the rest of this declarator, up until the comma or semicolon.
1877 SkipUntil(tok::comma, true);
1883 // Must have either 'enum name' or 'enum {...}'.
1884 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1885 Diag(Tok, diag::err_expected_ident_lbrace);
1887 // Skip the rest of this declarator, up until the comma or semicolon.
1888 SkipUntil(tok::comma, true);
1892 // enums cannot be templates.
1893 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1894 Diag(Tok, diag::err_enum_template);
1896 // Skip the rest of this declarator, up until the comma or semicolon.
1897 SkipUntil(tok::comma, true);
1901 // If an identifier is present, consume and remember it.
1902 IdentifierInfo *Name = 0;
1903 SourceLocation NameLoc;
1904 if (Tok.is(tok::identifier)) {
1905 Name = Tok.getIdentifierInfo();
1906 NameLoc = ConsumeToken();
1909 // There are three options here. If we have 'enum foo;', then this is a
1910 // forward declaration. If we have 'enum foo {...' then this is a
1911 // definition. Otherwise we have something like 'enum foo xyz', a reference.
1913 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1914 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
1915 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
1917 Action::TagUseKind TUK;
1918 if (Tok.is(tok::l_brace))
1919 TUK = Action::TUK_Definition;
1920 else if (Tok.is(tok::semi))
1921 TUK = Action::TUK_Declaration;
1923 TUK = Action::TUK_Reference;
1925 bool IsDependent = false;
1926 DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1927 StartLoc, SS, Name, NameLoc, Attr.get(),
1929 Action::MultiTemplateParamsArg(Actions),
1930 Owned, IsDependent);
1931 assert(!IsDependent && "didn't expect dependent enum");
1933 if (Tok.is(tok::l_brace))
1934 ParseEnumBody(StartLoc, TagDecl);
1936 // FIXME: The DeclSpec should keep the locations of both the keyword and the
1937 // name (if there is one).
1938 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
1939 const char *PrevSpec = 0;
1941 if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID,
1942 TagDecl.getAs<void>(), Owned))
1943 Diag(StartLoc, DiagID) << PrevSpec;
1946 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
1947 /// enumerator-list:
1949 /// enumerator-list ',' enumerator
1951 /// enumeration-constant
1952 /// enumeration-constant '=' constant-expression
1953 /// enumeration-constant:
1956 void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1957 // Enter the scope of the enum body and start the definition.
1958 ParseScope EnumScope(this, Scope::DeclScope);
1959 Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1961 SourceLocation LBraceLoc = ConsumeBrace();
1963 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1964 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1965 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1967 llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1969 DeclPtrTy LastEnumConstDecl;
1971 // Parse the enumerator-list.
1972 while (Tok.is(tok::identifier)) {
1973 IdentifierInfo *Ident = Tok.getIdentifierInfo();
1974 SourceLocation IdentLoc = ConsumeToken();
1976 SourceLocation EqualLoc;
1977 OwningExprResult AssignedVal(Actions);
1978 if (Tok.is(tok::equal)) {
1979 EqualLoc = ConsumeToken();
1980 AssignedVal = ParseConstantExpression();
1981 if (AssignedVal.isInvalid())
1982 SkipUntil(tok::comma, tok::r_brace, true, true);
1985 // Install the enumerator constant into EnumDecl.
1986 DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1990 AssignedVal.release());
1991 EnumConstantDecls.push_back(EnumConstDecl);
1992 LastEnumConstDecl = EnumConstDecl;
1994 if (Tok.isNot(tok::comma))
1996 SourceLocation CommaLoc = ConsumeToken();
1998 if (Tok.isNot(tok::identifier) &&
1999 !(getLang().C99 || getLang().CPlusPlus0x))
2000 Diag(CommaLoc, diag::ext_enumerator_list_comma)
2001 << getLang().CPlusPlus
2002 << CodeModificationHint::CreateRemoval(CommaLoc);
2006 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2008 llvm::OwningPtr<AttributeList> Attr;
2009 // If attributes exist after the identifier list, parse them.
2010 if (Tok.is(tok::kw___attribute))
2011 Attr.reset(ParseGNUAttributes()); // FIXME: where do they do?
2013 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2014 EnumConstantDecls.data(), EnumConstantDecls.size(),
2015 CurScope, Attr.get());
2018 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
2021 /// isTypeSpecifierQualifier - Return true if the current token could be the
2022 /// start of a type-qualifier-list.
2023 bool Parser::isTypeQualifier() const {
2024 switch (Tok.getKind()) {
2025 default: return false;
2028 case tok::kw_volatile:
2029 case tok::kw_restrict:
2034 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2035 /// is definitely a type-specifier. Return false if it isn't part of a type
2036 /// specifier or if we're not sure.
2037 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2038 switch (Tok.getKind()) {
2039 default: return false;
2043 case tok::kw_signed:
2044 case tok::kw_unsigned:
2045 case tok::kw__Complex:
2046 case tok::kw__Imaginary:
2049 case tok::kw_wchar_t:
2050 case tok::kw_char16_t:
2051 case tok::kw_char32_t:
2054 case tok::kw_double:
2057 case tok::kw__Decimal32:
2058 case tok::kw__Decimal64:
2059 case tok::kw__Decimal128:
2060 case tok::kw___vector:
2062 // struct-or-union-specifier (C99) or class-specifier (C++)
2064 case tok::kw_struct:
2070 case tok::annot_typename:
2075 /// isTypeSpecifierQualifier - Return true if the current token could be the
2076 /// start of a specifier-qualifier-list.
2077 bool Parser::isTypeSpecifierQualifier() {
2078 switch (Tok.getKind()) {
2079 default: return false;
2081 case tok::identifier: // foo::bar
2082 if (TryAltiVecVectorToken())
2085 case tok::kw_typename: // typename T::type
2086 // Annotate typenames and C++ scope specifiers. If we get one, just
2087 // recurse to handle whatever we get.
2088 if (TryAnnotateTypeOrScopeToken())
2090 if (Tok.is(tok::identifier))
2092 return isTypeSpecifierQualifier();
2094 case tok::coloncolon: // ::foo::bar
2095 if (NextToken().is(tok::kw_new) || // ::new
2096 NextToken().is(tok::kw_delete)) // ::delete
2099 if (TryAnnotateTypeOrScopeToken())
2101 return isTypeSpecifierQualifier();
2103 // GNU attributes support.
2104 case tok::kw___attribute:
2105 // GNU typeof support.
2106 case tok::kw_typeof:
2111 case tok::kw_signed:
2112 case tok::kw_unsigned:
2113 case tok::kw__Complex:
2114 case tok::kw__Imaginary:
2117 case tok::kw_wchar_t:
2118 case tok::kw_char16_t:
2119 case tok::kw_char32_t:
2122 case tok::kw_double:
2125 case tok::kw__Decimal32:
2126 case tok::kw__Decimal64:
2127 case tok::kw__Decimal128:
2128 case tok::kw___vector:
2130 // struct-or-union-specifier (C99) or class-specifier (C++)
2132 case tok::kw_struct:
2139 case tok::kw_volatile:
2140 case tok::kw_restrict:
2143 case tok::annot_typename:
2146 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2148 return getLang().ObjC1;
2150 case tok::kw___cdecl:
2151 case tok::kw___stdcall:
2152 case tok::kw___fastcall:
2154 case tok::kw___ptr64:
2159 /// isDeclarationSpecifier() - Return true if the current token is part of a
2160 /// declaration specifier.
2161 bool Parser::isDeclarationSpecifier() {
2162 switch (Tok.getKind()) {
2163 default: return false;
2165 case tok::identifier: // foo::bar
2166 // Unfortunate hack to support "Class.factoryMethod" notation.
2167 if (getLang().ObjC1 && NextToken().is(tok::period))
2169 if (TryAltiVecVectorToken())
2172 case tok::kw_typename: // typename T::type
2173 // Annotate typenames and C++ scope specifiers. If we get one, just
2174 // recurse to handle whatever we get.
2175 if (TryAnnotateTypeOrScopeToken())
2177 if (Tok.is(tok::identifier))
2179 return isDeclarationSpecifier();
2181 case tok::coloncolon: // ::foo::bar
2182 if (NextToken().is(tok::kw_new) || // ::new
2183 NextToken().is(tok::kw_delete)) // ::delete
2186 // Annotate typenames and C++ scope specifiers. If we get one, just
2187 // recurse to handle whatever we get.
2188 if (TryAnnotateTypeOrScopeToken())
2190 return isDeclarationSpecifier();
2192 // storage-class-specifier
2193 case tok::kw_typedef:
2194 case tok::kw_extern:
2195 case tok::kw___private_extern__:
2196 case tok::kw_static:
2198 case tok::kw_register:
2199 case tok::kw___thread:
2204 case tok::kw_signed:
2205 case tok::kw_unsigned:
2206 case tok::kw__Complex:
2207 case tok::kw__Imaginary:
2210 case tok::kw_wchar_t:
2211 case tok::kw_char16_t:
2212 case tok::kw_char32_t:
2216 case tok::kw_double:
2219 case tok::kw__Decimal32:
2220 case tok::kw__Decimal64:
2221 case tok::kw__Decimal128:
2222 case tok::kw___vector:
2224 // struct-or-union-specifier (C99) or class-specifier (C++)
2226 case tok::kw_struct:
2233 case tok::kw_volatile:
2234 case tok::kw_restrict:
2236 // function-specifier
2237 case tok::kw_inline:
2238 case tok::kw_virtual:
2239 case tok::kw_explicit:
2242 case tok::annot_typename:
2244 // GNU typeof support.
2245 case tok::kw_typeof:
2248 case tok::kw___attribute:
2251 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2253 return getLang().ObjC1;
2255 case tok::kw___declspec:
2256 case tok::kw___cdecl:
2257 case tok::kw___stdcall:
2258 case tok::kw___fastcall:
2260 case tok::kw___ptr64:
2261 case tok::kw___forceinline:
2266 bool Parser::isConstructorDeclarator() {
2267 TentativeParsingAction TPA(*this);
2269 // Parse the C++ scope specifier.
2271 if (ParseOptionalCXXScopeSpecifier(SS, 0, true)) {
2276 // Parse the constructor name.
2277 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2278 // We already know that we have a constructor name; just consume
2286 // Current class name must be followed by a left parentheses.
2287 if (Tok.isNot(tok::l_paren)) {
2293 // A right parentheses or ellipsis signals that we have a constructor.
2294 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2299 // If we need to, enter the specified scope.
2300 DeclaratorScopeObj DeclScopeObj(*this, SS);
2301 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(CurScope, SS))
2302 DeclScopeObj.EnterDeclaratorScope();
2304 // Check whether the next token(s) are part of a declaration
2305 // specifier, in which case we have the start of a parameter and,
2306 // therefore, we know that this is a constructor.
2307 bool IsConstructor = isDeclarationSpecifier();
2309 return IsConstructor;
2312 /// ParseTypeQualifierListOpt
2313 /// type-qualifier-list: [C99 6.7.5]
2315 /// [GNU] attributes [ only if AttributesAllowed=true ]
2316 /// type-qualifier-list type-qualifier
2317 /// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ]
2318 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2319 /// if CXX0XAttributesAllowed = true
2321 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed,
2322 bool CXX0XAttributesAllowed) {
2323 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2324 SourceLocation Loc = Tok.getLocation();
2325 CXX0XAttributeList Attr = ParseCXX0XAttributes();
2326 if (CXX0XAttributesAllowed)
2327 DS.AddAttributes(Attr.AttrList);
2329 Diag(Loc, diag::err_attributes_not_allowed);
2333 bool isInvalid = false;
2334 const char *PrevSpec = 0;
2335 unsigned DiagID = 0;
2336 SourceLocation Loc = Tok.getLocation();
2338 switch (Tok.getKind()) {
2340 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
2343 case tok::kw_volatile:
2344 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2347 case tok::kw_restrict:
2348 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2352 case tok::kw___ptr64:
2353 case tok::kw___cdecl:
2354 case tok::kw___stdcall:
2355 case tok::kw___fastcall:
2356 if (GNUAttributesAllowed) {
2357 DS.AddAttributes(ParseMicrosoftTypeAttributes());
2360 goto DoneWithTypeQuals;
2361 case tok::kw___attribute:
2362 if (GNUAttributesAllowed) {
2363 DS.AddAttributes(ParseGNUAttributes());
2364 continue; // do *not* consume the next token!
2366 // otherwise, FALL THROUGH!
2369 // If this is not a type-qualifier token, we're done reading type
2370 // qualifiers. First verify that DeclSpec's are consistent.
2371 DS.Finish(Diags, PP);
2375 // If the specifier combination wasn't legal, issue a diagnostic.
2377 assert(PrevSpec && "Method did not return previous specifier!");
2378 Diag(Tok, DiagID) << PrevSpec;
2385 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2387 void Parser::ParseDeclarator(Declarator &D) {
2388 /// This implements the 'declarator' production in the C grammar, then checks
2389 /// for well-formedness and issues diagnostics.
2390 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2393 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2394 /// is parsed by the function passed to it. Pass null, and the direct-declarator
2395 /// isn't parsed at all, making this function effectively parse the C++
2396 /// ptr-operator production.
2398 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2399 /// [C] pointer[opt] direct-declarator
2400 /// [C++] direct-declarator
2401 /// [C++] ptr-operator declarator
2403 /// pointer: [C99 6.7.5]
2404 /// '*' type-qualifier-list[opt]
2405 /// '*' type-qualifier-list[opt] pointer
2408 /// '*' cv-qualifier-seq[opt]
2411 /// [GNU] '&' restrict[opt] attributes[opt]
2412 /// [GNU?] '&&' restrict[opt] attributes[opt]
2413 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2414 void Parser::ParseDeclaratorInternal(Declarator &D,
2415 DirectDeclParseFunction DirectDeclParser) {
2416 if (Diags.hasAllExtensionsSilenced())
2418 // C++ member pointers start with a '::' or a nested-name.
2419 // Member pointers get special handling, since there's no place for the
2420 // scope spec in the generic path below.
2421 if (getLang().CPlusPlus &&
2422 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2423 Tok.is(tok::annot_cxxscope))) {
2425 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); // ignore fail
2428 if (Tok.isNot(tok::star)) {
2429 // The scope spec really belongs to the direct-declarator.
2430 D.getCXXScopeSpec() = SS;
2431 if (DirectDeclParser)
2432 (this->*DirectDeclParser)(D);
2436 SourceLocation Loc = ConsumeToken();
2439 ParseTypeQualifierListOpt(DS);
2440 D.ExtendWithDeclSpec(DS);
2442 // Recurse to parse whatever is left.
2443 ParseDeclaratorInternal(D, DirectDeclParser);
2445 // Sema will have to catch (syntactically invalid) pointers into global
2446 // scope. It has to catch pointers into namespace scope anyway.
2447 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2448 Loc, DS.TakeAttributes()),
2449 /* Don't replace range end. */SourceLocation());
2454 tok::TokenKind Kind = Tok.getKind();
2455 // Not a pointer, C++ reference, or block.
2456 if (Kind != tok::star && Kind != tok::caret &&
2457 (Kind != tok::amp || !getLang().CPlusPlus) &&
2458 // We parse rvalue refs in C++03, because otherwise the errors are scary.
2459 (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2460 if (DirectDeclParser)
2461 (this->*DirectDeclParser)(D);
2465 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2466 // '&&' -> rvalue reference
2467 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
2470 if (Kind == tok::star || Kind == tok::caret) {
2474 ParseTypeQualifierListOpt(DS);
2475 D.ExtendWithDeclSpec(DS);
2477 // Recursively parse the declarator.
2478 ParseDeclaratorInternal(D, DirectDeclParser);
2479 if (Kind == tok::star)
2480 // Remember that we parsed a pointer type, and remember the type-quals.
2481 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2482 DS.TakeAttributes()),
2485 // Remember that we parsed a Block type, and remember the type-quals.
2486 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2487 Loc, DS.TakeAttributes()),
2493 // Complain about rvalue references in C++03, but then go on and build
2495 if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2496 Diag(Loc, diag::err_rvalue_reference);
2498 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2499 // cv-qualifiers are introduced through the use of a typedef or of a
2500 // template type argument, in which case the cv-qualifiers are ignored.
2502 // [GNU] Retricted references are allowed.
2503 // [GNU] Attributes on references are allowed.
2504 // [C++0x] Attributes on references are not allowed.
2505 ParseTypeQualifierListOpt(DS, true, false);
2506 D.ExtendWithDeclSpec(DS);
2508 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2509 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2510 Diag(DS.getConstSpecLoc(),
2511 diag::err_invalid_reference_qualifier_application) << "const";
2512 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2513 Diag(DS.getVolatileSpecLoc(),
2514 diag::err_invalid_reference_qualifier_application) << "volatile";
2517 // Recursively parse the declarator.
2518 ParseDeclaratorInternal(D, DirectDeclParser);
2520 if (D.getNumTypeObjects() > 0) {
2521 // C++ [dcl.ref]p4: There shall be no references to references.
2522 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2523 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2524 if (const IdentifierInfo *II = D.getIdentifier())
2525 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2528 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2531 // Once we've complained about the reference-to-reference, we
2532 // can go ahead and build the (technically ill-formed)
2533 // declarator: reference collapsing will take care of it.
2537 // Remember that we parsed a reference type. It doesn't have type-quals.
2538 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2539 DS.TakeAttributes(),
2545 /// ParseDirectDeclarator
2546 /// direct-declarator: [C99 6.7.5]
2547 /// [C99] identifier
2548 /// '(' declarator ')'
2549 /// [GNU] '(' attributes declarator ')'
2550 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2551 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2552 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2553 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2554 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2555 /// direct-declarator '(' parameter-type-list ')'
2556 /// direct-declarator '(' identifier-list[opt] ')'
2557 /// [GNU] direct-declarator '(' parameter-forward-declarations
2558 /// parameter-type-list[opt] ')'
2559 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2560 /// cv-qualifier-seq[opt] exception-specification[opt]
2561 /// [C++] declarator-id
2563 /// declarator-id: [C++ 8]
2565 /// '::'[opt] nested-name-specifier[opt] type-name
2567 /// id-expression: [C++ 5.1]
2571 /// unqualified-id: [C++ 5.1]
2573 /// operator-function-id
2574 /// conversion-function-id
2578 void Parser::ParseDirectDeclarator(Declarator &D) {
2579 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2581 if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
2582 // ParseDeclaratorInternal might already have parsed the scope.
2583 bool afterCXXScope = D.getCXXScopeSpec().isSet();
2584 if (!afterCXXScope) {
2585 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2587 afterCXXScope = D.getCXXScopeSpec().isSet();
2590 if (afterCXXScope) {
2591 if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2592 // Change the declaration context for name lookup, until this function
2593 // is exited (and the declarator has been parsed).
2594 DeclScopeObj.EnterDeclaratorScope();
2597 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
2598 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
2599 // We found something that indicates the start of an unqualified-id.
2600 // Parse that unqualified-id.
2601 bool AllowConstructorName
2602 = ((D.getCXXScopeSpec().isSet() &&
2603 D.getContext() == Declarator::FileContext) ||
2604 (!D.getCXXScopeSpec().isSet() &&
2605 D.getContext() == Declarator::MemberContext)) &&
2606 !D.getDeclSpec().hasTypeSpecifier();
2607 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
2608 /*EnteringContext=*/true,
2609 /*AllowDestructorName=*/true,
2610 AllowConstructorName,
2613 D.SetIdentifier(0, Tok.getLocation());
2614 D.setInvalidType(true);
2616 // Parsed the unqualified-id; update range information and move along.
2617 if (D.getSourceRange().getBegin().isInvalid())
2618 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
2619 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
2621 goto PastIdentifier;
2623 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2624 assert(!getLang().CPlusPlus &&
2625 "There's a C++-specific check for tok::identifier above");
2626 assert(Tok.getIdentifierInfo() && "Not an identifier?");
2627 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2629 goto PastIdentifier;
2632 if (Tok.is(tok::l_paren)) {
2633 // direct-declarator: '(' declarator ')'
2634 // direct-declarator: '(' attributes declarator ')'
2635 // Example: 'char (*X)' or 'int (*XX)(void)'
2636 ParseParenDeclarator(D);
2638 // If the declarator was parenthesized, we entered the declarator
2639 // scope when parsing the parenthesized declarator, then exited
2640 // the scope already. Re-enter the scope, if we need to.
2641 if (D.getCXXScopeSpec().isSet()) {
2642 if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2643 // Change the declaration context for name lookup, until this function
2644 // is exited (and the declarator has been parsed).
2645 DeclScopeObj.EnterDeclaratorScope();
2647 } else if (D.mayOmitIdentifier()) {
2648 // This could be something simple like "int" (in which case the declarator
2649 // portion is empty), if an abstract-declarator is allowed.
2650 D.SetIdentifier(0, Tok.getLocation());
2652 if (D.getContext() == Declarator::MemberContext)
2653 Diag(Tok, diag::err_expected_member_name_or_semi)
2654 << D.getDeclSpec().getSourceRange();
2655 else if (getLang().CPlusPlus)
2656 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
2658 Diag(Tok, diag::err_expected_ident_lparen);
2659 D.SetIdentifier(0, Tok.getLocation());
2660 D.setInvalidType(true);
2664 assert(D.isPastIdentifier() &&
2665 "Haven't past the location of the identifier yet?");
2667 // Don't parse attributes unless we have an identifier.
2668 if (D.getIdentifier() && getLang().CPlusPlus0x
2669 && isCXX0XAttributeSpecifier(true)) {
2670 SourceLocation AttrEndLoc;
2671 CXX0XAttributeList Attr = ParseCXX0XAttributes();
2672 D.AddAttributes(Attr.AttrList, AttrEndLoc);
2676 if (Tok.is(tok::l_paren)) {
2677 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2678 // In such a case, check if we actually have a function declarator; if it
2679 // is not, the declarator has been fully parsed.
2680 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2681 // When not in file scope, warn for ambiguous function declarators, just
2682 // in case the author intended it as a variable definition.
2683 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2684 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2687 ParseFunctionDeclarator(ConsumeParen(), D);
2688 } else if (Tok.is(tok::l_square)) {
2689 ParseBracketDeclarator(D);
2696 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2697 /// only called before the identifier, so these are most likely just grouping
2698 /// parens for precedence. If we find that these are actually function
2699 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2701 /// direct-declarator:
2702 /// '(' declarator ')'
2703 /// [GNU] '(' attributes declarator ')'
2704 /// direct-declarator '(' parameter-type-list ')'
2705 /// direct-declarator '(' identifier-list[opt] ')'
2706 /// [GNU] direct-declarator '(' parameter-forward-declarations
2707 /// parameter-type-list[opt] ')'
2709 void Parser::ParseParenDeclarator(Declarator &D) {
2710 SourceLocation StartLoc = ConsumeParen();
2711 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2713 // Eat any attributes before we look at whether this is a grouping or function
2714 // declarator paren. If this is a grouping paren, the attribute applies to
2715 // the type being built up, for example:
2716 // int (__attribute__(()) *x)(long y)
2717 // If this ends up not being a grouping paren, the attribute applies to the
2718 // first argument, for example:
2719 // int (__attribute__(()) int x)
2720 // In either case, we need to eat any attributes to be able to determine what
2721 // sort of paren this is.
2723 llvm::OwningPtr<AttributeList> AttrList;
2724 bool RequiresArg = false;
2725 if (Tok.is(tok::kw___attribute)) {
2726 AttrList.reset(ParseGNUAttributes());
2728 // We require that the argument list (if this is a non-grouping paren) be
2729 // present even if the attribute list was empty.
2732 // Eat any Microsoft extensions.
2733 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2734 Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2735 Tok.is(tok::kw___ptr64)) {
2736 AttrList.reset(ParseMicrosoftTypeAttributes(AttrList.take()));
2739 // If we haven't past the identifier yet (or where the identifier would be
2740 // stored, if this is an abstract declarator), then this is probably just
2741 // grouping parens. However, if this could be an abstract-declarator, then
2742 // this could also be the start of function arguments (consider 'void()').
2745 if (!D.mayOmitIdentifier()) {
2746 // If this can't be an abstract-declarator, this *must* be a grouping
2747 // paren, because we haven't seen the identifier yet.
2749 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
2750 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2751 isDeclarationSpecifier()) { // 'int(int)' is a function.
2752 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2753 // considered to be a type, not a K&R identifier-list.
2756 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2760 // If this is a grouping paren, handle:
2761 // direct-declarator: '(' declarator ')'
2762 // direct-declarator: '(' attributes declarator ')'
2764 bool hadGroupingParens = D.hasGroupingParens();
2765 D.setGroupingParens(true);
2767 D.AddAttributes(AttrList.take(), SourceLocation());
2769 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2771 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2773 D.setGroupingParens(hadGroupingParens);
2778 // Okay, if this wasn't a grouping paren, it must be the start of a function
2779 // argument list. Recognize that this declarator will never have an
2780 // identifier (and remember where it would have been), then call into
2781 // ParseFunctionDeclarator to handle of argument list.
2782 D.SetIdentifier(0, Tok.getLocation());
2784 ParseFunctionDeclarator(StartLoc, D, AttrList.take(), RequiresArg);
2787 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
2788 /// declarator D up to a paren, which indicates that we are parsing function
2791 /// If AttrList is non-null, then the caller parsed those arguments immediately
2792 /// after the open paren - they should be considered to be the first argument of
2793 /// a parameter. If RequiresArg is true, then the first argument of the
2794 /// function is required to be present and required to not be an identifier
2797 /// This method also handles this portion of the grammar:
2798 /// parameter-type-list: [C99 6.7.5]
2800 /// parameter-list ',' '...'
2801 /// [C++] parameter-list '...'
2803 /// parameter-list: [C99 6.7.5]
2804 /// parameter-declaration
2805 /// parameter-list ',' parameter-declaration
2807 /// parameter-declaration: [C99 6.7.5]
2808 /// declaration-specifiers declarator
2809 /// [C++] declaration-specifiers declarator '=' assignment-expression
2810 /// [GNU] declaration-specifiers declarator attributes
2811 /// declaration-specifiers abstract-declarator[opt]
2812 /// [C++] declaration-specifiers abstract-declarator[opt]
2813 /// '=' assignment-expression
2814 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
2816 /// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2817 /// and "exception-specification[opt]".
2819 void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2820 AttributeList *AttrList,
2822 // lparen is already consumed!
2823 assert(D.isPastIdentifier() && "Should not call before identifier!");
2825 // This parameter list may be empty.
2826 if (Tok.is(tok::r_paren)) {
2828 Diag(Tok, diag::err_argument_required_after_attribute);
2832 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'.
2833 SourceLocation EndLoc = RParenLoc;
2835 // cv-qualifier-seq[opt].
2837 bool hasExceptionSpec = false;
2838 SourceLocation ThrowLoc;
2839 bool hasAnyExceptionSpec = false;
2840 llvm::SmallVector<TypeTy*, 2> Exceptions;
2841 llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2842 if (getLang().CPlusPlus) {
2843 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2844 if (!DS.getSourceRange().getEnd().isInvalid())
2845 EndLoc = DS.getSourceRange().getEnd();
2847 // Parse exception-specification[opt].
2848 if (Tok.is(tok::kw_throw)) {
2849 hasExceptionSpec = true;
2850 ThrowLoc = Tok.getLocation();
2851 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2852 hasAnyExceptionSpec);
2853 assert(Exceptions.size() == ExceptionRanges.size() &&
2854 "Produced different number of exception types and ranges.");
2858 // Remember that we parsed a function type, and remember the attributes.
2859 // int() -> no prototype, no '...'.
2860 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2864 DS.getTypeQualifiers(),
2865 hasExceptionSpec, ThrowLoc,
2866 hasAnyExceptionSpec,
2868 ExceptionRanges.data(),
2870 LParenLoc, RParenLoc, D),
2875 // Alternatively, this parameter list may be an identifier list form for a
2876 // K&R-style function: void foo(a,b,c)
2877 if (!getLang().CPlusPlus && Tok.is(tok::identifier)
2878 && !TryAltiVecVectorToken()) {
2879 if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
2880 // K&R identifier lists can't have typedefs as identifiers, per
2883 Diag(Tok, diag::err_argument_required_after_attribute);
2886 // Identifier list. Note that '(' identifier-list ')' is only allowed for
2887 // normal declarators, not for abstract-declarators.
2888 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2892 // Finally, a normal, non-empty parameter type list.
2894 // Build up an array of information about the parsed arguments.
2895 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2897 // Enter function-declaration scope, limiting any declarators to the
2898 // function prototype scope, including parameter declarators.
2899 ParseScope PrototypeScope(this,
2900 Scope::FunctionPrototypeScope|Scope::DeclScope);
2902 bool IsVariadic = false;
2903 SourceLocation EllipsisLoc;
2905 if (Tok.is(tok::ellipsis)) {
2907 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
2911 SourceLocation DSStart = Tok.getLocation();
2913 // Parse the declaration-specifiers.
2914 // Just use the ParsingDeclaration "scope" of the declarator.
2917 // If the caller parsed attributes for the first argument, add them now.
2919 DS.AddAttributes(AttrList);
2920 AttrList = 0; // Only apply the attributes to the first parameter.
2922 ParseDeclarationSpecifiers(DS);
2924 // Parse the declarator. This is "PrototypeContext", because we must
2925 // accept either 'declarator' or 'abstract-declarator' here.
2926 Declarator ParmDecl(DS, Declarator::PrototypeContext);
2927 ParseDeclarator(ParmDecl);
2929 // Parse GNU attributes, if present.
2930 if (Tok.is(tok::kw___attribute)) {
2932 AttributeList *AttrList = ParseGNUAttributes(&Loc);
2933 ParmDecl.AddAttributes(AttrList, Loc);
2936 // Remember this parsed parameter in ParamInfo.
2937 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2939 // DefArgToks is used when the parsing of default arguments needs
2941 CachedTokens *DefArgToks = 0;
2943 // If no parameter was specified, verify that *something* was specified,
2944 // otherwise we have a missing type and identifier.
2945 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2946 ParmDecl.getNumTypeObjects() == 0) {
2947 // Completely missing, emit error.
2948 Diag(DSStart, diag::err_missing_param);
2950 // Otherwise, we have something. Add it and let semantic analysis try
2951 // to grok it and add the result to the ParamInfo we are building.
2953 // Inform the actions module about the parameter declarator, so it gets
2954 // added to the current scope.
2955 DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2957 // Parse the default argument, if any. We parse the default
2958 // arguments in all dialects; the semantic analysis in
2959 // ActOnParamDefaultArgument will reject the default argument in
2961 if (Tok.is(tok::equal)) {
2962 SourceLocation EqualLoc = Tok.getLocation();
2964 // Parse the default argument
2965 if (D.getContext() == Declarator::MemberContext) {
2966 // If we're inside a class definition, cache the tokens
2967 // corresponding to the default argument. We'll actually parse
2968 // them when we see the end of the class definition.
2969 // FIXME: Templates will require something similar.
2970 // FIXME: Can we use a smart pointer for Toks?
2971 DefArgToks = new CachedTokens;
2973 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2974 tok::semi, false)) {
2977 Actions.ActOnParamDefaultArgumentError(Param);
2979 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2980 (*DefArgToks)[1].getLocation());
2985 OwningExprResult DefArgResult(ParseAssignmentExpression());
2986 if (DefArgResult.isInvalid()) {
2987 Actions.ActOnParamDefaultArgumentError(Param);
2988 SkipUntil(tok::comma, tok::r_paren, true, true);
2990 // Inform the actions module about the default argument
2991 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2992 move(DefArgResult));
2997 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2998 ParmDecl.getIdentifierLoc(), Param,
3002 // If the next token is a comma, consume it and keep reading arguments.
3003 if (Tok.isNot(tok::comma)) {
3004 if (Tok.is(tok::ellipsis)) {
3006 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
3008 if (!getLang().CPlusPlus) {
3009 // We have ellipsis without a preceding ',', which is ill-formed
3010 // in C. Complain and provide the fix.
3011 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3012 << CodeModificationHint::CreateInsertion(EllipsisLoc, ", ");
3019 // Consume the comma.
3023 // Leave prototype scope.
3024 PrototypeScope.Exit();
3026 // If we have the closing ')', eat it.
3027 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3028 SourceLocation EndLoc = RParenLoc;
3031 bool hasExceptionSpec = false;
3032 SourceLocation ThrowLoc;
3033 bool hasAnyExceptionSpec = false;
3034 llvm::SmallVector<TypeTy*, 2> Exceptions;
3035 llvm::SmallVector<SourceRange, 2> ExceptionRanges;
3037 if (getLang().CPlusPlus) {
3038 // Parse cv-qualifier-seq[opt].
3039 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3040 if (!DS.getSourceRange().getEnd().isInvalid())
3041 EndLoc = DS.getSourceRange().getEnd();
3043 // Parse exception-specification[opt].
3044 if (Tok.is(tok::kw_throw)) {
3045 hasExceptionSpec = true;
3046 ThrowLoc = Tok.getLocation();
3047 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
3048 hasAnyExceptionSpec);
3049 assert(Exceptions.size() == ExceptionRanges.size() &&
3050 "Produced different number of exception types and ranges.");
3054 // Remember that we parsed a function type, and remember the attributes.
3055 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3057 ParamInfo.data(), ParamInfo.size(),
3058 DS.getTypeQualifiers(),
3059 hasExceptionSpec, ThrowLoc,
3060 hasAnyExceptionSpec,
3062 ExceptionRanges.data(),
3064 LParenLoc, RParenLoc, D),
3068 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3069 /// we found a K&R-style identifier list instead of a type argument list. The
3070 /// current token is known to be the first identifier in the list.
3072 /// identifier-list: [C99 6.7.5]
3074 /// identifier-list ',' identifier
3076 void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3078 // Build up an array of information about the parsed arguments.
3079 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3080 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3082 // If there was no identifier specified for the declarator, either we are in
3083 // an abstract-declarator, or we are in a parameter declarator which was found
3084 // to be abstract. In abstract-declarators, identifier lists are not valid:
3086 if (!D.getIdentifier())
3087 Diag(Tok, diag::ext_ident_list_in_param);
3089 // Tok is known to be the first identifier in the list. Remember this
3090 // identifier in ParamInfo.
3091 ParamsSoFar.insert(Tok.getIdentifierInfo());
3092 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
3096 ConsumeToken(); // eat the first identifier.
3098 while (Tok.is(tok::comma)) {
3102 // If this isn't an identifier, report the error and skip until ')'.
3103 if (Tok.isNot(tok::identifier)) {
3104 Diag(Tok, diag::err_expected_ident);
3105 SkipUntil(tok::r_paren);
3109 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3111 // Reject 'typedef int y; int test(x, y)', but continue parsing.
3112 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
3113 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3115 // Verify that the argument identifier has not already been mentioned.
3116 if (!ParamsSoFar.insert(ParmII)) {
3117 Diag(Tok, diag::err_param_redefinition) << ParmII;
3119 // Remember this identifier in ParamInfo.
3120 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3125 // Eat the identifier.
3129 // If we have the closing ')', eat it and we're done.
3130 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3132 // Remember that we parsed a function type, and remember the attributes. This
3133 // function type is always a K&R style function type, which is not varargs and
3134 // has no prototype.
3135 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3137 &ParamInfo[0], ParamInfo.size(),
3140 SourceLocation(), false, 0, 0, 0,
3141 LParenLoc, RLoc, D),
3145 /// [C90] direct-declarator '[' constant-expression[opt] ']'
3146 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3147 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3148 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3149 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
3150 void Parser::ParseBracketDeclarator(Declarator &D) {
3151 SourceLocation StartLoc = ConsumeBracket();
3153 // C array syntax has many features, but by-far the most common is [] and [4].
3154 // This code does a fast path to handle some of the most obvious cases.
3155 if (Tok.getKind() == tok::r_square) {
3156 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3158 CXX0XAttributeList Attr;
3159 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) {
3160 Attr = ParseCXX0XAttributes();
3163 // Remember that we parsed the empty array type.
3164 OwningExprResult NumElements(Actions);
3165 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
3169 } else if (Tok.getKind() == tok::numeric_constant &&
3170 GetLookAheadToken(1).is(tok::r_square)) {
3171 // [4] is very common. Parse the numeric constant expression.
3172 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
3175 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3177 CXX0XAttributeList Attr;
3178 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3179 Attr = ParseCXX0XAttributes();
3182 // If there was an error parsing the assignment-expression, recover.
3183 if (ExprRes.isInvalid())
3184 ExprRes.release(); // Deallocate expr, just use [].
3186 // Remember that we parsed a array type, and remember its features.
3187 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
3193 // If valid, this location is the position where we read the 'static' keyword.
3194 SourceLocation StaticLoc;
3195 if (Tok.is(tok::kw_static))
3196 StaticLoc = ConsumeToken();
3198 // If there is a type-qualifier-list, read it now.
3199 // Type qualifiers in an array subscript are a C99 feature.
3201 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3203 // If we haven't already read 'static', check to see if there is one after the
3204 // type-qualifier-list.
3205 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
3206 StaticLoc = ConsumeToken();
3208 // Handle "direct-declarator [ type-qual-list[opt] * ]".
3209 bool isStar = false;
3210 OwningExprResult NumElements(Actions);
3212 // Handle the case where we have '[*]' as the array size. However, a leading
3213 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
3214 // the the token after the star is a ']'. Since stars in arrays are
3215 // infrequent, use of lookahead is not costly here.
3216 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
3217 ConsumeToken(); // Eat the '*'.
3219 if (StaticLoc.isValid()) {
3220 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
3221 StaticLoc = SourceLocation(); // Drop the static.
3224 } else if (Tok.isNot(tok::r_square)) {
3225 // Note, in C89, this production uses the constant-expr production instead
3226 // of assignment-expr. The only difference is that assignment-expr allows
3227 // things like '=' and '*='. Sema rejects these in C89 mode because they
3228 // are not i-c-e's, so we don't need to distinguish between the two here.
3230 // Parse the constant-expression or assignment-expression now (depending
3232 if (getLang().CPlusPlus)
3233 NumElements = ParseConstantExpression();
3235 NumElements = ParseAssignmentExpression();
3238 // If there was an error parsing the assignment-expression, recover.
3239 if (NumElements.isInvalid()) {
3240 D.setInvalidType(true);
3241 // If the expression was invalid, skip it.
3242 SkipUntil(tok::r_square);
3246 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3249 CXX0XAttributeList Attr;
3250 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3251 Attr = ParseCXX0XAttributes();
3254 // Remember that we parsed a array type, and remember its features.
3255 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
3256 StaticLoc.isValid(), isStar,
3257 NumElements.release(),
3262 /// [GNU] typeof-specifier:
3263 /// typeof ( expressions )
3264 /// typeof ( type-name )
3265 /// [GNU/C++] typeof unary-expression
3267 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
3268 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
3270 SourceLocation StartLoc = ConsumeToken();
3272 const bool hasParens = Tok.is(tok::l_paren);
3276 SourceRange CastRange;
3277 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
3282 DS.setTypeofParensRange(CastRange);
3284 if (CastRange.getEnd().isInvalid())
3285 // FIXME: Not accurate, the range gets one token more than it should.
3286 DS.SetRangeEnd(Tok.getLocation());
3288 DS.SetRangeEnd(CastRange.getEnd());
3292 DS.SetTypeSpecError();
3296 const char *PrevSpec = 0;
3298 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3299 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
3301 Diag(StartLoc, DiagID) << PrevSpec;
3305 // If we get here, the operand to the typeof was an expresion.
3306 if (Operand.isInvalid()) {
3307 DS.SetTypeSpecError();
3311 const char *PrevSpec = 0;
3313 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3314 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3315 DiagID, Operand.release()))
3316 Diag(StartLoc, DiagID) << PrevSpec;
3320 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
3321 /// from TryAltiVecVectorToken.
3322 bool Parser::TryAltiVecVectorTokenOutOfLine() {
3323 Token Next = NextToken();
3324 switch (Next.getKind()) {
3325 default: return false;
3328 case tok::kw_signed:
3329 case tok::kw_unsigned:
3334 case tok::kw_double:
3336 case tok::kw___pixel:
3337 Tok.setKind(tok::kw___vector);
3339 case tok::identifier:
3340 if (Next.getIdentifierInfo() == Ident_pixel) {
3341 Tok.setKind(tok::kw___vector);
3348 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
3349 const char *&PrevSpec, unsigned &DiagID,
3351 if (Tok.getIdentifierInfo() == Ident_vector) {
3352 Token Next = NextToken();
3353 switch (Next.getKind()) {
3356 case tok::kw_signed:
3357 case tok::kw_unsigned:
3362 case tok::kw_double:
3364 case tok::kw___pixel:
3365 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3367 case tok::identifier:
3368 if (Next.getIdentifierInfo() == Ident_pixel) {
3369 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3376 } else if (Tok.getIdentifierInfo() == Ident_pixel &&
3377 DS.isTypeAltiVecVector()) {
3378 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);