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/Sema/Scope.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "RAIIObjectsForParser.h"
20 #include "llvm/ADT/SmallSet.h"
21 using namespace clang
;
23 //===----------------------------------------------------------------------===//
24 // C99 6.7: Declarations.
25 //===----------------------------------------------------------------------===//
28 /// type-name: [C99 6.7.6]
29 /// specifier-qualifier-list abstract-declarator[opt]
31 /// Called type-id in C++.
32 TypeResult
Parser::ParseTypeName(SourceRange
*Range
) {
33 // Parse the common declaration-specifiers piece.
35 ParseSpecifierQualifierList(DS
);
37 // Parse the abstract-declarator, if present.
38 Declarator
DeclaratorInfo(DS
, Declarator::TypeNameContext
);
39 ParseDeclarator(DeclaratorInfo
);
41 *Range
= DeclaratorInfo
.getSourceRange();
43 if (DeclaratorInfo
.isInvalidType())
46 return Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
49 /// ParseGNUAttributes - Parse a non-empty attributes list.
53 /// attributes attribute
56 /// '__attribute__' '(' '(' attribute-list ')' ')'
58 /// [GNU] attribute-list:
60 /// attribute_list ',' attrib
65 /// attrib-name '(' identifier ')'
66 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
67 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
69 /// [GNU] attrib-name:
75 /// FIXME: The GCC grammar/code for this construct implies we need two
76 /// token lookahead. Comment from gcc: "If they start with an identifier
77 /// which is followed by a comma or close parenthesis, then the arguments
78 /// start with that identifier; otherwise they are an expression list."
80 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
81 /// any attributes that don't work (based on my limited testing). Most
82 /// attributes are very simple in practice. Until we find a bug, I don't see
83 /// a pressing need to implement the 2 token lookahead.
85 void Parser::ParseGNUAttributes(ParsedAttributes
&attrs
,
86 SourceLocation
*endLoc
) {
87 assert(Tok
.is(tok::kw___attribute
) && "Not a GNU attribute list!");
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 "parameterized" 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 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
,
125 ParmName
, ParmLoc
, 0, 0));
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 ExprResult
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 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0,
149 AttrNameLoc
, ParmName
, ParmLoc
,
150 ArgExprs
.take(), ArgExprs
.size()));
153 } else { // not an identifier
154 switch (Tok
.getKind()) {
156 // parse a possibly empty comma separated list of expressions
157 // __attribute__(( nonnull() ))
158 ConsumeParen(); // ignore the right paren loc for now
159 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
,
160 0, SourceLocation(), 0, 0));
163 case tok::kw_wchar_t
:
164 case tok::kw_char16_t
:
165 case tok::kw_char32_t
:
171 case tok::kw_unsigned
:
175 case tok::kw_typeof
: {
177 = AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
,
178 0, SourceLocation(), 0, 0);
180 if (attr
->getKind() == AttributeList::AT_IBOutletCollection
)
181 Diag(Tok
, diag::err_iboutletcollection_builtintype
);
182 // If it's a builtin type name, eat it and expect a rparen
183 // __attribute__(( vec_type_hint(char) ))
185 if (Tok
.is(tok::r_paren
))
190 // __attribute__(( aligned(16) ))
191 ExprVector
ArgExprs(Actions
);
192 bool ArgExprsOk
= true;
194 // now parse the list of expressions
196 ExprResult
ArgExpr(ParseAssignmentExpression());
197 if (ArgExpr
.isInvalid()) {
199 SkipUntil(tok::r_paren
);
202 ArgExprs
.push_back(ArgExpr
.release());
204 if (Tok
.isNot(tok::comma
))
206 ConsumeToken(); // Eat the comma, move to the next argument
209 if (ArgExprsOk
&& Tok
.is(tok::r_paren
)) {
210 ConsumeParen(); // ignore the right paren loc for now
211 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0,
212 AttrNameLoc
, 0, SourceLocation(),
213 ArgExprs
.take(), ArgExprs
.size()));
219 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
,
220 0, SourceLocation(), 0, 0));
223 if (ExpectAndConsume(tok::r_paren
, diag::err_expected_rparen
))
224 SkipUntil(tok::r_paren
, false);
225 SourceLocation Loc
= Tok
.getLocation();
226 if (ExpectAndConsume(tok::r_paren
, diag::err_expected_rparen
)) {
227 SkipUntil(tok::r_paren
, false);
234 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
236 /// [MS] decl-specifier:
237 /// __declspec ( extended-decl-modifier-seq )
239 /// [MS] extended-decl-modifier-seq:
240 /// extended-decl-modifier[opt]
241 /// extended-decl-modifier extended-decl-modifier-seq
243 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes
&attrs
) {
244 assert(Tok
.is(tok::kw___declspec
) && "Not a declspec!");
247 if (ExpectAndConsume(tok::l_paren
, diag::err_expected_lparen_after
,
249 SkipUntil(tok::r_paren
, true); // skip until ) or ;
252 while (Tok
.getIdentifierInfo()) {
253 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
254 SourceLocation AttrNameLoc
= ConsumeToken();
255 if (Tok
.is(tok::l_paren
)) {
257 // FIXME: This doesn't parse __declspec(property(get=get_func_name))
259 ExprResult
ArgExpr(ParseAssignmentExpression());
260 if (!ArgExpr
.isInvalid()) {
261 Expr
*ExprList
= ArgExpr
.take();
262 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
, 0,
263 SourceLocation(), &ExprList
, 1, true));
265 if (ExpectAndConsume(tok::r_paren
, diag::err_expected_rparen
))
266 SkipUntil(tok::r_paren
, false);
268 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
,
269 0, SourceLocation(), 0, 0, true));
272 if (ExpectAndConsume(tok::r_paren
, diag::err_expected_rparen
))
273 SkipUntil(tok::r_paren
, false);
277 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes
&attrs
) {
278 // Treat these like attributes
279 // FIXME: Allow Sema to distinguish between these and real attributes!
280 while (Tok
.is(tok::kw___fastcall
) || Tok
.is(tok::kw___stdcall
) ||
281 Tok
.is(tok::kw___thiscall
) || Tok
.is(tok::kw___cdecl
) ||
282 Tok
.is(tok::kw___ptr64
) || Tok
.is(tok::kw___w64
)) {
283 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
284 SourceLocation AttrNameLoc
= ConsumeToken();
285 if (Tok
.is(tok::kw___ptr64
) || Tok
.is(tok::kw___w64
))
286 // FIXME: Support these properly!
288 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
, 0,
289 SourceLocation(), 0, 0, true));
293 void Parser::ParseBorlandTypeAttributes(ParsedAttributes
&attrs
) {
294 // Treat these like attributes
295 while (Tok
.is(tok::kw___pascal
)) {
296 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
297 SourceLocation AttrNameLoc
= ConsumeToken();
298 attrs
.add(AttrFactory
.Create(AttrName
, AttrNameLoc
, 0, AttrNameLoc
, 0,
299 SourceLocation(), 0, 0, true));
303 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange
&attrs
) {
304 Diag(attrs
.Range
.getBegin(), diag::err_attributes_not_allowed
)
308 /// ParseDeclaration - Parse a full 'declaration', which consists of
309 /// declaration-specifiers, some number of declarators, and a semicolon.
310 /// 'Context' should be a Declarator::TheContext value. This returns the
311 /// location of the semicolon in DeclEnd.
313 /// declaration: [C99 6.7]
314 /// block-declaration ->
315 /// simple-declaration
317 /// [C++] template-declaration
318 /// [C++] namespace-definition
319 /// [C++] using-directive
320 /// [C++] using-declaration
321 /// [C++0x] static_assert-declaration
322 /// others... [FIXME]
324 Parser::DeclGroupPtrTy
Parser::ParseDeclaration(StmtVector
&Stmts
,
326 SourceLocation
&DeclEnd
,
327 ParsedAttributesWithRange
&attrs
) {
328 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
330 Decl
*SingleDecl
= 0;
331 switch (Tok
.getKind()) {
332 case tok::kw_template
:
334 ProhibitAttributes(attrs
);
335 SingleDecl
= ParseDeclarationStartingWithTemplate(Context
, DeclEnd
);
338 // Could be the start of an inline namespace. Allowed as an ext in C++03.
339 if (getLang().CPlusPlus
&& NextToken().is(tok::kw_namespace
)) {
340 ProhibitAttributes(attrs
);
341 SourceLocation InlineLoc
= ConsumeToken();
342 SingleDecl
= ParseNamespace(Context
, DeclEnd
, InlineLoc
);
345 return ParseSimpleDeclaration(Stmts
, Context
, DeclEnd
, attrs
,
347 case tok::kw_namespace
:
348 ProhibitAttributes(attrs
);
349 SingleDecl
= ParseNamespace(Context
, DeclEnd
);
352 SingleDecl
= ParseUsingDirectiveOrDeclaration(Context
, ParsedTemplateInfo(),
355 case tok::kw_static_assert
:
356 ProhibitAttributes(attrs
);
357 SingleDecl
= ParseStaticAssertDeclaration(DeclEnd
);
360 return ParseSimpleDeclaration(Stmts
, Context
, DeclEnd
, attrs
, true);
363 // This routine returns a DeclGroup, if the thing we parsed only contains a
364 // single decl, convert it now.
365 return Actions
.ConvertDeclToDeclGroup(SingleDecl
);
368 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
369 /// declaration-specifiers init-declarator-list[opt] ';'
370 ///[C90/C++]init-declarator-list ';' [TODO]
371 /// [OMP] threadprivate-directive [TODO]
373 /// If RequireSemi is false, this does not check for a ';' at the end of the
374 /// declaration. If it is true, it checks for and eats it.
375 Parser::DeclGroupPtrTy
Parser::ParseSimpleDeclaration(StmtVector
&Stmts
,
377 SourceLocation
&DeclEnd
,
378 ParsedAttributes
&attrs
,
380 // Parse the common declaration-specifiers piece.
381 ParsingDeclSpec
DS(*this);
382 DS
.takeAttributesFrom(attrs
);
383 ParseDeclarationSpecifiers(DS
, ParsedTemplateInfo(), AS_none
,
384 getDeclSpecContextFromDeclaratorContext(Context
));
385 StmtResult R
= Actions
.ActOnVlaStmt(DS
);
387 Stmts
.push_back(R
.release());
389 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
390 // declaration-specifiers init-declarator-list[opt] ';'
391 if (Tok
.is(tok::semi
)) {
392 if (RequireSemi
) ConsumeToken();
393 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(getCurScope(), AS_none
,
395 DS
.complete(TheDecl
);
396 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
399 return ParseDeclGroup(DS
, Context
, /*FunctionDefs=*/ false, &DeclEnd
);
402 /// ParseDeclGroup - Having concluded that this is either a function
403 /// definition or a group of object declarations, actually parse the
405 Parser::DeclGroupPtrTy
Parser::ParseDeclGroup(ParsingDeclSpec
&DS
,
407 bool AllowFunctionDefinitions
,
408 SourceLocation
*DeclEnd
) {
409 // Parse the first declarator.
410 ParsingDeclarator
D(*this, DS
, static_cast<Declarator::TheContext
>(Context
));
413 // Bail out if the first declarator didn't seem well-formed.
414 if (!D
.hasName() && !D
.mayOmitIdentifier()) {
415 // Skip until ; or }.
416 SkipUntil(tok::r_brace
, true, true);
417 if (Tok
.is(tok::semi
))
419 return DeclGroupPtrTy();
422 // Check to see if we have a function *definition* which must have a body.
423 if (AllowFunctionDefinitions
&& D
.isFunctionDeclarator() &&
424 // Look at the next token to make sure that this isn't a function
425 // declaration. We have to check this because __attribute__ might be the
426 // start of a function definition in GCC-extended K&R C.
427 !isDeclarationAfterDeclarator()) {
429 if (isStartOfFunctionDefinition(D
)) {
430 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
431 Diag(Tok
, diag::err_function_declared_typedef
);
433 // Recover by treating the 'typedef' as spurious.
434 DS
.ClearStorageClassSpecs();
437 Decl
*TheDecl
= ParseFunctionDefinition(D
);
438 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
441 if (isDeclarationSpecifier()) {
442 // If there is an invalid declaration specifier right after the function
443 // prototype, then we must be in a missing semicolon case where this isn't
444 // actually a body. Just fall through into the code that handles it as a
445 // prototype, and let the top-level code handle the erroneous declspec
446 // where it would otherwise expect a comma or semicolon.
448 Diag(Tok
, diag::err_expected_fn_body
);
449 SkipUntil(tok::semi
);
450 return DeclGroupPtrTy();
454 llvm::SmallVector
<Decl
*, 8> DeclsInGroup
;
455 Decl
*FirstDecl
= ParseDeclarationAfterDeclarator(D
);
456 D
.complete(FirstDecl
);
458 DeclsInGroup
.push_back(FirstDecl
);
460 // If we don't have a comma, it is either the end of the list (a ';') or an
462 while (Tok
.is(tok::comma
)) {
463 // Consume the comma.
466 // Parse the next declarator.
469 // Accept attributes in an init-declarator. In the first declarator in a
470 // declaration, these would be part of the declspec. In subsequent
471 // declarators, they become part of the declarator itself, so that they
472 // don't apply to declarators after *this* one. Examples:
473 // short __attribute__((common)) var; -> declspec
474 // short var __attribute__((common)); -> declarator
475 // short x, __attribute__((common)) var; -> declarator
476 MaybeParseGNUAttributes(D
);
480 Decl
*ThisDecl
= ParseDeclarationAfterDeclarator(D
);
481 D
.complete(ThisDecl
);
483 DeclsInGroup
.push_back(ThisDecl
);
487 *DeclEnd
= Tok
.getLocation();
489 if (Context
!= Declarator::ForContext
&&
490 ExpectAndConsume(tok::semi
,
491 Context
== Declarator::FileContext
492 ? diag::err_invalid_token_after_toplevel_declarator
493 : diag::err_expected_semi_declaration
)) {
494 // Okay, there was no semicolon and one was expected. If we see a
495 // declaration specifier, just assume it was missing and continue parsing.
496 // Otherwise things are very confused and we skip to recover.
497 if (!isDeclarationSpecifier()) {
498 SkipUntil(tok::r_brace
, true, true);
499 if (Tok
.is(tok::semi
))
504 return Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
,
506 DeclsInGroup
.size());
509 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
510 /// declarator'. This method parses the remainder of the declaration
511 /// (including any attributes or initializer, among other things) and
512 /// finalizes the declaration.
514 /// init-declarator: [C99 6.7]
516 /// declarator '=' initializer
517 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
518 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
519 /// [C++] declarator initializer[opt]
521 /// [C++] initializer:
522 /// [C++] '=' initializer-clause
523 /// [C++] '(' expression-list ')'
524 /// [C++0x] '=' 'default' [TODO]
525 /// [C++0x] '=' 'delete'
527 /// According to the standard grammar, =default and =delete are function
528 /// definitions, but that definitely doesn't fit with the parser here.
530 Decl
*Parser::ParseDeclarationAfterDeclarator(Declarator
&D
,
531 const ParsedTemplateInfo
&TemplateInfo
) {
532 // If a simple-asm-expr is present, parse it.
533 if (Tok
.is(tok::kw_asm
)) {
535 ExprResult
AsmLabel(ParseSimpleAsm(&Loc
));
536 if (AsmLabel
.isInvalid()) {
537 SkipUntil(tok::semi
, true, true);
541 D
.setAsmLabel(AsmLabel
.release());
545 MaybeParseGNUAttributes(D
);
547 // Inform the current actions module that we just parsed this declarator.
549 switch (TemplateInfo
.Kind
) {
550 case ParsedTemplateInfo::NonTemplate
:
551 ThisDecl
= Actions
.ActOnDeclarator(getCurScope(), D
);
554 case ParsedTemplateInfo::Template
:
555 case ParsedTemplateInfo::ExplicitSpecialization
:
556 ThisDecl
= Actions
.ActOnTemplateDeclarator(getCurScope(),
557 MultiTemplateParamsArg(Actions
,
558 TemplateInfo
.TemplateParams
->data(),
559 TemplateInfo
.TemplateParams
->size()),
563 case ParsedTemplateInfo::ExplicitInstantiation
: {
565 = Actions
.ActOnExplicitInstantiation(getCurScope(),
566 TemplateInfo
.ExternLoc
,
567 TemplateInfo
.TemplateLoc
,
569 if (ThisRes
.isInvalid()) {
570 SkipUntil(tok::semi
, true, true);
574 ThisDecl
= ThisRes
.get();
579 // Parse declarator '=' initializer.
580 if (isTokenEqualOrMistypedEqualEqual(
581 diag::err_invalid_equalequal_after_declarator
)) {
583 if (Tok
.is(tok::kw_delete
)) {
584 SourceLocation DelLoc
= ConsumeToken();
586 if (!getLang().CPlusPlus0x
)
587 Diag(DelLoc
, diag::warn_deleted_function_accepted_as_extension
);
589 Actions
.SetDeclDeleted(ThisDecl
, DelLoc
);
591 if (getLang().CPlusPlus
&& D
.getCXXScopeSpec().isSet()) {
593 Actions
.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl
);
596 if (Tok
.is(tok::code_completion
)) {
597 Actions
.CodeCompleteInitializer(getCurScope(), ThisDecl
);
598 ConsumeCodeCompletionToken();
599 SkipUntil(tok::comma
, true, true);
603 ExprResult
Init(ParseInitializer());
605 if (getLang().CPlusPlus
&& D
.getCXXScopeSpec().isSet()) {
606 Actions
.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl
);
610 if (Init
.isInvalid()) {
611 SkipUntil(tok::comma
, true, true);
612 Actions
.ActOnInitializerError(ThisDecl
);
614 Actions
.AddInitializerToDecl(ThisDecl
, Init
.take());
616 } else if (Tok
.is(tok::l_paren
)) {
617 // Parse C++ direct initializer: '(' expression-list ')'
618 SourceLocation LParenLoc
= ConsumeParen();
619 ExprVector
Exprs(Actions
);
620 CommaLocsTy CommaLocs
;
622 if (getLang().CPlusPlus
&& D
.getCXXScopeSpec().isSet()) {
624 Actions
.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl
);
627 if (ParseExpressionList(Exprs
, CommaLocs
)) {
628 SkipUntil(tok::r_paren
);
630 if (getLang().CPlusPlus
&& D
.getCXXScopeSpec().isSet()) {
631 Actions
.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl
);
636 SourceLocation RParenLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
638 assert(!Exprs
.empty() && Exprs
.size()-1 == CommaLocs
.size() &&
639 "Unexpected number of commas!");
641 if (getLang().CPlusPlus
&& D
.getCXXScopeSpec().isSet()) {
642 Actions
.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl
);
646 Actions
.AddCXXDirectInitializerToDecl(ThisDecl
, LParenLoc
,
651 bool TypeContainsUndeducedAuto
=
652 D
.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
;
653 Actions
.ActOnUninitializedDecl(ThisDecl
, TypeContainsUndeducedAuto
);
659 /// ParseSpecifierQualifierList
660 /// specifier-qualifier-list:
661 /// type-specifier specifier-qualifier-list[opt]
662 /// type-qualifier specifier-qualifier-list[opt]
663 /// [GNU] attributes specifier-qualifier-list[opt]
665 void Parser::ParseSpecifierQualifierList(DeclSpec
&DS
) {
666 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
667 /// parse declaration-specifiers and complain about extra stuff.
668 ParseDeclarationSpecifiers(DS
);
670 // Validate declspec for type-name.
671 unsigned Specs
= DS
.getParsedSpecifiers();
672 if (Specs
== DeclSpec::PQ_None
&& !DS
.getNumProtocolQualifiers() &&
674 Diag(Tok
, diag::err_typename_requires_specqual
);
676 // Issue diagnostic and remove storage class if present.
677 if (Specs
& DeclSpec::PQ_StorageClassSpecifier
) {
678 if (DS
.getStorageClassSpecLoc().isValid())
679 Diag(DS
.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass
);
681 Diag(DS
.getThreadSpecLoc(), diag::err_typename_invalid_storageclass
);
682 DS
.ClearStorageClassSpecs();
685 // Issue diagnostic and remove function specfier if present.
686 if (Specs
& DeclSpec::PQ_FunctionSpecifier
) {
687 if (DS
.isInlineSpecified())
688 Diag(DS
.getInlineSpecLoc(), diag::err_typename_invalid_functionspec
);
689 if (DS
.isVirtualSpecified())
690 Diag(DS
.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec
);
691 if (DS
.isExplicitSpecified())
692 Diag(DS
.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec
);
693 DS
.ClearFunctionSpecs();
697 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
698 /// specified token is valid after the identifier in a declarator which
699 /// immediately follows the declspec. For example, these things are valid:
701 /// int x [ 4]; // direct-declarator
702 /// int x ( int y); // direct-declarator
703 /// int(int x ) // direct-declarator
704 /// int x ; // simple-declaration
705 /// int x = 17; // init-declarator-list
706 /// int x , y; // init-declarator-list
707 /// int x __asm__ ("foo"); // init-declarator-list
708 /// int x : 4; // struct-declarator
709 /// int x { 5}; // C++'0x unified initializers
711 /// This is not, because 'x' does not immediately follow the declspec (though
712 /// ')' happens to be valid anyway).
715 static bool isValidAfterIdentifierInDeclarator(const Token
&T
) {
716 return T
.is(tok::l_square
) || T
.is(tok::l_paren
) || T
.is(tok::r_paren
) ||
717 T
.is(tok::semi
) || T
.is(tok::comma
) || T
.is(tok::equal
) ||
718 T
.is(tok::kw_asm
) || T
.is(tok::l_brace
) || T
.is(tok::colon
);
722 /// ParseImplicitInt - This method is called when we have an non-typename
723 /// identifier in a declspec (which normally terminates the decl spec) when
724 /// the declspec has no type specifier. In this case, the declspec is either
725 /// malformed or is "implicit int" (in K&R and C89).
727 /// This method handles diagnosing this prettily and returns false if the
728 /// declspec is done being processed. If it recovers and thinks there may be
729 /// other pieces of declspec after it, it returns true.
731 bool Parser::ParseImplicitInt(DeclSpec
&DS
, CXXScopeSpec
*SS
,
732 const ParsedTemplateInfo
&TemplateInfo
,
733 AccessSpecifier AS
) {
734 assert(Tok
.is(tok::identifier
) && "should have identifier");
736 SourceLocation Loc
= Tok
.getLocation();
737 // If we see an identifier that is not a type name, we normally would
738 // parse it as the identifer being declared. However, when a typename
739 // is typo'd or the definition is not included, this will incorrectly
740 // parse the typename as the identifier name and fall over misparsing
741 // later parts of the diagnostic.
743 // As such, we try to do some look-ahead in cases where this would
744 // otherwise be an "implicit-int" case to see if this is invalid. For
745 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
746 // an identifier with implicit int, we'd get a parse error because the
747 // next token is obviously invalid for a type. Parse these as a case
748 // with an invalid type specifier.
749 assert(!DS
.hasTypeSpecifier() && "Type specifier checked above");
751 // Since we know that this either implicit int (which is rare) or an
752 // error, we'd do lookahead to try to do better recovery.
753 if (isValidAfterIdentifierInDeclarator(NextToken())) {
754 // If this token is valid for implicit int, e.g. "static x = 4", then
755 // we just avoid eating the identifier, so it will be parsed as the
756 // identifier in the declarator.
760 // Otherwise, if we don't consume this token, we are going to emit an
761 // error anyway. Try to recover from various common problems. Check
762 // to see if this was a reference to a tag name without a tag specified.
763 // This is a common problem in C (saying 'foo' instead of 'struct foo').
765 // C++ doesn't need this, and isTagName doesn't take SS.
767 const char *TagName
= 0;
768 tok::TokenKind TagKind
= tok::unknown
;
770 switch (Actions
.isTagName(*Tok
.getIdentifierInfo(), getCurScope())) {
772 case DeclSpec::TST_enum
: TagName
="enum" ;TagKind
=tok::kw_enum
;break;
773 case DeclSpec::TST_union
: TagName
="union" ;TagKind
=tok::kw_union
;break;
774 case DeclSpec::TST_struct
:TagName
="struct";TagKind
=tok::kw_struct
;break;
775 case DeclSpec::TST_class
: TagName
="class" ;TagKind
=tok::kw_class
;break;
779 Diag(Loc
, diag::err_use_of_tag_name_without_tag
)
780 << Tok
.getIdentifierInfo() << TagName
<< getLang().CPlusPlus
781 << FixItHint::CreateInsertion(Tok
.getLocation(),TagName
);
783 // Parse this as a tag as if the missing tag were present.
784 if (TagKind
== tok::kw_enum
)
785 ParseEnumSpecifier(Loc
, DS
, TemplateInfo
, AS
);
787 ParseClassSpecifier(TagKind
, Loc
, DS
, TemplateInfo
, AS
);
792 // This is almost certainly an invalid type name. Let the action emit a
793 // diagnostic and attempt to recover.
795 if (Actions
.DiagnoseUnknownTypeName(*Tok
.getIdentifierInfo(), Loc
,
796 getCurScope(), SS
, T
)) {
797 // The action emitted a diagnostic, so we don't have to.
799 // The action has suggested that the type T could be used. Set that as
800 // the type in the declaration specifiers, consume the would-be type
801 // name token, and we're done.
802 const char *PrevSpec
;
804 DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
, DiagID
, T
);
805 DS
.SetRangeEnd(Tok
.getLocation());
808 // There may be other declaration specifiers after this.
812 // Fall through; the action had no suggestion for us.
814 // The action did not emit a diagnostic, so emit one now.
816 if (SS
) R
= SS
->getRange();
817 Diag(Loc
, diag::err_unknown_typename
) << Tok
.getIdentifierInfo() << R
;
820 // Mark this as an error.
821 const char *PrevSpec
;
823 DS
.SetTypeSpecType(DeclSpec::TST_error
, Loc
, PrevSpec
, DiagID
);
824 DS
.SetRangeEnd(Tok
.getLocation());
827 // TODO: Could inject an invalid typedef decl in an enclosing scope to
828 // avoid rippling error messages on subsequent uses of the same type,
829 // could be useful if #include was forgotten.
833 /// \brief Determine the declaration specifier context from the declarator
836 /// \param Context the declarator context, which is one of the
837 /// Declarator::TheContext enumerator values.
838 Parser::DeclSpecContext
839 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context
) {
840 if (Context
== Declarator::MemberContext
)
842 if (Context
== Declarator::FileContext
)
843 return DSC_top_level
;
847 /// ParseDeclarationSpecifiers
848 /// declaration-specifiers: [C99 6.7]
849 /// storage-class-specifier declaration-specifiers[opt]
850 /// type-specifier declaration-specifiers[opt]
851 /// [C99] function-specifier declaration-specifiers[opt]
852 /// [GNU] attributes declaration-specifiers[opt]
854 /// storage-class-specifier: [C99 6.7.1]
862 /// function-specifier: [C99 6.7.4]
866 /// 'friend': [C++ dcl.friend]
867 /// 'constexpr': [C++0x dcl.constexpr]
870 void Parser::ParseDeclarationSpecifiers(DeclSpec
&DS
,
871 const ParsedTemplateInfo
&TemplateInfo
,
873 DeclSpecContext DSContext
) {
874 DS
.SetRangeStart(Tok
.getLocation());
875 DS
.SetRangeEnd(Tok
.getLocation());
877 bool isInvalid
= false;
878 const char *PrevSpec
= 0;
881 SourceLocation Loc
= Tok
.getLocation();
883 switch (Tok
.getKind()) {
886 // If this is not a declaration specifier token, we're done reading decl
887 // specifiers. First verify that DeclSpec's are consistent.
888 DS
.Finish(Diags
, PP
);
891 case tok::code_completion
: {
892 Sema::ParserCompletionContext CCC
= Sema::PCC_Namespace
;
893 if (DS
.hasTypeSpecifier()) {
894 bool AllowNonIdentifiers
895 = (getCurScope()->getFlags() & (Scope::ControlScope
|
897 Scope::TemplateParamScope
|
898 Scope::FunctionPrototypeScope
|
899 Scope::AtCatchScope
)) == 0;
900 bool AllowNestedNameSpecifiers
901 = DSContext
== DSC_top_level
||
902 (DSContext
== DSC_class
&& DS
.isFriendSpecified());
904 Actions
.CodeCompleteDeclSpec(getCurScope(), DS
,
906 AllowNestedNameSpecifiers
);
907 ConsumeCodeCompletionToken();
911 if (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
)
912 CCC
= DSContext
== DSC_class
? Sema::PCC_MemberTemplate
913 : Sema::PCC_Template
;
914 else if (DSContext
== DSC_class
)
915 CCC
= Sema::PCC_Class
;
916 else if (ObjCImpDecl
)
917 CCC
= Sema::PCC_ObjCImplementation
;
919 Actions
.CodeCompleteOrdinaryName(getCurScope(), CCC
);
920 ConsumeCodeCompletionToken();
924 case tok::coloncolon
: // ::foo::bar
925 // C++ scope specifier. Annotate and loop, or bail out on error.
926 if (TryAnnotateCXXScopeToken(true)) {
927 if (!DS
.hasTypeSpecifier())
928 DS
.SetTypeSpecError();
929 goto DoneWithDeclSpec
;
931 if (Tok
.is(tok::coloncolon
)) // ::new or ::delete
932 goto DoneWithDeclSpec
;
935 case tok::annot_cxxscope
: {
936 if (DS
.hasTypeSpecifier())
937 goto DoneWithDeclSpec
;
940 SS
.setScopeRep((NestedNameSpecifier
*) Tok
.getAnnotationValue());
941 SS
.setRange(Tok
.getAnnotationRange());
943 // We are looking for a qualified typename.
944 Token Next
= NextToken();
945 if (Next
.is(tok::annot_template_id
) &&
946 static_cast<TemplateIdAnnotation
*>(Next
.getAnnotationValue())
947 ->Kind
== TNK_Type_template
) {
948 // We have a qualified template-id, e.g., N::A<int>
950 // C++ [class.qual]p2:
951 // In a lookup in which the constructor is an acceptable lookup
952 // result and the nested-name-specifier nominates a class C:
954 // - if the name specified after the
955 // nested-name-specifier, when looked up in C, is the
956 // injected-class-name of C (Clause 9), or
958 // - if the name specified after the nested-name-specifier
959 // is the same as the identifier or the
960 // simple-template-id's template-name in the last
961 // component of the nested-name-specifier,
963 // the name is instead considered to name the constructor of
966 // Thus, if the template-name is actually the constructor
967 // name, then the code is ill-formed; this interpretation is
968 // reinforced by the NAD status of core issue 635.
969 TemplateIdAnnotation
*TemplateId
970 = static_cast<TemplateIdAnnotation
*>(Next
.getAnnotationValue());
971 if ((DSContext
== DSC_top_level
||
972 (DSContext
== DSC_class
&& DS
.isFriendSpecified())) &&
974 Actions
.isCurrentClassName(*TemplateId
->Name
, getCurScope(), &SS
)) {
975 if (isConstructorDeclarator()) {
976 // The user meant this to be an out-of-line constructor
977 // definition, but template arguments are not allowed
978 // there. Just allow this as a constructor; we'll
979 // complain about it later.
980 goto DoneWithDeclSpec
;
983 // The user meant this to name a type, but it actually names
984 // a constructor with some extraneous template
985 // arguments. Complain, then parse it as a type as the user
987 Diag(TemplateId
->TemplateNameLoc
,
988 diag::err_out_of_line_template_id_names_constructor
)
992 DS
.getTypeSpecScope() = SS
;
993 ConsumeToken(); // The C++ scope.
994 assert(Tok
.is(tok::annot_template_id
) &&
995 "ParseOptionalCXXScopeSpecifier not working");
996 AnnotateTemplateIdTokenAsType(&SS
);
1000 if (Next
.is(tok::annot_typename
)) {
1001 DS
.getTypeSpecScope() = SS
;
1002 ConsumeToken(); // The C++ scope.
1003 if (Tok
.getAnnotationValue()) {
1004 ParsedType T
= getTypeAnnotation(Tok
);
1005 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
,
1006 Tok
.getAnnotationEndLoc(),
1007 PrevSpec
, DiagID
, T
);
1010 DS
.SetTypeSpecError();
1011 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
1012 ConsumeToken(); // The typename
1015 if (Next
.isNot(tok::identifier
))
1016 goto DoneWithDeclSpec
;
1018 // If we're in a context where the identifier could be a class name,
1019 // check whether this is a constructor declaration.
1020 if ((DSContext
== DSC_top_level
||
1021 (DSContext
== DSC_class
&& DS
.isFriendSpecified())) &&
1022 Actions
.isCurrentClassName(*Next
.getIdentifierInfo(), getCurScope(),
1024 if (isConstructorDeclarator())
1025 goto DoneWithDeclSpec
;
1027 // As noted in C++ [class.qual]p2 (cited above), when the name
1028 // of the class is qualified in a context where it could name
1029 // a constructor, its a constructor name. However, we've
1030 // looked at the declarator, and the user probably meant this
1031 // to be a type. Complain that it isn't supposed to be treated
1032 // as a type, then proceed to parse it as a type.
1033 Diag(Next
.getLocation(), diag::err_out_of_line_type_names_constructor
)
1034 << Next
.getIdentifierInfo();
1037 ParsedType TypeRep
= Actions
.getTypeName(*Next
.getIdentifierInfo(),
1039 getCurScope(), &SS
);
1041 // If the referenced identifier is not a type, then this declspec is
1042 // erroneous: We already checked about that it has no type specifier, and
1043 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
1046 ConsumeToken(); // Eat the scope spec so the identifier is current.
1047 if (ParseImplicitInt(DS
, &SS
, TemplateInfo
, AS
)) continue;
1048 goto DoneWithDeclSpec
;
1051 DS
.getTypeSpecScope() = SS
;
1052 ConsumeToken(); // The C++ scope.
1054 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
1059 DS
.SetRangeEnd(Tok
.getLocation());
1060 ConsumeToken(); // The typename.
1065 case tok::annot_typename
: {
1066 if (Tok
.getAnnotationValue()) {
1067 ParsedType T
= getTypeAnnotation(Tok
);
1068 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
1071 DS
.SetTypeSpecError();
1076 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
1077 ConsumeToken(); // The typename
1079 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1080 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1081 // Objective-C interface.
1082 if (Tok
.is(tok::less
) && getLang().ObjC1
)
1083 ParseObjCProtocolQualifiers(DS
);
1089 case tok::identifier
: {
1090 // In C++, check to see if this is a scope specifier like foo::bar::, if
1091 // so handle it as such. This is important for ctor parsing.
1092 if (getLang().CPlusPlus
) {
1093 if (TryAnnotateCXXScopeToken(true)) {
1094 if (!DS
.hasTypeSpecifier())
1095 DS
.SetTypeSpecError();
1096 goto DoneWithDeclSpec
;
1098 if (!Tok
.is(tok::identifier
))
1102 // This identifier can only be a typedef name if we haven't already seen
1103 // a type-specifier. Without this check we misparse:
1104 // typedef int X; struct Y { short X; }; as 'short int'.
1105 if (DS
.hasTypeSpecifier())
1106 goto DoneWithDeclSpec
;
1108 // Check for need to substitute AltiVec keyword tokens.
1109 if (TryAltiVecToken(DS
, Loc
, PrevSpec
, DiagID
, isInvalid
))
1112 // It has to be available as a typedef too!
1113 ParsedType TypeRep
=
1114 Actions
.getTypeName(*Tok
.getIdentifierInfo(),
1115 Tok
.getLocation(), getCurScope());
1117 // If this is not a typedef name, don't parse it as part of the declspec,
1118 // it must be an implicit int or an error.
1120 if (ParseImplicitInt(DS
, 0, TemplateInfo
, AS
)) continue;
1121 goto DoneWithDeclSpec
;
1124 // If we're in a context where the identifier could be a class name,
1125 // check whether this is a constructor declaration.
1126 if (getLang().CPlusPlus
&& DSContext
== DSC_class
&&
1127 Actions
.isCurrentClassName(*Tok
.getIdentifierInfo(), getCurScope()) &&
1128 isConstructorDeclarator())
1129 goto DoneWithDeclSpec
;
1131 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
1136 DS
.SetRangeEnd(Tok
.getLocation());
1137 ConsumeToken(); // The identifier
1139 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1140 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1141 // Objective-C interface.
1142 if (Tok
.is(tok::less
) && getLang().ObjC1
)
1143 ParseObjCProtocolQualifiers(DS
);
1145 // Need to support trailing type qualifiers (e.g. "id<p> const").
1146 // If a type specifier follows, it will be diagnosed elsewhere.
1151 case tok::annot_template_id
: {
1152 TemplateIdAnnotation
*TemplateId
1153 = static_cast<TemplateIdAnnotation
*>(Tok
.getAnnotationValue());
1154 if (TemplateId
->Kind
!= TNK_Type_template
) {
1155 // This template-id does not refer to a type name, so we're
1156 // done with the type-specifiers.
1157 goto DoneWithDeclSpec
;
1160 // If we're in a context where the template-id could be a
1161 // constructor name or specialization, check whether this is a
1162 // constructor declaration.
1163 if (getLang().CPlusPlus
&& DSContext
== DSC_class
&&
1164 Actions
.isCurrentClassName(*TemplateId
->Name
, getCurScope()) &&
1165 isConstructorDeclarator())
1166 goto DoneWithDeclSpec
;
1168 // Turn the template-id annotation token into a type annotation
1169 // token, then try again to parse it as a type-specifier.
1170 AnnotateTemplateIdTokenAsType();
1174 // GNU attributes support.
1175 case tok::kw___attribute
:
1176 ParseGNUAttributes(DS
.getAttributes());
1179 // Microsoft declspec support.
1180 case tok::kw___declspec
:
1181 ParseMicrosoftDeclSpec(DS
.getAttributes());
1184 // Microsoft single token adornments.
1185 case tok::kw___forceinline
:
1186 // FIXME: Add handling here!
1189 case tok::kw___ptr64
:
1191 case tok::kw___cdecl
:
1192 case tok::kw___stdcall
:
1193 case tok::kw___fastcall
:
1194 case tok::kw___thiscall
:
1195 ParseMicrosoftTypeAttributes(DS
.getAttributes());
1198 // Borland single token adornments.
1199 case tok::kw___pascal
:
1200 ParseBorlandTypeAttributes(DS
.getAttributes());
1203 // storage-class-specifier
1204 case tok::kw_typedef
:
1205 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_typedef
, Loc
, PrevSpec
,
1208 case tok::kw_extern
:
1209 if (DS
.isThreadSpecified())
1210 Diag(Tok
, diag::ext_thread_before
) << "extern";
1211 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_extern
, Loc
, PrevSpec
,
1214 case tok::kw___private_extern__
:
1215 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_private_extern
, Loc
,
1218 case tok::kw_static
:
1219 if (DS
.isThreadSpecified())
1220 Diag(Tok
, diag::ext_thread_before
) << "static";
1221 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_static
, Loc
, PrevSpec
,
1225 if (getLang().CPlusPlus0x
)
1226 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_auto
, Loc
, PrevSpec
,
1229 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_auto
, Loc
, PrevSpec
,
1232 case tok::kw_register
:
1233 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_register
, Loc
, PrevSpec
,
1236 case tok::kw_mutable
:
1237 isInvalid
= DS
.SetStorageClassSpec(DeclSpec::SCS_mutable
, Loc
, PrevSpec
,
1240 case tok::kw___thread
:
1241 isInvalid
= DS
.SetStorageClassSpecThread(Loc
, PrevSpec
, DiagID
);
1244 // function-specifier
1245 case tok::kw_inline
:
1246 isInvalid
= DS
.SetFunctionSpecInline(Loc
, PrevSpec
, DiagID
);
1248 case tok::kw_virtual
:
1249 isInvalid
= DS
.SetFunctionSpecVirtual(Loc
, PrevSpec
, DiagID
);
1251 case tok::kw_explicit
:
1252 isInvalid
= DS
.SetFunctionSpecExplicit(Loc
, PrevSpec
, DiagID
);
1256 case tok::kw_friend
:
1257 if (DSContext
== DSC_class
)
1258 isInvalid
= DS
.SetFriendSpec(Loc
, PrevSpec
, DiagID
);
1260 PrevSpec
= ""; // not actually used by the diagnostic
1261 DiagID
= diag::err_friend_invalid_in_context
;
1267 case tok::kw_constexpr
:
1268 isInvalid
= DS
.SetConstexprSpec(Loc
, PrevSpec
, DiagID
);
1273 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_short
, Loc
, PrevSpec
,
1277 if (DS
.getTypeSpecWidth() != DeclSpec::TSW_long
)
1278 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_long
, Loc
, PrevSpec
,
1281 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_longlong
, Loc
, PrevSpec
,
1284 case tok::kw_signed
:
1285 isInvalid
= DS
.SetTypeSpecSign(DeclSpec::TSS_signed
, Loc
, PrevSpec
,
1288 case tok::kw_unsigned
:
1289 isInvalid
= DS
.SetTypeSpecSign(DeclSpec::TSS_unsigned
, Loc
, PrevSpec
,
1292 case tok::kw__Complex
:
1293 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_complex
, Loc
, PrevSpec
,
1296 case tok::kw__Imaginary
:
1297 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_imaginary
, Loc
, PrevSpec
,
1301 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_void
, Loc
, PrevSpec
,
1305 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char
, Loc
, PrevSpec
,
1309 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, PrevSpec
,
1313 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_float
, Loc
, PrevSpec
,
1316 case tok::kw_double
:
1317 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_double
, Loc
, PrevSpec
,
1320 case tok::kw_wchar_t
:
1321 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_wchar
, Loc
, PrevSpec
,
1324 case tok::kw_char16_t
:
1325 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char16
, Loc
, PrevSpec
,
1328 case tok::kw_char32_t
:
1329 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char32
, Loc
, PrevSpec
,
1334 if (Tok
.is(tok::kw_bool
) &&
1335 DS
.getTypeSpecType() != DeclSpec::TST_unspecified
&&
1336 DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
1337 PrevSpec
= ""; // Not used by the diagnostic.
1338 DiagID
= diag::err_bool_redeclaration
;
1341 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_bool
, Loc
, PrevSpec
,
1345 case tok::kw__Decimal32
:
1346 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal32
, Loc
, PrevSpec
,
1349 case tok::kw__Decimal64
:
1350 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal64
, Loc
, PrevSpec
,
1353 case tok::kw__Decimal128
:
1354 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal128
, Loc
, PrevSpec
,
1357 case tok::kw___vector
:
1358 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
);
1360 case tok::kw___pixel
:
1361 isInvalid
= DS
.SetTypeAltiVecPixel(true, Loc
, PrevSpec
, DiagID
);
1366 case tok::kw_struct
:
1367 case tok::kw_union
: {
1368 tok::TokenKind Kind
= Tok
.getKind();
1370 ParseClassSpecifier(Kind
, Loc
, DS
, TemplateInfo
, AS
);
1377 ParseEnumSpecifier(Loc
, DS
, TemplateInfo
, AS
);
1382 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_const
, Loc
, PrevSpec
, DiagID
,
1385 case tok::kw_volatile
:
1386 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_volatile
, Loc
, PrevSpec
, DiagID
,
1389 case tok::kw_restrict
:
1390 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_restrict
, Loc
, PrevSpec
, DiagID
,
1394 // C++ typename-specifier:
1395 case tok::kw_typename
:
1396 if (TryAnnotateTypeOrScopeToken()) {
1397 DS
.SetTypeSpecError();
1398 goto DoneWithDeclSpec
;
1400 if (!Tok
.is(tok::kw_typename
))
1404 // GNU typeof support.
1405 case tok::kw_typeof
:
1406 ParseTypeofSpecifier(DS
);
1409 case tok::kw_decltype
:
1410 ParseDecltypeSpecifier(DS
);
1414 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1415 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
1416 // but we support it.
1417 if (DS
.hasTypeSpecifier() || !getLang().ObjC1
)
1418 goto DoneWithDeclSpec
;
1420 if (!ParseObjCProtocolQualifiers(DS
))
1421 Diag(Loc
, diag::warn_objc_protocol_qualifier_missing_id
)
1422 << FixItHint::CreateInsertion(Loc
, "id")
1423 << SourceRange(Loc
, DS
.getSourceRange().getEnd());
1425 // Need to support trailing type qualifiers (e.g. "id<p> const").
1426 // If a type specifier follows, it will be diagnosed elsewhere.
1429 // If the specifier wasn't legal, issue a diagnostic.
1431 assert(PrevSpec
&& "Method did not return previous specifier!");
1434 if (DiagID
== diag::ext_duplicate_declspec
)
1436 << PrevSpec
<< FixItHint::CreateRemoval(Tok
.getLocation());
1438 Diag(Tok
, DiagID
) << PrevSpec
;
1440 DS
.SetRangeEnd(Tok
.getLocation());
1445 /// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1446 /// primarily follow the C++ grammar with additions for C99 and GNU,
1447 /// which together subsume the C grammar. Note that the C++
1448 /// type-specifier also includes the C type-qualifier (for const,
1449 /// volatile, and C99 restrict). Returns true if a type-specifier was
1450 /// found (and parsed), false otherwise.
1452 /// type-specifier: [C++ 7.1.5]
1453 /// simple-type-specifier
1456 /// elaborated-type-specifier [TODO]
1459 /// cv-qualifier: [C++ 7.1.5.1]
1462 /// [C99] 'restrict'
1464 /// simple-type-specifier: [ C++ 7.1.5.2]
1465 /// '::'[opt] nested-name-specifier[opt] type-name [TODO]
1466 /// '::'[opt] nested-name-specifier 'template' template-id [TODO]
1479 /// [C99] '_Complex'
1480 /// [C99] '_Imaginary' // Removed in TC2?
1481 /// [GNU] '_Decimal32'
1482 /// [GNU] '_Decimal64'
1483 /// [GNU] '_Decimal128'
1484 /// [GNU] typeof-specifier
1485 /// [OBJC] class-name objc-protocol-refs[opt] [TODO]
1486 /// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
1487 /// [C++0x] 'decltype' ( expression )
1488 /// [AltiVec] '__vector'
1489 bool Parser::ParseOptionalTypeSpecifier(DeclSpec
&DS
, bool& isInvalid
,
1490 const char *&PrevSpec
,
1492 const ParsedTemplateInfo
&TemplateInfo
,
1493 bool SuppressDeclarations
) {
1494 SourceLocation Loc
= Tok
.getLocation();
1496 switch (Tok
.getKind()) {
1497 case tok::identifier
: // foo::bar
1498 // If we already have a type specifier, this identifier is not a type.
1499 if (DS
.getTypeSpecType() != DeclSpec::TST_unspecified
||
1500 DS
.getTypeSpecWidth() != DeclSpec::TSW_unspecified
||
1501 DS
.getTypeSpecSign() != DeclSpec::TSS_unspecified
)
1503 // Check for need to substitute AltiVec keyword tokens.
1504 if (TryAltiVecToken(DS
, Loc
, PrevSpec
, DiagID
, isInvalid
))
1507 case tok::kw_typename
: // typename foo::bar
1508 // Annotate typenames and C++ scope specifiers. If we get one, just
1509 // recurse to handle whatever we get.
1510 if (TryAnnotateTypeOrScopeToken())
1512 if (Tok
.is(tok::identifier
))
1514 return ParseOptionalTypeSpecifier(DS
, isInvalid
, PrevSpec
, DiagID
,
1515 TemplateInfo
, SuppressDeclarations
);
1516 case tok::coloncolon
: // ::foo::bar
1517 if (NextToken().is(tok::kw_new
) || // ::new
1518 NextToken().is(tok::kw_delete
)) // ::delete
1521 // Annotate typenames and C++ scope specifiers. If we get one, just
1522 // recurse to handle whatever we get.
1523 if (TryAnnotateTypeOrScopeToken())
1525 return ParseOptionalTypeSpecifier(DS
, isInvalid
, PrevSpec
, DiagID
,
1526 TemplateInfo
, SuppressDeclarations
);
1528 // simple-type-specifier:
1529 case tok::annot_typename
: {
1530 if (ParsedType T
= getTypeAnnotation(Tok
)) {
1531 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
,
1532 Tok
.getAnnotationEndLoc(), PrevSpec
,
1535 DS
.SetTypeSpecError();
1536 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
1537 ConsumeToken(); // The typename
1539 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1540 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1541 // Objective-C interface. If we don't have Objective-C or a '<', this is
1542 // just a normal reference to a typedef name.
1543 if (Tok
.is(tok::less
) && getLang().ObjC1
)
1544 ParseObjCProtocolQualifiers(DS
);
1550 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_short
, Loc
, PrevSpec
, DiagID
);
1553 if (DS
.getTypeSpecWidth() != DeclSpec::TSW_long
)
1554 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_long
, Loc
, PrevSpec
,
1557 isInvalid
= DS
.SetTypeSpecWidth(DeclSpec::TSW_longlong
, Loc
, PrevSpec
,
1560 case tok::kw_signed
:
1561 isInvalid
= DS
.SetTypeSpecSign(DeclSpec::TSS_signed
, Loc
, PrevSpec
, DiagID
);
1563 case tok::kw_unsigned
:
1564 isInvalid
= DS
.SetTypeSpecSign(DeclSpec::TSS_unsigned
, Loc
, PrevSpec
,
1567 case tok::kw__Complex
:
1568 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_complex
, Loc
, PrevSpec
,
1571 case tok::kw__Imaginary
:
1572 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_imaginary
, Loc
, PrevSpec
,
1576 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_void
, Loc
, PrevSpec
, DiagID
);
1579 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char
, Loc
, PrevSpec
, DiagID
);
1582 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, PrevSpec
, DiagID
);
1585 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_float
, Loc
, PrevSpec
, DiagID
);
1587 case tok::kw_double
:
1588 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_double
, Loc
, PrevSpec
, DiagID
);
1590 case tok::kw_wchar_t
:
1591 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_wchar
, Loc
, PrevSpec
, DiagID
);
1593 case tok::kw_char16_t
:
1594 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char16
, Loc
, PrevSpec
, DiagID
);
1596 case tok::kw_char32_t
:
1597 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char32
, Loc
, PrevSpec
, DiagID
);
1601 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_bool
, Loc
, PrevSpec
, DiagID
);
1603 case tok::kw__Decimal32
:
1604 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal32
, Loc
, PrevSpec
,
1607 case tok::kw__Decimal64
:
1608 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal64
, Loc
, PrevSpec
,
1611 case tok::kw__Decimal128
:
1612 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal128
, Loc
, PrevSpec
,
1615 case tok::kw___vector
:
1616 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
);
1618 case tok::kw___pixel
:
1619 isInvalid
= DS
.SetTypeAltiVecPixel(true, Loc
, PrevSpec
, DiagID
);
1624 case tok::kw_struct
:
1625 case tok::kw_union
: {
1626 tok::TokenKind Kind
= Tok
.getKind();
1628 ParseClassSpecifier(Kind
, Loc
, DS
, TemplateInfo
, AS_none
,
1629 SuppressDeclarations
);
1636 ParseEnumSpecifier(Loc
, DS
, TemplateInfo
, AS_none
);
1641 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_const
, Loc
, PrevSpec
,
1644 case tok::kw_volatile
:
1645 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_volatile
, Loc
, PrevSpec
,
1648 case tok::kw_restrict
:
1649 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_restrict
, Loc
, PrevSpec
,
1653 // GNU typeof support.
1654 case tok::kw_typeof
:
1655 ParseTypeofSpecifier(DS
);
1658 // C++0x decltype support.
1659 case tok::kw_decltype
:
1660 ParseDecltypeSpecifier(DS
);
1663 // C++0x auto support.
1665 if (!getLang().CPlusPlus0x
)
1668 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_auto
, Loc
, PrevSpec
, DiagID
);
1671 case tok::kw___ptr64
:
1673 case tok::kw___cdecl
:
1674 case tok::kw___stdcall
:
1675 case tok::kw___fastcall
:
1676 case tok::kw___thiscall
:
1677 ParseMicrosoftTypeAttributes(DS
.getAttributes());
1680 case tok::kw___pascal
:
1681 ParseBorlandTypeAttributes(DS
.getAttributes());
1685 // Not a type-specifier; do nothing.
1689 // If the specifier combination wasn't legal, issue a diagnostic.
1691 assert(PrevSpec
&& "Method did not return previous specifier!");
1692 // Pick between error or extwarn.
1693 Diag(Tok
, DiagID
) << PrevSpec
;
1695 DS
.SetRangeEnd(Tok
.getLocation());
1696 ConsumeToken(); // whatever we parsed above.
1700 /// ParseStructDeclaration - Parse a struct declaration without the terminating
1703 /// struct-declaration:
1704 /// specifier-qualifier-list struct-declarator-list
1705 /// [GNU] __extension__ struct-declaration
1706 /// [GNU] specifier-qualifier-list
1707 /// struct-declarator-list:
1708 /// struct-declarator
1709 /// struct-declarator-list ',' struct-declarator
1710 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
1711 /// struct-declarator:
1713 /// [GNU] declarator attributes[opt]
1714 /// declarator[opt] ':' constant-expression
1715 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
1718 ParseStructDeclaration(DeclSpec
&DS
, FieldCallback
&Fields
) {
1719 if (Tok
.is(tok::kw___extension__
)) {
1720 // __extension__ silences extension warnings in the subexpression.
1721 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
1723 return ParseStructDeclaration(DS
, Fields
);
1726 // Parse the common specifier-qualifiers-list piece.
1727 ParseSpecifierQualifierList(DS
);
1729 // If there are no declarators, this is a free-standing declaration
1730 // specifier. Let the actions module cope with it.
1731 if (Tok
.is(tok::semi
)) {
1732 Actions
.ParsedFreeStandingDeclSpec(getCurScope(), AS_none
, DS
);
1736 // Read struct-declarators until we find the semicolon.
1737 bool FirstDeclarator
= true;
1739 ParsingDeclRAIIObject
PD(*this);
1740 FieldDeclarator
DeclaratorInfo(DS
);
1742 // Attributes are only allowed here on successive declarators.
1743 if (!FirstDeclarator
)
1744 MaybeParseGNUAttributes(DeclaratorInfo
.D
);
1746 /// struct-declarator: declarator
1747 /// struct-declarator: declarator[opt] ':' constant-expression
1748 if (Tok
.isNot(tok::colon
)) {
1749 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1750 ColonProtectionRAIIObject
X(*this);
1751 ParseDeclarator(DeclaratorInfo
.D
);
1754 if (Tok
.is(tok::colon
)) {
1756 ExprResult
Res(ParseConstantExpression());
1757 if (Res
.isInvalid())
1758 SkipUntil(tok::semi
, true, true);
1760 DeclaratorInfo
.BitfieldSize
= Res
.release();
1763 // If attributes exist after the declarator, parse them.
1764 MaybeParseGNUAttributes(DeclaratorInfo
.D
);
1766 // We're done with this declarator; invoke the callback.
1767 Decl
*D
= Fields
.invoke(DeclaratorInfo
);
1770 // If we don't have a comma, it is either the end of the list (a ';')
1771 // or an error, bail out.
1772 if (Tok
.isNot(tok::comma
))
1775 // Consume the comma.
1778 FirstDeclarator
= false;
1782 /// ParseStructUnionBody
1783 /// struct-contents:
1784 /// struct-declaration-list
1786 /// [GNU] "struct-declaration-list" without terminatoring ';'
1787 /// struct-declaration-list:
1788 /// struct-declaration
1789 /// struct-declaration-list struct-declaration
1790 /// [OBC] '@' 'defs' '(' class-name ')'
1792 void Parser::ParseStructUnionBody(SourceLocation RecordLoc
,
1793 unsigned TagType
, Decl
*TagDecl
) {
1794 PrettyDeclStackTraceEntry
CrashInfo(Actions
, TagDecl
, RecordLoc
,
1795 "parsing struct/union body");
1797 SourceLocation LBraceLoc
= ConsumeBrace();
1799 ParseScope
StructScope(this, Scope::ClassScope
|Scope::DeclScope
);
1800 Actions
.ActOnTagStartDefinition(getCurScope(), TagDecl
);
1802 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1804 if (Tok
.is(tok::r_brace
) && !getLang().CPlusPlus
)
1805 Diag(Tok
, diag::ext_empty_struct_union
)
1806 << (TagType
== TST_union
);
1808 llvm::SmallVector
<Decl
*, 32> FieldDecls
;
1810 // While we still have something to read, read the declarations in the struct.
1811 while (Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::eof
)) {
1812 // Each iteration of this loop reads one struct-declaration.
1814 // Check for extraneous top-level semicolon.
1815 if (Tok
.is(tok::semi
)) {
1816 Diag(Tok
, diag::ext_extra_struct_semi
)
1817 << DeclSpec::getSpecifierName((DeclSpec::TST
)TagType
)
1818 << FixItHint::CreateRemoval(Tok
.getLocation());
1823 // Parse all the comma separated declarators.
1826 if (!Tok
.is(tok::at
)) {
1827 struct CFieldCallback
: FieldCallback
{
1830 llvm::SmallVectorImpl
<Decl
*> &FieldDecls
;
1832 CFieldCallback(Parser
&P
, Decl
*TagDecl
,
1833 llvm::SmallVectorImpl
<Decl
*> &FieldDecls
) :
1834 P(P
), TagDecl(TagDecl
), FieldDecls(FieldDecls
) {}
1836 virtual Decl
*invoke(FieldDeclarator
&FD
) {
1837 // Install the declarator into the current TagDecl.
1838 Decl
*Field
= P
.Actions
.ActOnField(P
.getCurScope(), TagDecl
,
1839 FD
.D
.getDeclSpec().getSourceRange().getBegin(),
1840 FD
.D
, FD
.BitfieldSize
);
1841 FieldDecls
.push_back(Field
);
1844 } Callback(*this, TagDecl
, FieldDecls
);
1846 ParseStructDeclaration(DS
, Callback
);
1847 } else { // Handle @defs
1849 if (!Tok
.isObjCAtKeyword(tok::objc_defs
)) {
1850 Diag(Tok
, diag::err_unexpected_at
);
1851 SkipUntil(tok::semi
, true);
1855 ExpectAndConsume(tok::l_paren
, diag::err_expected_lparen
);
1856 if (!Tok
.is(tok::identifier
)) {
1857 Diag(Tok
, diag::err_expected_ident
);
1858 SkipUntil(tok::semi
, true);
1861 llvm::SmallVector
<Decl
*, 16> Fields
;
1862 Actions
.ActOnDefs(getCurScope(), TagDecl
, Tok
.getLocation(),
1863 Tok
.getIdentifierInfo(), Fields
);
1864 FieldDecls
.insert(FieldDecls
.end(), Fields
.begin(), Fields
.end());
1866 ExpectAndConsume(tok::r_paren
, diag::err_expected_rparen
);
1869 if (Tok
.is(tok::semi
)) {
1871 } else if (Tok
.is(tok::r_brace
)) {
1872 ExpectAndConsume(tok::semi
, diag::ext_expected_semi_decl_list
);
1875 ExpectAndConsume(tok::semi
, diag::err_expected_semi_decl_list
);
1876 // Skip to end of block or statement to avoid ext-warning on extra ';'.
1877 SkipUntil(tok::r_brace
, true, true);
1878 // If we stopped at a ';', eat it.
1879 if (Tok
.is(tok::semi
)) ConsumeToken();
1883 SourceLocation RBraceLoc
= MatchRHSPunctuation(tok::r_brace
, LBraceLoc
);
1885 ParsedAttributes attrs
;
1886 // If attributes exist after struct contents, parse them.
1887 MaybeParseGNUAttributes(attrs
);
1889 Actions
.ActOnFields(getCurScope(),
1890 RecordLoc
, TagDecl
, FieldDecls
.data(), FieldDecls
.size(),
1891 LBraceLoc
, RBraceLoc
,
1894 Actions
.ActOnTagFinishDefinition(getCurScope(), TagDecl
, RBraceLoc
);
1897 /// ParseEnumSpecifier
1898 /// enum-specifier: [C99 6.7.2.2]
1899 /// 'enum' identifier[opt] '{' enumerator-list '}'
1900 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1901 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1902 /// '}' attributes[opt]
1903 /// 'enum' identifier
1904 /// [GNU] 'enum' attributes[opt] identifier
1906 /// [C++0x] enum-head '{' enumerator-list[opt] '}'
1907 /// [C++0x] enum-head '{' enumerator-list ',' '}'
1909 /// enum-head: [C++0x]
1910 /// enum-key attributes[opt] identifier[opt] enum-base[opt]
1911 /// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
1913 /// enum-key: [C++0x]
1918 /// enum-base: [C++0x]
1919 /// ':' type-specifier-seq
1921 /// [C++] elaborated-type-specifier:
1922 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
1924 void Parser::ParseEnumSpecifier(SourceLocation StartLoc
, DeclSpec
&DS
,
1925 const ParsedTemplateInfo
&TemplateInfo
,
1926 AccessSpecifier AS
) {
1927 // Parse the tag portion of this.
1928 if (Tok
.is(tok::code_completion
)) {
1929 // Code completion for an enum name.
1930 Actions
.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum
);
1931 ConsumeCodeCompletionToken();
1934 // If attributes exist after tag, parse them.
1935 ParsedAttributes attrs
;
1936 MaybeParseGNUAttributes(attrs
);
1938 CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
1939 if (getLang().CPlusPlus
) {
1940 if (ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false))
1943 if (SS
.isSet() && Tok
.isNot(tok::identifier
)) {
1944 Diag(Tok
, diag::err_expected_ident
);
1945 if (Tok
.isNot(tok::l_brace
)) {
1946 // Has no name and is not a definition.
1947 // Skip the rest of this declarator, up until the comma or semicolon.
1948 SkipUntil(tok::comma
, true);
1954 bool IsScopedEnum
= false;
1955 bool IsScopedUsingClassTag
= false;
1957 if (getLang().CPlusPlus0x
&&
1958 (Tok
.is(tok::kw_class
) || Tok
.is(tok::kw_struct
))) {
1959 IsScopedEnum
= true;
1960 IsScopedUsingClassTag
= Tok
.is(tok::kw_class
);
1964 // Must have either 'enum name' or 'enum {...}'.
1965 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::l_brace
)) {
1966 Diag(Tok
, diag::err_expected_ident_lbrace
);
1968 // Skip the rest of this declarator, up until the comma or semicolon.
1969 SkipUntil(tok::comma
, true);
1973 // If an identifier is present, consume and remember it.
1974 IdentifierInfo
*Name
= 0;
1975 SourceLocation NameLoc
;
1976 if (Tok
.is(tok::identifier
)) {
1977 Name
= Tok
.getIdentifierInfo();
1978 NameLoc
= ConsumeToken();
1981 if (!Name
&& IsScopedEnum
) {
1982 // C++0x 7.2p2: The optional identifier shall not be omitted in the
1983 // declaration of a scoped enumeration.
1984 Diag(Tok
, diag::err_scoped_enum_missing_identifier
);
1985 IsScopedEnum
= false;
1986 IsScopedUsingClassTag
= false;
1989 TypeResult BaseType
;
1991 // Parse the fixed underlying type.
1992 if (getLang().CPlusPlus0x
&& Tok
.is(tok::colon
)) {
1993 bool PossibleBitfield
= false;
1994 if (getCurScope()->getFlags() & Scope::ClassScope
) {
1995 // If we're in class scope, this can either be an enum declaration with
1996 // an underlying type, or a declaration of a bitfield member. We try to
1997 // use a simple disambiguation scheme first to catch the common cases
1998 // (integer literal, sizeof); if it's still ambiguous, we then consider
1999 // anything that's a simple-type-specifier followed by '(' as an
2000 // expression. This suffices because function types are not valid
2001 // underlying types anyway.
2002 TPResult TPR
= isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2003 // If the next token starts an expression, we know we're parsing a
2004 // bit-field. This is the common case.
2005 if (TPR
== TPResult::True())
2006 PossibleBitfield
= true;
2007 // If the next token starts a type-specifier-seq, it may be either a
2008 // a fixed underlying type or the start of a function-style cast in C++;
2009 // lookahead one more token to see if it's obvious that we have a
2010 // fixed underlying type.
2011 else if (TPR
== TPResult::False() &&
2012 GetLookAheadToken(2).getKind() == tok::semi
) {
2016 // We have the start of a type-specifier-seq, so we have to perform
2017 // tentative parsing to determine whether we have an expression or a
2019 TentativeParsingAction
TPA(*this);
2024 if (isCXXDeclarationSpecifier() != TPResult::True()) {
2025 // We'll parse this as a bitfield later.
2026 PossibleBitfield
= true;
2029 // We have a type-specifier-seq.
2038 if (!PossibleBitfield
) {
2040 BaseType
= ParseTypeName(&Range
);
2044 // There are three options here. If we have 'enum foo;', then this is a
2045 // forward declaration. If we have 'enum foo {...' then this is a
2046 // definition. Otherwise we have something like 'enum foo xyz', a reference.
2048 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2049 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
2050 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
2052 Sema::TagUseKind TUK
;
2053 if (Tok
.is(tok::l_brace
))
2054 TUK
= Sema::TUK_Definition
;
2055 else if (Tok
.is(tok::semi
))
2056 TUK
= Sema::TUK_Declaration
;
2058 TUK
= Sema::TUK_Reference
;
2060 // enums cannot be templates, although they can be referenced from a
2062 if (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
&&
2063 TUK
!= Sema::TUK_Reference
) {
2064 Diag(Tok
, diag::err_enum_template
);
2066 // Skip the rest of this declarator, up until the comma or semicolon.
2067 SkipUntil(tok::comma
, true);
2072 bool IsDependent
= false;
2073 SourceLocation TSTLoc
= NameLoc
.isValid()? NameLoc
: StartLoc
;
2074 const char *PrevSpec
= 0;
2076 Decl
*TagDecl
= Actions
.ActOnTag(getCurScope(), DeclSpec::TST_enum
, TUK
,
2077 StartLoc
, SS
, Name
, NameLoc
, attrs
.getList(),
2079 MultiTemplateParamsArg(Actions
),
2080 Owned
, IsDependent
, IsScopedEnum
,
2081 IsScopedUsingClassTag
, BaseType
);
2084 // This enum has a dependent nested-name-specifier. Handle it as a
2087 DS
.SetTypeSpecError();
2088 Diag(Tok
, diag::err_expected_type_name_after_typename
);
2092 TypeResult Type
= Actions
.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum
,
2093 TUK
, SS
, Name
, StartLoc
,
2095 if (Type
.isInvalid()) {
2096 DS
.SetTypeSpecError();
2100 if (DS
.SetTypeSpecType(DeclSpec::TST_typename
, TSTLoc
, PrevSpec
, DiagID
,
2102 Diag(StartLoc
, DiagID
) << PrevSpec
;
2108 // The action failed to produce an enumeration tag. If this is a
2109 // definition, consume the entire definition.
2110 if (Tok
.is(tok::l_brace
)) {
2112 SkipUntil(tok::r_brace
);
2115 DS
.SetTypeSpecError();
2119 if (Tok
.is(tok::l_brace
))
2120 ParseEnumBody(StartLoc
, TagDecl
);
2122 // FIXME: The DeclSpec should keep the locations of both the keyword
2123 // and the name (if there is one).
2124 if (DS
.SetTypeSpecType(DeclSpec::TST_enum
, TSTLoc
, PrevSpec
, DiagID
,
2126 Diag(StartLoc
, DiagID
) << PrevSpec
;
2129 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
2130 /// enumerator-list:
2132 /// enumerator-list ',' enumerator
2134 /// enumeration-constant
2135 /// enumeration-constant '=' constant-expression
2136 /// enumeration-constant:
2139 void Parser::ParseEnumBody(SourceLocation StartLoc
, Decl
*EnumDecl
) {
2140 // Enter the scope of the enum body and start the definition.
2141 ParseScope
EnumScope(this, Scope::DeclScope
);
2142 Actions
.ActOnTagStartDefinition(getCurScope(), EnumDecl
);
2144 SourceLocation LBraceLoc
= ConsumeBrace();
2146 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2147 if (Tok
.is(tok::r_brace
) && !getLang().CPlusPlus
)
2148 Diag(Tok
, diag::error_empty_enum
);
2150 llvm::SmallVector
<Decl
*, 32> EnumConstantDecls
;
2152 Decl
*LastEnumConstDecl
= 0;
2154 // Parse the enumerator-list.
2155 while (Tok
.is(tok::identifier
)) {
2156 IdentifierInfo
*Ident
= Tok
.getIdentifierInfo();
2157 SourceLocation IdentLoc
= ConsumeToken();
2159 // If attributes exist after the enumerator, parse them.
2160 ParsedAttributes attrs
;
2161 MaybeParseGNUAttributes(attrs
);
2163 SourceLocation EqualLoc
;
2164 ExprResult AssignedVal
;
2165 if (Tok
.is(tok::equal
)) {
2166 EqualLoc
= ConsumeToken();
2167 AssignedVal
= ParseConstantExpression();
2168 if (AssignedVal
.isInvalid())
2169 SkipUntil(tok::comma
, tok::r_brace
, true, true);
2172 // Install the enumerator constant into EnumDecl.
2173 Decl
*EnumConstDecl
= Actions
.ActOnEnumConstant(getCurScope(), EnumDecl
,
2176 attrs
.getList(), EqualLoc
,
2177 AssignedVal
.release());
2178 EnumConstantDecls
.push_back(EnumConstDecl
);
2179 LastEnumConstDecl
= EnumConstDecl
;
2181 if (Tok
.is(tok::identifier
)) {
2182 // We're missing a comma between enumerators.
2183 SourceLocation Loc
= PP
.getLocForEndOfToken(PrevTokLocation
);
2184 Diag(Loc
, diag::err_enumerator_list_missing_comma
)
2185 << FixItHint::CreateInsertion(Loc
, ", ");
2189 if (Tok
.isNot(tok::comma
))
2191 SourceLocation CommaLoc
= ConsumeToken();
2193 if (Tok
.isNot(tok::identifier
) &&
2194 !(getLang().C99
|| getLang().CPlusPlus0x
))
2195 Diag(CommaLoc
, diag::ext_enumerator_list_comma
)
2196 << getLang().CPlusPlus
2197 << FixItHint::CreateRemoval(CommaLoc
);
2201 SourceLocation RBraceLoc
= MatchRHSPunctuation(tok::r_brace
, LBraceLoc
);
2203 // If attributes exist after the identifier list, parse them.
2204 ParsedAttributes attrs
;
2205 MaybeParseGNUAttributes(attrs
);
2207 Actions
.ActOnEnumBody(StartLoc
, LBraceLoc
, RBraceLoc
, EnumDecl
,
2208 EnumConstantDecls
.data(), EnumConstantDecls
.size(),
2209 getCurScope(), attrs
.getList());
2212 Actions
.ActOnTagFinishDefinition(getCurScope(), EnumDecl
, RBraceLoc
);
2215 /// isTypeSpecifierQualifier - Return true if the current token could be the
2216 /// start of a type-qualifier-list.
2217 bool Parser::isTypeQualifier() const {
2218 switch (Tok
.getKind()) {
2219 default: return false;
2222 case tok::kw_volatile
:
2223 case tok::kw_restrict
:
2228 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2229 /// is definitely a type-specifier. Return false if it isn't part of a type
2230 /// specifier or if we're not sure.
2231 bool Parser::isKnownToBeTypeSpecifier(const Token
&Tok
) const {
2232 switch (Tok
.getKind()) {
2233 default: return false;
2237 case tok::kw_signed
:
2238 case tok::kw_unsigned
:
2239 case tok::kw__Complex
:
2240 case tok::kw__Imaginary
:
2243 case tok::kw_wchar_t
:
2244 case tok::kw_char16_t
:
2245 case tok::kw_char32_t
:
2248 case tok::kw_double
:
2251 case tok::kw__Decimal32
:
2252 case tok::kw__Decimal64
:
2253 case tok::kw__Decimal128
:
2254 case tok::kw___vector
:
2256 // struct-or-union-specifier (C99) or class-specifier (C++)
2258 case tok::kw_struct
:
2264 case tok::annot_typename
:
2269 /// isTypeSpecifierQualifier - Return true if the current token could be the
2270 /// start of a specifier-qualifier-list.
2271 bool Parser::isTypeSpecifierQualifier() {
2272 switch (Tok
.getKind()) {
2273 default: return false;
2275 case tok::identifier
: // foo::bar
2276 if (TryAltiVecVectorToken())
2279 case tok::kw_typename
: // typename T::type
2280 // Annotate typenames and C++ scope specifiers. If we get one, just
2281 // recurse to handle whatever we get.
2282 if (TryAnnotateTypeOrScopeToken())
2284 if (Tok
.is(tok::identifier
))
2286 return isTypeSpecifierQualifier();
2288 case tok::coloncolon
: // ::foo::bar
2289 if (NextToken().is(tok::kw_new
) || // ::new
2290 NextToken().is(tok::kw_delete
)) // ::delete
2293 if (TryAnnotateTypeOrScopeToken())
2295 return isTypeSpecifierQualifier();
2297 // GNU attributes support.
2298 case tok::kw___attribute
:
2299 // GNU typeof support.
2300 case tok::kw_typeof
:
2305 case tok::kw_signed
:
2306 case tok::kw_unsigned
:
2307 case tok::kw__Complex
:
2308 case tok::kw__Imaginary
:
2311 case tok::kw_wchar_t
:
2312 case tok::kw_char16_t
:
2313 case tok::kw_char32_t
:
2316 case tok::kw_double
:
2319 case tok::kw__Decimal32
:
2320 case tok::kw__Decimal64
:
2321 case tok::kw__Decimal128
:
2322 case tok::kw___vector
:
2324 // struct-or-union-specifier (C99) or class-specifier (C++)
2326 case tok::kw_struct
:
2333 case tok::kw_volatile
:
2334 case tok::kw_restrict
:
2337 case tok::annot_typename
:
2340 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2342 return getLang().ObjC1
;
2344 case tok::kw___cdecl
:
2345 case tok::kw___stdcall
:
2346 case tok::kw___fastcall
:
2347 case tok::kw___thiscall
:
2349 case tok::kw___ptr64
:
2350 case tok::kw___pascal
:
2355 /// isDeclarationSpecifier() - Return true if the current token is part of a
2356 /// declaration specifier.
2358 /// \param DisambiguatingWithExpression True to indicate that the purpose of
2359 /// this check is to disambiguate between an expression and a declaration.
2360 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression
) {
2361 switch (Tok
.getKind()) {
2362 default: return false;
2364 case tok::identifier
: // foo::bar
2365 // Unfortunate hack to support "Class.factoryMethod" notation.
2366 if (getLang().ObjC1
&& NextToken().is(tok::period
))
2368 if (TryAltiVecVectorToken())
2371 case tok::kw_typename
: // typename T::type
2372 // Annotate typenames and C++ scope specifiers. If we get one, just
2373 // recurse to handle whatever we get.
2374 if (TryAnnotateTypeOrScopeToken())
2376 if (Tok
.is(tok::identifier
))
2379 // If we're in Objective-C and we have an Objective-C class type followed
2380 // by an identifier and then either ':' or ']', in a place where an
2381 // expression is permitted, then this is probably a class message send
2382 // missing the initial '['. In this case, we won't consider this to be
2383 // the start of a declaration.
2384 if (DisambiguatingWithExpression
&&
2385 isStartOfObjCClassMessageMissingOpenBracket())
2388 return isDeclarationSpecifier();
2390 case tok::coloncolon
: // ::foo::bar
2391 if (NextToken().is(tok::kw_new
) || // ::new
2392 NextToken().is(tok::kw_delete
)) // ::delete
2395 // Annotate typenames and C++ scope specifiers. If we get one, just
2396 // recurse to handle whatever we get.
2397 if (TryAnnotateTypeOrScopeToken())
2399 return isDeclarationSpecifier();
2401 // storage-class-specifier
2402 case tok::kw_typedef
:
2403 case tok::kw_extern
:
2404 case tok::kw___private_extern__
:
2405 case tok::kw_static
:
2407 case tok::kw_register
:
2408 case tok::kw___thread
:
2413 case tok::kw_signed
:
2414 case tok::kw_unsigned
:
2415 case tok::kw__Complex
:
2416 case tok::kw__Imaginary
:
2419 case tok::kw_wchar_t
:
2420 case tok::kw_char16_t
:
2421 case tok::kw_char32_t
:
2425 case tok::kw_double
:
2428 case tok::kw__Decimal32
:
2429 case tok::kw__Decimal64
:
2430 case tok::kw__Decimal128
:
2431 case tok::kw___vector
:
2433 // struct-or-union-specifier (C99) or class-specifier (C++)
2435 case tok::kw_struct
:
2442 case tok::kw_volatile
:
2443 case tok::kw_restrict
:
2445 // function-specifier
2446 case tok::kw_inline
:
2447 case tok::kw_virtual
:
2448 case tok::kw_explicit
:
2451 case tok::annot_typename
:
2453 // GNU typeof support.
2454 case tok::kw_typeof
:
2457 case tok::kw___attribute
:
2460 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2462 return getLang().ObjC1
;
2464 case tok::kw___declspec
:
2465 case tok::kw___cdecl
:
2466 case tok::kw___stdcall
:
2467 case tok::kw___fastcall
:
2468 case tok::kw___thiscall
:
2470 case tok::kw___ptr64
:
2471 case tok::kw___forceinline
:
2472 case tok::kw___pascal
:
2477 bool Parser::isConstructorDeclarator() {
2478 TentativeParsingAction
TPA(*this);
2480 // Parse the C++ scope specifier.
2482 if (ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), true)) {
2487 // Parse the constructor name.
2488 if (Tok
.is(tok::identifier
) || Tok
.is(tok::annot_template_id
)) {
2489 // We already know that we have a constructor name; just consume
2497 // Current class name must be followed by a left parentheses.
2498 if (Tok
.isNot(tok::l_paren
)) {
2504 // A right parentheses or ellipsis signals that we have a constructor.
2505 if (Tok
.is(tok::r_paren
) || Tok
.is(tok::ellipsis
)) {
2510 // If we need to, enter the specified scope.
2511 DeclaratorScopeObj
DeclScopeObj(*this, SS
);
2512 if (SS
.isSet() && Actions
.ShouldEnterDeclaratorScope(getCurScope(), SS
))
2513 DeclScopeObj
.EnterDeclaratorScope();
2515 // Check whether the next token(s) are part of a declaration
2516 // specifier, in which case we have the start of a parameter and,
2517 // therefore, we know that this is a constructor.
2518 bool IsConstructor
= isDeclarationSpecifier();
2520 return IsConstructor
;
2523 /// ParseTypeQualifierListOpt
2524 /// type-qualifier-list: [C99 6.7.5]
2526 /// [vendor] attributes
2527 /// [ only if VendorAttributesAllowed=true ]
2528 /// type-qualifier-list type-qualifier
2529 /// [vendor] type-qualifier-list attributes
2530 /// [ only if VendorAttributesAllowed=true ]
2531 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2532 /// [ only if CXX0XAttributesAllowed=true ]
2533 /// Note: vendor can be GNU, MS, etc.
2535 void Parser::ParseTypeQualifierListOpt(DeclSpec
&DS
,
2536 bool VendorAttributesAllowed
,
2537 bool CXX0XAttributesAllowed
) {
2538 if (getLang().CPlusPlus0x
&& isCXX0XAttributeSpecifier()) {
2539 SourceLocation Loc
= Tok
.getLocation();
2540 ParsedAttributesWithRange attrs
;
2541 ParseCXX0XAttributes(attrs
);
2542 if (CXX0XAttributesAllowed
)
2543 DS
.takeAttributesFrom(attrs
);
2545 Diag(Loc
, diag::err_attributes_not_allowed
);
2549 bool isInvalid
= false;
2550 const char *PrevSpec
= 0;
2551 unsigned DiagID
= 0;
2552 SourceLocation Loc
= Tok
.getLocation();
2554 switch (Tok
.getKind()) {
2555 case tok::code_completion
:
2556 Actions
.CodeCompleteTypeQualifiers(DS
);
2557 ConsumeCodeCompletionToken();
2561 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_const
, Loc
, PrevSpec
, DiagID
,
2564 case tok::kw_volatile
:
2565 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_volatile
, Loc
, PrevSpec
, DiagID
,
2568 case tok::kw_restrict
:
2569 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_restrict
, Loc
, PrevSpec
, DiagID
,
2573 case tok::kw___ptr64
:
2574 case tok::kw___cdecl
:
2575 case tok::kw___stdcall
:
2576 case tok::kw___fastcall
:
2577 case tok::kw___thiscall
:
2578 if (VendorAttributesAllowed
) {
2579 ParseMicrosoftTypeAttributes(DS
.getAttributes());
2582 goto DoneWithTypeQuals
;
2583 case tok::kw___pascal
:
2584 if (VendorAttributesAllowed
) {
2585 ParseBorlandTypeAttributes(DS
.getAttributes());
2588 goto DoneWithTypeQuals
;
2589 case tok::kw___attribute
:
2590 if (VendorAttributesAllowed
) {
2591 ParseGNUAttributes(DS
.getAttributes());
2592 continue; // do *not* consume the next token!
2594 // otherwise, FALL THROUGH!
2597 // If this is not a type-qualifier token, we're done reading type
2598 // qualifiers. First verify that DeclSpec's are consistent.
2599 DS
.Finish(Diags
, PP
);
2603 // If the specifier combination wasn't legal, issue a diagnostic.
2605 assert(PrevSpec
&& "Method did not return previous specifier!");
2606 Diag(Tok
, DiagID
) << PrevSpec
;
2613 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2615 void Parser::ParseDeclarator(Declarator
&D
) {
2616 /// This implements the 'declarator' production in the C grammar, then checks
2617 /// for well-formedness and issues diagnostics.
2618 ParseDeclaratorInternal(D
, &Parser::ParseDirectDeclarator
);
2621 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2622 /// is parsed by the function passed to it. Pass null, and the direct-declarator
2623 /// isn't parsed at all, making this function effectively parse the C++
2624 /// ptr-operator production.
2626 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2627 /// [C] pointer[opt] direct-declarator
2628 /// [C++] direct-declarator
2629 /// [C++] ptr-operator declarator
2631 /// pointer: [C99 6.7.5]
2632 /// '*' type-qualifier-list[opt]
2633 /// '*' type-qualifier-list[opt] pointer
2636 /// '*' cv-qualifier-seq[opt]
2639 /// [GNU] '&' restrict[opt] attributes[opt]
2640 /// [GNU?] '&&' restrict[opt] attributes[opt]
2641 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2642 void Parser::ParseDeclaratorInternal(Declarator
&D
,
2643 DirectDeclParseFunction DirectDeclParser
) {
2644 if (Diags
.hasAllExtensionsSilenced())
2647 // C++ member pointers start with a '::' or a nested-name.
2648 // Member pointers get special handling, since there's no place for the
2649 // scope spec in the generic path below.
2650 if (getLang().CPlusPlus
&&
2651 (Tok
.is(tok::coloncolon
) || Tok
.is(tok::identifier
) ||
2652 Tok
.is(tok::annot_cxxscope
))) {
2654 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), true); // ignore fail
2656 if (SS
.isNotEmpty()) {
2657 if (Tok
.isNot(tok::star
)) {
2658 // The scope spec really belongs to the direct-declarator.
2659 D
.getCXXScopeSpec() = SS
;
2660 if (DirectDeclParser
)
2661 (this->*DirectDeclParser
)(D
);
2665 SourceLocation Loc
= ConsumeToken();
2668 ParseTypeQualifierListOpt(DS
);
2669 D
.ExtendWithDeclSpec(DS
);
2671 // Recurse to parse whatever is left.
2672 ParseDeclaratorInternal(D
, DirectDeclParser
);
2674 // Sema will have to catch (syntactically invalid) pointers into global
2675 // scope. It has to catch pointers into namespace scope anyway.
2676 D
.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS
,DS
.getTypeQualifiers(),
2677 Loc
, DS
.takeAttributes()),
2678 /* Don't replace range end. */SourceLocation());
2683 tok::TokenKind Kind
= Tok
.getKind();
2684 // Not a pointer, C++ reference, or block.
2685 if (Kind
!= tok::star
&& Kind
!= tok::caret
&&
2686 (Kind
!= tok::amp
|| !getLang().CPlusPlus
) &&
2687 // We parse rvalue refs in C++03, because otherwise the errors are scary.
2688 (Kind
!= tok::ampamp
|| !getLang().CPlusPlus
)) {
2689 if (DirectDeclParser
)
2690 (this->*DirectDeclParser
)(D
);
2694 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2695 // '&&' -> rvalue reference
2696 SourceLocation Loc
= ConsumeToken(); // Eat the *, ^, & or &&.
2699 if (Kind
== tok::star
|| Kind
== tok::caret
) {
2703 ParseTypeQualifierListOpt(DS
);
2704 D
.ExtendWithDeclSpec(DS
);
2706 // Recursively parse the declarator.
2707 ParseDeclaratorInternal(D
, DirectDeclParser
);
2708 if (Kind
== tok::star
)
2709 // Remember that we parsed a pointer type, and remember the type-quals.
2710 D
.AddTypeInfo(DeclaratorChunk::getPointer(DS
.getTypeQualifiers(), Loc
,
2711 DS
.takeAttributes()),
2714 // Remember that we parsed a Block type, and remember the type-quals.
2715 D
.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS
.getTypeQualifiers(),
2716 Loc
, DS
.takeAttributes()),
2722 // Complain about rvalue references in C++03, but then go on and build
2724 if (Kind
== tok::ampamp
&& !getLang().CPlusPlus0x
)
2725 Diag(Loc
, diag::err_rvalue_reference
);
2727 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2728 // cv-qualifiers are introduced through the use of a typedef or of a
2729 // template type argument, in which case the cv-qualifiers are ignored.
2731 // [GNU] Retricted references are allowed.
2732 // [GNU] Attributes on references are allowed.
2733 // [C++0x] Attributes on references are not allowed.
2734 ParseTypeQualifierListOpt(DS
, true, false);
2735 D
.ExtendWithDeclSpec(DS
);
2737 if (DS
.getTypeQualifiers() != DeclSpec::TQ_unspecified
) {
2738 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
2739 Diag(DS
.getConstSpecLoc(),
2740 diag::err_invalid_reference_qualifier_application
) << "const";
2741 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
2742 Diag(DS
.getVolatileSpecLoc(),
2743 diag::err_invalid_reference_qualifier_application
) << "volatile";
2746 // Recursively parse the declarator.
2747 ParseDeclaratorInternal(D
, DirectDeclParser
);
2749 if (D
.getNumTypeObjects() > 0) {
2750 // C++ [dcl.ref]p4: There shall be no references to references.
2751 DeclaratorChunk
& InnerChunk
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
2752 if (InnerChunk
.Kind
== DeclaratorChunk::Reference
) {
2753 if (const IdentifierInfo
*II
= D
.getIdentifier())
2754 Diag(InnerChunk
.Loc
, diag::err_illegal_decl_reference_to_reference
)
2757 Diag(InnerChunk
.Loc
, diag::err_illegal_decl_reference_to_reference
)
2760 // Once we've complained about the reference-to-reference, we
2761 // can go ahead and build the (technically ill-formed)
2762 // declarator: reference collapsing will take care of it.
2766 // Remember that we parsed a reference type. It doesn't have type-quals.
2767 D
.AddTypeInfo(DeclaratorChunk::getReference(DS
.getTypeQualifiers(), Loc
,
2768 DS
.takeAttributes(),
2774 /// ParseDirectDeclarator
2775 /// direct-declarator: [C99 6.7.5]
2776 /// [C99] identifier
2777 /// '(' declarator ')'
2778 /// [GNU] '(' attributes declarator ')'
2779 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2780 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2781 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2782 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2783 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2784 /// direct-declarator '(' parameter-type-list ')'
2785 /// direct-declarator '(' identifier-list[opt] ')'
2786 /// [GNU] direct-declarator '(' parameter-forward-declarations
2787 /// parameter-type-list[opt] ')'
2788 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2789 /// cv-qualifier-seq[opt] exception-specification[opt]
2790 /// [C++] declarator-id
2792 /// declarator-id: [C++ 8]
2793 /// '...'[opt] id-expression
2794 /// '::'[opt] nested-name-specifier[opt] type-name
2796 /// id-expression: [C++ 5.1]
2800 /// unqualified-id: [C++ 5.1]
2802 /// operator-function-id
2803 /// conversion-function-id
2807 void Parser::ParseDirectDeclarator(Declarator
&D
) {
2808 DeclaratorScopeObj
DeclScopeObj(*this, D
.getCXXScopeSpec());
2810 if (getLang().CPlusPlus
&& D
.mayHaveIdentifier()) {
2811 // ParseDeclaratorInternal might already have parsed the scope.
2812 if (D
.getCXXScopeSpec().isEmpty()) {
2813 ParseOptionalCXXScopeSpecifier(D
.getCXXScopeSpec(), ParsedType(), true);
2816 if (D
.getCXXScopeSpec().isValid()) {
2817 if (Actions
.ShouldEnterDeclaratorScope(getCurScope(), D
.getCXXScopeSpec()))
2818 // Change the declaration context for name lookup, until this function
2819 // is exited (and the declarator has been parsed).
2820 DeclScopeObj
.EnterDeclaratorScope();
2823 // C++0x [dcl.fct]p14:
2824 // There is a syntactic ambiguity when an ellipsis occurs at the end
2825 // of a parameter-declaration-clause without a preceding comma. In
2826 // this case, the ellipsis is parsed as part of the
2827 // abstract-declarator if the type of the parameter names a template
2828 // parameter pack that has not been expanded; otherwise, it is parsed
2829 // as part of the parameter-declaration-clause.
2830 if (Tok
.is(tok::ellipsis
) &&
2831 !((D
.getContext() == Declarator::PrototypeContext
||
2832 D
.getContext() == Declarator::BlockLiteralContext
) &&
2833 NextToken().is(tok::r_paren
) &&
2834 !Actions
.containsUnexpandedParameterPacks(D
)))
2835 D
.setEllipsisLoc(ConsumeToken());
2837 if (Tok
.is(tok::identifier
) || Tok
.is(tok::kw_operator
) ||
2838 Tok
.is(tok::annot_template_id
) || Tok
.is(tok::tilde
)) {
2839 // We found something that indicates the start of an unqualified-id.
2840 // Parse that unqualified-id.
2841 bool AllowConstructorName
;
2842 if (D
.getDeclSpec().hasTypeSpecifier())
2843 AllowConstructorName
= false;
2844 else if (D
.getCXXScopeSpec().isSet())
2845 AllowConstructorName
=
2846 (D
.getContext() == Declarator::FileContext
||
2847 (D
.getContext() == Declarator::MemberContext
&&
2848 D
.getDeclSpec().isFriendSpecified()));
2850 AllowConstructorName
= (D
.getContext() == Declarator::MemberContext
);
2852 if (ParseUnqualifiedId(D
.getCXXScopeSpec(),
2853 /*EnteringContext=*/true,
2854 /*AllowDestructorName=*/true,
2855 AllowConstructorName
,
2858 // Once we're past the identifier, if the scope was bad, mark the
2859 // whole declarator bad.
2860 D
.getCXXScopeSpec().isInvalid()) {
2861 D
.SetIdentifier(0, Tok
.getLocation());
2862 D
.setInvalidType(true);
2864 // Parsed the unqualified-id; update range information and move along.
2865 if (D
.getSourceRange().getBegin().isInvalid())
2866 D
.SetRangeBegin(D
.getName().getSourceRange().getBegin());
2867 D
.SetRangeEnd(D
.getName().getSourceRange().getEnd());
2869 goto PastIdentifier
;
2871 } else if (Tok
.is(tok::identifier
) && D
.mayHaveIdentifier()) {
2872 assert(!getLang().CPlusPlus
&&
2873 "There's a C++-specific check for tok::identifier above");
2874 assert(Tok
.getIdentifierInfo() && "Not an identifier?");
2875 D
.SetIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
2877 goto PastIdentifier
;
2880 if (Tok
.is(tok::l_paren
)) {
2881 // direct-declarator: '(' declarator ')'
2882 // direct-declarator: '(' attributes declarator ')'
2883 // Example: 'char (*X)' or 'int (*XX)(void)'
2884 ParseParenDeclarator(D
);
2886 // If the declarator was parenthesized, we entered the declarator
2887 // scope when parsing the parenthesized declarator, then exited
2888 // the scope already. Re-enter the scope, if we need to.
2889 if (D
.getCXXScopeSpec().isSet()) {
2890 // If there was an error parsing parenthesized declarator, declarator
2891 // scope may have been enterred before. Don't do it again.
2892 if (!D
.isInvalidType() &&
2893 Actions
.ShouldEnterDeclaratorScope(getCurScope(), D
.getCXXScopeSpec()))
2894 // Change the declaration context for name lookup, until this function
2895 // is exited (and the declarator has been parsed).
2896 DeclScopeObj
.EnterDeclaratorScope();
2898 } else if (D
.mayOmitIdentifier()) {
2899 // This could be something simple like "int" (in which case the declarator
2900 // portion is empty), if an abstract-declarator is allowed.
2901 D
.SetIdentifier(0, Tok
.getLocation());
2903 if (D
.getContext() == Declarator::MemberContext
)
2904 Diag(Tok
, diag::err_expected_member_name_or_semi
)
2905 << D
.getDeclSpec().getSourceRange();
2906 else if (getLang().CPlusPlus
)
2907 Diag(Tok
, diag::err_expected_unqualified_id
) << getLang().CPlusPlus
;
2909 Diag(Tok
, diag::err_expected_ident_lparen
);
2910 D
.SetIdentifier(0, Tok
.getLocation());
2911 D
.setInvalidType(true);
2915 assert(D
.isPastIdentifier() &&
2916 "Haven't past the location of the identifier yet?");
2918 // Don't parse attributes unless we have an identifier.
2919 if (D
.getIdentifier())
2920 MaybeParseCXX0XAttributes(D
);
2923 if (Tok
.is(tok::l_paren
)) {
2924 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2925 // In such a case, check if we actually have a function declarator; if it
2926 // is not, the declarator has been fully parsed.
2927 if (getLang().CPlusPlus
&& D
.mayBeFollowedByCXXDirectInit()) {
2928 // When not in file scope, warn for ambiguous function declarators, just
2929 // in case the author intended it as a variable definition.
2930 bool warnIfAmbiguous
= D
.getContext() != Declarator::FileContext
;
2931 if (!isCXXFunctionDeclarator(warnIfAmbiguous
))
2934 ParsedAttributes attrs
;
2935 ParseFunctionDeclarator(ConsumeParen(), D
, attrs
);
2936 } else if (Tok
.is(tok::l_square
)) {
2937 ParseBracketDeclarator(D
);
2944 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2945 /// only called before the identifier, so these are most likely just grouping
2946 /// parens for precedence. If we find that these are actually function
2947 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2949 /// direct-declarator:
2950 /// '(' declarator ')'
2951 /// [GNU] '(' attributes declarator ')'
2952 /// direct-declarator '(' parameter-type-list ')'
2953 /// direct-declarator '(' identifier-list[opt] ')'
2954 /// [GNU] direct-declarator '(' parameter-forward-declarations
2955 /// parameter-type-list[opt] ')'
2957 void Parser::ParseParenDeclarator(Declarator
&D
) {
2958 SourceLocation StartLoc
= ConsumeParen();
2959 assert(!D
.isPastIdentifier() && "Should be called before passing identifier");
2961 // Eat any attributes before we look at whether this is a grouping or function
2962 // declarator paren. If this is a grouping paren, the attribute applies to
2963 // the type being built up, for example:
2964 // int (__attribute__(()) *x)(long y)
2965 // If this ends up not being a grouping paren, the attribute applies to the
2966 // first argument, for example:
2967 // int (__attribute__(()) int x)
2968 // In either case, we need to eat any attributes to be able to determine what
2969 // sort of paren this is.
2971 ParsedAttributes attrs
;
2972 bool RequiresArg
= false;
2973 if (Tok
.is(tok::kw___attribute
)) {
2974 ParseGNUAttributes(attrs
);
2976 // We require that the argument list (if this is a non-grouping paren) be
2977 // present even if the attribute list was empty.
2980 // Eat any Microsoft extensions.
2981 if (Tok
.is(tok::kw___cdecl
) || Tok
.is(tok::kw___stdcall
) ||
2982 Tok
.is(tok::kw___thiscall
) || Tok
.is(tok::kw___fastcall
) ||
2983 Tok
.is(tok::kw___w64
) || Tok
.is(tok::kw___ptr64
)) {
2984 ParseMicrosoftTypeAttributes(attrs
);
2986 // Eat any Borland extensions.
2987 if (Tok
.is(tok::kw___pascal
))
2988 ParseBorlandTypeAttributes(attrs
);
2990 // If we haven't past the identifier yet (or where the identifier would be
2991 // stored, if this is an abstract declarator), then this is probably just
2992 // grouping parens. However, if this could be an abstract-declarator, then
2993 // this could also be the start of function arguments (consider 'void()').
2996 if (!D
.mayOmitIdentifier()) {
2997 // If this can't be an abstract-declarator, this *must* be a grouping
2998 // paren, because we haven't seen the identifier yet.
3000 } else if (Tok
.is(tok::r_paren
) || // 'int()' is a function.
3001 (getLang().CPlusPlus
&& Tok
.is(tok::ellipsis
)) || // C++ int(...)
3002 isDeclarationSpecifier()) { // 'int(int)' is a function.
3003 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3004 // considered to be a type, not a K&R identifier-list.
3007 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3011 // If this is a grouping paren, handle:
3012 // direct-declarator: '(' declarator ')'
3013 // direct-declarator: '(' attributes declarator ')'
3015 bool hadGroupingParens
= D
.hasGroupingParens();
3016 D
.setGroupingParens(true);
3018 D
.addAttributes(attrs
.getList(), SourceLocation());
3020 ParseDeclaratorInternal(D
, &Parser::ParseDirectDeclarator
);
3022 SourceLocation EndLoc
= MatchRHSPunctuation(tok::r_paren
, StartLoc
);
3023 D
.AddTypeInfo(DeclaratorChunk::getParen(StartLoc
, EndLoc
), EndLoc
);
3025 D
.setGroupingParens(hadGroupingParens
);
3029 // Okay, if this wasn't a grouping paren, it must be the start of a function
3030 // argument list. Recognize that this declarator will never have an
3031 // identifier (and remember where it would have been), then call into
3032 // ParseFunctionDeclarator to handle of argument list.
3033 D
.SetIdentifier(0, Tok
.getLocation());
3035 ParseFunctionDeclarator(StartLoc
, D
, attrs
, RequiresArg
);
3038 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
3039 /// declarator D up to a paren, which indicates that we are parsing function
3042 /// If AttrList is non-null, then the caller parsed those arguments immediately
3043 /// after the open paren - they should be considered to be the first argument of
3044 /// a parameter. If RequiresArg is true, then the first argument of the
3045 /// function is required to be present and required to not be an identifier
3048 /// This method also handles this portion of the grammar:
3049 /// parameter-type-list: [C99 6.7.5]
3051 /// parameter-list ',' '...'
3052 /// [C++] parameter-list '...'
3054 /// parameter-list: [C99 6.7.5]
3055 /// parameter-declaration
3056 /// parameter-list ',' parameter-declaration
3058 /// parameter-declaration: [C99 6.7.5]
3059 /// declaration-specifiers declarator
3060 /// [C++] declaration-specifiers declarator '=' assignment-expression
3061 /// [GNU] declaration-specifiers declarator attributes
3062 /// declaration-specifiers abstract-declarator[opt]
3063 /// [C++] declaration-specifiers abstract-declarator[opt]
3064 /// '=' assignment-expression
3065 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
3067 /// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
3068 /// and "exception-specification[opt]".
3070 void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc
, Declarator
&D
,
3071 ParsedAttributes
&attrs
,
3073 // lparen is already consumed!
3074 assert(D
.isPastIdentifier() && "Should not call before identifier!");
3076 ParsedType TrailingReturnType
;
3078 // This parameter list may be empty.
3079 if (Tok
.is(tok::r_paren
)) {
3081 Diag(Tok
, diag::err_argument_required_after_attribute
);
3083 SourceLocation RParenLoc
= ConsumeParen(); // Eat the closing ')'.
3084 SourceLocation EndLoc
= RParenLoc
;
3086 // cv-qualifier-seq[opt].
3088 bool hasExceptionSpec
= false;
3089 SourceLocation ThrowLoc
;
3090 bool hasAnyExceptionSpec
= false;
3091 llvm::SmallVector
<ParsedType
, 2> Exceptions
;
3092 llvm::SmallVector
<SourceRange
, 2> ExceptionRanges
;
3093 if (getLang().CPlusPlus
) {
3094 MaybeParseCXX0XAttributes(attrs
);
3096 ParseTypeQualifierListOpt(DS
, false /*no attributes*/);
3097 if (!DS
.getSourceRange().getEnd().isInvalid())
3098 EndLoc
= DS
.getSourceRange().getEnd();
3100 // Parse exception-specification[opt].
3101 if (Tok
.is(tok::kw_throw
)) {
3102 hasExceptionSpec
= true;
3103 ThrowLoc
= Tok
.getLocation();
3104 ParseExceptionSpecification(EndLoc
, Exceptions
, ExceptionRanges
,
3105 hasAnyExceptionSpec
);
3106 assert(Exceptions
.size() == ExceptionRanges
.size() &&
3107 "Produced different number of exception types and ranges.");
3110 // Parse trailing-return-type.
3111 if (getLang().CPlusPlus0x
&& Tok
.is(tok::arrow
)) {
3112 TrailingReturnType
= ParseTrailingReturnType().get();
3116 // Remember that we parsed a function type, and remember the attributes.
3117 // int() -> no prototype, no '...'.
3118 D
.AddTypeInfo(DeclaratorChunk::getFunction(attrs
,
3119 /*prototype*/getLang().CPlusPlus
,
3123 DS
.getTypeQualifiers(),
3124 hasExceptionSpec
, ThrowLoc
,
3125 hasAnyExceptionSpec
,
3127 ExceptionRanges
.data(),
3129 LParenLoc
, RParenLoc
, D
,
3130 TrailingReturnType
),
3135 // Alternatively, this parameter list may be an identifier list form for a
3136 // K&R-style function: void foo(a,b,c)
3137 if (!getLang().CPlusPlus
&& Tok
.is(tok::identifier
)
3138 && !TryAltiVecVectorToken()) {
3139 if (TryAnnotateTypeOrScopeToken() || !Tok
.is(tok::annot_typename
)) {
3140 // K&R identifier lists can't have typedefs as identifiers, per
3143 Diag(Tok
, diag::err_argument_required_after_attribute
);
3145 // Identifier list. Note that '(' identifier-list ')' is only allowed for
3146 // normal declarators, not for abstract-declarators. Get the first
3148 Token FirstTok
= Tok
;
3149 ConsumeToken(); // eat the first identifier.
3151 // Identifier lists follow a really simple grammar: the identifiers can
3152 // be followed *only* by a ", moreidentifiers" or ")". However, K&R
3153 // identifier lists are really rare in the brave new modern world, and it
3154 // is very common for someone to typo a type in a non-k&r style list. If
3155 // we are presented with something like: "void foo(intptr x, float y)",
3156 // we don't want to start parsing the function declarator as though it is
3157 // a K&R style declarator just because intptr is an invalid type.
3159 // To handle this, we check to see if the token after the first identifier
3160 // is a "," or ")". Only if so, do we parse it as an identifier list.
3161 if (Tok
.is(tok::comma
) || Tok
.is(tok::r_paren
))
3162 return ParseFunctionDeclaratorIdentifierList(LParenLoc
,
3163 FirstTok
.getIdentifierInfo(),
3164 FirstTok
.getLocation(), D
);
3166 // If we get here, the code is invalid. Push the first identifier back
3167 // into the token stream and parse the first argument as an (invalid)
3168 // normal argument declarator.
3174 // Finally, a normal, non-empty parameter type list.
3176 // Build up an array of information about the parsed arguments.
3177 llvm::SmallVector
<DeclaratorChunk::ParamInfo
, 16> ParamInfo
;
3179 // Enter function-declaration scope, limiting any declarators to the
3180 // function prototype scope, including parameter declarators.
3181 ParseScope
PrototypeScope(this,
3182 Scope::FunctionPrototypeScope
|Scope::DeclScope
);
3184 bool IsVariadic
= false;
3185 SourceLocation EllipsisLoc
;
3187 if (Tok
.is(tok::ellipsis
)) {
3189 EllipsisLoc
= ConsumeToken(); // Consume the ellipsis.
3193 // Parse the declaration-specifiers.
3194 // Just use the ParsingDeclaration "scope" of the declarator.
3197 // Skip any Microsoft attributes before a param.
3198 if (getLang().Microsoft
&& Tok
.is(tok::l_square
))
3199 ParseMicrosoftAttributes(DS
.getAttributes());
3201 SourceLocation DSStart
= Tok
.getLocation();
3203 // If the caller parsed attributes for the first argument, add them now.
3204 // Take them so that we only apply the attributes to the first parameter.
3205 DS
.takeAttributesFrom(attrs
);
3207 ParseDeclarationSpecifiers(DS
);
3209 // Parse the declarator. This is "PrototypeContext", because we must
3210 // accept either 'declarator' or 'abstract-declarator' here.
3211 Declarator
ParmDecl(DS
, Declarator::PrototypeContext
);
3212 ParseDeclarator(ParmDecl
);
3214 // Parse GNU attributes, if present.
3215 MaybeParseGNUAttributes(ParmDecl
);
3217 // Remember this parsed parameter in ParamInfo.
3218 IdentifierInfo
*ParmII
= ParmDecl
.getIdentifier();
3220 // DefArgToks is used when the parsing of default arguments needs
3222 CachedTokens
*DefArgToks
= 0;
3224 // If no parameter was specified, verify that *something* was specified,
3225 // otherwise we have a missing type and identifier.
3226 if (DS
.isEmpty() && ParmDecl
.getIdentifier() == 0 &&
3227 ParmDecl
.getNumTypeObjects() == 0) {
3228 // Completely missing, emit error.
3229 Diag(DSStart
, diag::err_missing_param
);
3231 // Otherwise, we have something. Add it and let semantic analysis try
3232 // to grok it and add the result to the ParamInfo we are building.
3234 // Inform the actions module about the parameter declarator, so it gets
3235 // added to the current scope.
3236 Decl
*Param
= Actions
.ActOnParamDeclarator(getCurScope(), ParmDecl
);
3238 // Parse the default argument, if any. We parse the default
3239 // arguments in all dialects; the semantic analysis in
3240 // ActOnParamDefaultArgument will reject the default argument in
3242 if (Tok
.is(tok::equal
)) {
3243 SourceLocation EqualLoc
= Tok
.getLocation();
3245 // Parse the default argument
3246 if (D
.getContext() == Declarator::MemberContext
) {
3247 // If we're inside a class definition, cache the tokens
3248 // corresponding to the default argument. We'll actually parse
3249 // them when we see the end of the class definition.
3250 // FIXME: Templates will require something similar.
3251 // FIXME: Can we use a smart pointer for Toks?
3252 DefArgToks
= new CachedTokens
;
3254 if (!ConsumeAndStoreUntil(tok::comma
, tok::r_paren
, *DefArgToks
,
3255 /*StopAtSemi=*/true,
3256 /*ConsumeFinalToken=*/false)) {
3259 Actions
.ActOnParamDefaultArgumentError(Param
);
3261 // Mark the end of the default argument so that we know when to
3262 // stop when we parse it later on.
3264 DefArgEnd
.startToken();
3265 DefArgEnd
.setKind(tok::cxx_defaultarg_end
);
3266 DefArgEnd
.setLocation(Tok
.getLocation());
3267 DefArgToks
->push_back(DefArgEnd
);
3268 Actions
.ActOnParamUnparsedDefaultArgument(Param
, EqualLoc
,
3269 (*DefArgToks
)[1].getLocation());
3275 // The argument isn't actually potentially evaluated unless it is
3277 EnterExpressionEvaluationContext
Eval(Actions
,
3278 Sema::PotentiallyEvaluatedIfUsed
);
3280 ExprResult
DefArgResult(ParseAssignmentExpression());
3281 if (DefArgResult
.isInvalid()) {
3282 Actions
.ActOnParamDefaultArgumentError(Param
);
3283 SkipUntil(tok::comma
, tok::r_paren
, true, true);
3285 // Inform the actions module about the default argument
3286 Actions
.ActOnParamDefaultArgument(Param
, EqualLoc
,
3287 DefArgResult
.take());
3292 ParamInfo
.push_back(DeclaratorChunk::ParamInfo(ParmII
,
3293 ParmDecl
.getIdentifierLoc(), Param
,
3297 // If the next token is a comma, consume it and keep reading arguments.
3298 if (Tok
.isNot(tok::comma
)) {
3299 if (Tok
.is(tok::ellipsis
)) {
3301 EllipsisLoc
= ConsumeToken(); // Consume the ellipsis.
3303 if (!getLang().CPlusPlus
) {
3304 // We have ellipsis without a preceding ',', which is ill-formed
3305 // in C. Complain and provide the fix.
3306 Diag(EllipsisLoc
, diag::err_missing_comma_before_ellipsis
)
3307 << FixItHint::CreateInsertion(EllipsisLoc
, ", ");
3314 // Consume the comma.
3318 // If we have the closing ')', eat it.
3319 SourceLocation RParenLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
3320 SourceLocation EndLoc
= RParenLoc
;
3323 bool hasExceptionSpec
= false;
3324 SourceLocation ThrowLoc
;
3325 bool hasAnyExceptionSpec
= false;
3326 llvm::SmallVector
<ParsedType
, 2> Exceptions
;
3327 llvm::SmallVector
<SourceRange
, 2> ExceptionRanges
;
3329 if (getLang().CPlusPlus
) {
3330 MaybeParseCXX0XAttributes(attrs
);
3332 // Parse cv-qualifier-seq[opt].
3333 ParseTypeQualifierListOpt(DS
, false /*no attributes*/);
3334 if (!DS
.getSourceRange().getEnd().isInvalid())
3335 EndLoc
= DS
.getSourceRange().getEnd();
3337 // Parse exception-specification[opt].
3338 if (Tok
.is(tok::kw_throw
)) {
3339 hasExceptionSpec
= true;
3340 ThrowLoc
= Tok
.getLocation();
3341 ParseExceptionSpecification(EndLoc
, Exceptions
, ExceptionRanges
,
3342 hasAnyExceptionSpec
);
3343 assert(Exceptions
.size() == ExceptionRanges
.size() &&
3344 "Produced different number of exception types and ranges.");
3347 // Parse trailing-return-type.
3348 if (getLang().CPlusPlus0x
&& Tok
.is(tok::arrow
)) {
3349 TrailingReturnType
= ParseTrailingReturnType().get();
3353 // FIXME: We should leave the prototype scope before parsing the exception
3354 // specification, and then reenter it when parsing the trailing return type.
3356 // Leave prototype scope.
3357 PrototypeScope
.Exit();
3359 // Remember that we parsed a function type, and remember the attributes.
3360 D
.AddTypeInfo(DeclaratorChunk::getFunction(attrs
,
3361 /*proto*/true, IsVariadic
,
3363 ParamInfo
.data(), ParamInfo
.size(),
3364 DS
.getTypeQualifiers(),
3365 hasExceptionSpec
, ThrowLoc
,
3366 hasAnyExceptionSpec
,
3368 ExceptionRanges
.data(),
3370 LParenLoc
, RParenLoc
, D
,
3371 TrailingReturnType
),
3375 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3376 /// we found a K&R-style identifier list instead of a type argument list. The
3377 /// first identifier has already been consumed, and the current token is the
3378 /// token right after it.
3380 /// identifier-list: [C99 6.7.5]
3382 /// identifier-list ',' identifier
3384 void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc
,
3385 IdentifierInfo
*FirstIdent
,
3386 SourceLocation FirstIdentLoc
,
3388 // Build up an array of information about the parsed arguments.
3389 llvm::SmallVector
<DeclaratorChunk::ParamInfo
, 16> ParamInfo
;
3390 llvm::SmallSet
<const IdentifierInfo
*, 16> ParamsSoFar
;
3392 // If there was no identifier specified for the declarator, either we are in
3393 // an abstract-declarator, or we are in a parameter declarator which was found
3394 // to be abstract. In abstract-declarators, identifier lists are not valid:
3396 if (!D
.getIdentifier())
3397 Diag(FirstIdentLoc
, diag::ext_ident_list_in_param
);
3399 // The first identifier was already read, and is known to be the first
3400 // identifier in the list. Remember this identifier in ParamInfo.
3401 ParamsSoFar
.insert(FirstIdent
);
3402 ParamInfo
.push_back(DeclaratorChunk::ParamInfo(FirstIdent
, FirstIdentLoc
, 0));
3404 while (Tok
.is(tok::comma
)) {
3408 // If this isn't an identifier, report the error and skip until ')'.
3409 if (Tok
.isNot(tok::identifier
)) {
3410 Diag(Tok
, diag::err_expected_ident
);
3411 SkipUntil(tok::r_paren
);
3415 IdentifierInfo
*ParmII
= Tok
.getIdentifierInfo();
3417 // Reject 'typedef int y; int test(x, y)', but continue parsing.
3418 if (Actions
.getTypeName(*ParmII
, Tok
.getLocation(), getCurScope()))
3419 Diag(Tok
, diag::err_unexpected_typedef_ident
) << ParmII
;
3421 // Verify that the argument identifier has not already been mentioned.
3422 if (!ParamsSoFar
.insert(ParmII
)) {
3423 Diag(Tok
, diag::err_param_redefinition
) << ParmII
;
3425 // Remember this identifier in ParamInfo.
3426 ParamInfo
.push_back(DeclaratorChunk::ParamInfo(ParmII
,
3431 // Eat the identifier.
3435 // If we have the closing ')', eat it and we're done.
3436 SourceLocation RLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
3438 // Remember that we parsed a function type, and remember the attributes. This
3439 // function type is always a K&R style function type, which is not varargs and
3440 // has no prototype.
3441 D
.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
3442 /*proto*/false, /*varargs*/false,
3444 &ParamInfo
[0], ParamInfo
.size(),
3447 SourceLocation(), false, 0, 0, 0,
3448 LParenLoc
, RLoc
, D
),
3452 /// [C90] direct-declarator '[' constant-expression[opt] ']'
3453 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3454 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3455 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3456 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
3457 void Parser::ParseBracketDeclarator(Declarator
&D
) {
3458 SourceLocation StartLoc
= ConsumeBracket();
3460 // C array syntax has many features, but by-far the most common is [] and [4].
3461 // This code does a fast path to handle some of the most obvious cases.
3462 if (Tok
.getKind() == tok::r_square
) {
3463 SourceLocation EndLoc
= MatchRHSPunctuation(tok::r_square
, StartLoc
);
3464 ParsedAttributes attrs
;
3465 MaybeParseCXX0XAttributes(attrs
);
3467 // Remember that we parsed the empty array type.
3468 ExprResult NumElements
;
3469 D
.AddTypeInfo(DeclaratorChunk::getArray(0, attrs
, false, false, 0,
3473 } else if (Tok
.getKind() == tok::numeric_constant
&&
3474 GetLookAheadToken(1).is(tok::r_square
)) {
3475 // [4] is very common. Parse the numeric constant expression.
3476 ExprResult
ExprRes(Actions
.ActOnNumericConstant(Tok
));
3479 SourceLocation EndLoc
= MatchRHSPunctuation(tok::r_square
, StartLoc
);
3480 ParsedAttributes attrs
;
3481 MaybeParseCXX0XAttributes(attrs
);
3483 // Remember that we parsed a array type, and remember its features.
3484 D
.AddTypeInfo(DeclaratorChunk::getArray(0, attrs
, false, 0,
3491 // If valid, this location is the position where we read the 'static' keyword.
3492 SourceLocation StaticLoc
;
3493 if (Tok
.is(tok::kw_static
))
3494 StaticLoc
= ConsumeToken();
3496 // If there is a type-qualifier-list, read it now.
3497 // Type qualifiers in an array subscript are a C99 feature.
3499 ParseTypeQualifierListOpt(DS
, false /*no attributes*/);
3501 // If we haven't already read 'static', check to see if there is one after the
3502 // type-qualifier-list.
3503 if (!StaticLoc
.isValid() && Tok
.is(tok::kw_static
))
3504 StaticLoc
= ConsumeToken();
3506 // Handle "direct-declarator [ type-qual-list[opt] * ]".
3507 bool isStar
= false;
3508 ExprResult NumElements
;
3510 // Handle the case where we have '[*]' as the array size. However, a leading
3511 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
3512 // the the token after the star is a ']'. Since stars in arrays are
3513 // infrequent, use of lookahead is not costly here.
3514 if (Tok
.is(tok::star
) && GetLookAheadToken(1).is(tok::r_square
)) {
3515 ConsumeToken(); // Eat the '*'.
3517 if (StaticLoc
.isValid()) {
3518 Diag(StaticLoc
, diag::err_unspecified_vla_size_with_static
);
3519 StaticLoc
= SourceLocation(); // Drop the static.
3522 } else if (Tok
.isNot(tok::r_square
)) {
3523 // Note, in C89, this production uses the constant-expr production instead
3524 // of assignment-expr. The only difference is that assignment-expr allows
3525 // things like '=' and '*='. Sema rejects these in C89 mode because they
3526 // are not i-c-e's, so we don't need to distinguish between the two here.
3528 // Parse the constant-expression or assignment-expression now (depending
3530 if (getLang().CPlusPlus
)
3531 NumElements
= ParseConstantExpression();
3533 NumElements
= ParseAssignmentExpression();
3536 // If there was an error parsing the assignment-expression, recover.
3537 if (NumElements
.isInvalid()) {
3538 D
.setInvalidType(true);
3539 // If the expression was invalid, skip it.
3540 SkipUntil(tok::r_square
);
3544 SourceLocation EndLoc
= MatchRHSPunctuation(tok::r_square
, StartLoc
);
3546 ParsedAttributes attrs
;
3547 MaybeParseCXX0XAttributes(attrs
);
3549 // Remember that we parsed a array type, and remember its features.
3550 D
.AddTypeInfo(DeclaratorChunk::getArray(DS
.getTypeQualifiers(), attrs
,
3551 StaticLoc
.isValid(), isStar
,
3552 NumElements
.release(),
3557 /// [GNU] typeof-specifier:
3558 /// typeof ( expressions )
3559 /// typeof ( type-name )
3560 /// [GNU/C++] typeof unary-expression
3562 void Parser::ParseTypeofSpecifier(DeclSpec
&DS
) {
3563 assert(Tok
.is(tok::kw_typeof
) && "Not a typeof specifier");
3565 SourceLocation StartLoc
= ConsumeToken();
3567 const bool hasParens
= Tok
.is(tok::l_paren
);
3571 SourceRange CastRange
;
3572 ExprResult Operand
= ParseExprAfterTypeofSizeofAlignof(OpTok
,
3577 DS
.setTypeofParensRange(CastRange
);
3579 if (CastRange
.getEnd().isInvalid())
3580 // FIXME: Not accurate, the range gets one token more than it should.
3581 DS
.SetRangeEnd(Tok
.getLocation());
3583 DS
.SetRangeEnd(CastRange
.getEnd());
3587 DS
.SetTypeSpecError();
3591 const char *PrevSpec
= 0;
3593 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3594 if (DS
.SetTypeSpecType(DeclSpec::TST_typeofType
, StartLoc
, PrevSpec
,
3596 Diag(StartLoc
, DiagID
) << PrevSpec
;
3600 // If we get here, the operand to the typeof was an expresion.
3601 if (Operand
.isInvalid()) {
3602 DS
.SetTypeSpecError();
3606 const char *PrevSpec
= 0;
3608 // Check for duplicate type specifiers (e.g. "int typeof(int)").
3609 if (DS
.SetTypeSpecType(DeclSpec::TST_typeofExpr
, StartLoc
, PrevSpec
,
3610 DiagID
, Operand
.get()))
3611 Diag(StartLoc
, DiagID
) << PrevSpec
;
3615 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
3616 /// from TryAltiVecVectorToken.
3617 bool Parser::TryAltiVecVectorTokenOutOfLine() {
3618 Token Next
= NextToken();
3619 switch (Next
.getKind()) {
3620 default: return false;
3623 case tok::kw_signed
:
3624 case tok::kw_unsigned
:
3629 case tok::kw_double
:
3631 case tok::kw___pixel
:
3632 Tok
.setKind(tok::kw___vector
);
3634 case tok::identifier
:
3635 if (Next
.getIdentifierInfo() == Ident_pixel
) {
3636 Tok
.setKind(tok::kw___vector
);
3643 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec
&DS
, SourceLocation Loc
,
3644 const char *&PrevSpec
, unsigned &DiagID
,
3646 if (Tok
.getIdentifierInfo() == Ident_vector
) {
3647 Token Next
= NextToken();
3648 switch (Next
.getKind()) {
3651 case tok::kw_signed
:
3652 case tok::kw_unsigned
:
3657 case tok::kw_double
:
3659 case tok::kw___pixel
:
3660 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
);
3662 case tok::identifier
:
3663 if (Next
.getIdentifierInfo() == Ident_pixel
) {
3664 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
);
3671 } else if ((Tok
.getIdentifierInfo() == Ident_pixel
) &&
3672 DS
.isTypeAltiVecVector()) {
3673 isInvalid
= DS
.SetTypeAltiVecPixel(true, Loc
, PrevSpec
, DiagID
);