blob: db568df26e1aeb9410e86e468ad8494dc632ef46 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/DeclSpec.h"
Chris Lattnera7549902007-08-26 06:24:45 +000016#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "llvm/ADT/SmallSet.h"
18using namespace clang;
19
20//===----------------------------------------------------------------------===//
21// C99 6.7: Declarations.
22//===----------------------------------------------------------------------===//
23
24/// ParseTypeName
25/// type-name: [C99 6.7.6]
26/// specifier-qualifier-list abstract-declarator[opt]
27Parser::TypeTy *Parser::ParseTypeName() {
28 // Parse the common declaration-specifiers piece.
29 DeclSpec DS;
30 ParseSpecifierQualifierList(DS);
31
32 // Parse the abstract-declarator, if present.
33 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
34 ParseDeclarator(DeclaratorInfo);
35
Steve Naroff0acc9c92007-09-15 18:49:24 +000036 return Actions.ActOnTypeName(CurScope, DeclaratorInfo).Val;
Chris Lattner4b009652007-07-25 00:24:17 +000037}
38
39/// ParseAttributes - Parse a non-empty attributes list.
40///
41/// [GNU] attributes:
42/// attribute
43/// attributes attribute
44///
45/// [GNU] attribute:
46/// '__attribute__' '(' '(' attribute-list ')' ')'
47///
48/// [GNU] attribute-list:
49/// attrib
50/// attribute_list ',' attrib
51///
52/// [GNU] attrib:
53/// empty
54/// attrib-name
55/// attrib-name '(' identifier ')'
56/// attrib-name '(' identifier ',' nonempty-expr-list ')'
57/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
58///
59/// [GNU] attrib-name:
60/// identifier
61/// typespec
62/// typequal
63/// storageclass
64///
65/// FIXME: The GCC grammar/code for this construct implies we need two
66/// token lookahead. Comment from gcc: "If they start with an identifier
67/// which is followed by a comma or close parenthesis, then the arguments
68/// start with that identifier; otherwise they are an expression list."
69///
70/// At the moment, I am not doing 2 token lookahead. I am also unaware of
71/// any attributes that don't work (based on my limited testing). Most
72/// attributes are very simple in practice. Until we find a bug, I don't see
73/// a pressing need to implement the 2 token lookahead.
74
75AttributeList *Parser::ParseAttributes() {
76 assert(Tok.getKind() == tok::kw___attribute && "Not an attribute list!");
77
78 AttributeList *CurrAttr = 0;
79
80 while (Tok.getKind() == tok::kw___attribute) {
81 ConsumeToken();
82 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
83 "attribute")) {
84 SkipUntil(tok::r_paren, true); // skip until ) or ;
85 return CurrAttr;
86 }
87 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
88 SkipUntil(tok::r_paren, true); // skip until ) or ;
89 return CurrAttr;
90 }
91 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
92 while (Tok.getKind() == tok::identifier || isDeclarationSpecifier() ||
93 Tok.getKind() == tok::comma) {
94
95 if (Tok.getKind() == tok::comma) {
96 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
97 ConsumeToken();
98 continue;
99 }
100 // we have an identifier or declaration specifier (const, int, etc.)
101 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
102 SourceLocation AttrNameLoc = ConsumeToken();
103
104 // check if we have a "paramterized" attribute
105 if (Tok.getKind() == tok::l_paren) {
106 ConsumeParen(); // ignore the left paren loc for now
107
108 if (Tok.getKind() == tok::identifier) {
109 IdentifierInfo *ParmName = Tok.getIdentifierInfo();
110 SourceLocation ParmLoc = ConsumeToken();
111
112 if (Tok.getKind() == tok::r_paren) {
113 // __attribute__(( mode(byte) ))
114 ConsumeParen(); // ignore the right paren loc for now
115 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
116 ParmName, ParmLoc, 0, 0, CurrAttr);
117 } else if (Tok.getKind() == tok::comma) {
118 ConsumeToken();
119 // __attribute__(( format(printf, 1, 2) ))
120 llvm::SmallVector<ExprTy*, 8> ArgExprs;
121 bool ArgExprsOk = true;
122
123 // now parse the non-empty comma separated list of expressions
124 while (1) {
125 ExprResult ArgExpr = ParseAssignmentExpression();
126 if (ArgExpr.isInvalid) {
127 ArgExprsOk = false;
128 SkipUntil(tok::r_paren);
129 break;
130 } else {
131 ArgExprs.push_back(ArgExpr.Val);
132 }
133 if (Tok.getKind() != tok::comma)
134 break;
135 ConsumeToken(); // Eat the comma, move to the next argument
136 }
137 if (ArgExprsOk && Tok.getKind() == tok::r_paren) {
138 ConsumeParen(); // ignore the right paren loc for now
139 CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
140 ParmLoc, &ArgExprs[0], ArgExprs.size(), CurrAttr);
141 }
142 }
143 } else { // not an identifier
144 // parse a possibly empty comma separated list of expressions
145 if (Tok.getKind() == tok::r_paren) {
146 // __attribute__(( nonnull() ))
147 ConsumeParen(); // ignore the right paren loc for now
148 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
149 0, SourceLocation(), 0, 0, CurrAttr);
150 } else {
151 // __attribute__(( aligned(16) ))
152 llvm::SmallVector<ExprTy*, 8> ArgExprs;
153 bool ArgExprsOk = true;
154
155 // now parse the list of expressions
156 while (1) {
157 ExprResult ArgExpr = ParseAssignmentExpression();
158 if (ArgExpr.isInvalid) {
159 ArgExprsOk = false;
160 SkipUntil(tok::r_paren);
161 break;
162 } else {
163 ArgExprs.push_back(ArgExpr.Val);
164 }
165 if (Tok.getKind() != tok::comma)
166 break;
167 ConsumeToken(); // Eat the comma, move to the next argument
168 }
169 // Match the ')'.
170 if (ArgExprsOk && Tok.getKind() == tok::r_paren) {
171 ConsumeParen(); // ignore the right paren loc for now
172 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
173 SourceLocation(), &ArgExprs[0], ArgExprs.size(),
174 CurrAttr);
175 }
176 }
177 }
178 } else {
179 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
180 0, SourceLocation(), 0, 0, CurrAttr);
181 }
182 }
183 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
184 SkipUntil(tok::r_paren, false);
185 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
186 SkipUntil(tok::r_paren, false);
187 }
188 return CurrAttr;
189}
190
191/// ParseDeclaration - Parse a full 'declaration', which consists of
192/// declaration-specifiers, some number of declarators, and a semicolon.
193/// 'Context' should be a Declarator::TheContext value.
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000194///
195/// declaration: [C99 6.7]
196/// block-declaration ->
197/// simple-declaration
198/// others [FIXME]
199/// [C++] namespace-definition
200/// others... [FIXME]
201///
Chris Lattner4b009652007-07-25 00:24:17 +0000202Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000203 switch (Tok.getKind()) {
204 case tok::kw_namespace:
205 return ParseNamespace(Context);
206 default:
207 return ParseSimpleDeclaration(Context);
208 }
209}
210
211/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
212/// declaration-specifiers init-declarator-list[opt] ';'
213///[C90/C++]init-declarator-list ';' [TODO]
214/// [OMP] threadprivate-directive [TODO]
215Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) {
Chris Lattner4b009652007-07-25 00:24:17 +0000216 // Parse the common declaration-specifiers piece.
217 DeclSpec DS;
218 ParseDeclarationSpecifiers(DS);
219
220 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
221 // declaration-specifiers init-declarator-list[opt] ';'
222 if (Tok.getKind() == tok::semi) {
223 ConsumeToken();
224 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
225 }
226
227 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
228 ParseDeclarator(DeclaratorInfo);
229
230 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
231}
232
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000233
Chris Lattner4b009652007-07-25 00:24:17 +0000234/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
235/// parsing 'declaration-specifiers declarator'. This method is split out this
236/// way to handle the ambiguity between top-level function-definitions and
237/// declarations.
238///
Chris Lattner4b009652007-07-25 00:24:17 +0000239/// init-declarator-list: [C99 6.7]
240/// init-declarator
241/// init-declarator-list ',' init-declarator
242/// init-declarator: [C99 6.7]
243/// declarator
244/// declarator '=' initializer
245/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
246/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
247///
248Parser::DeclTy *Parser::
249ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
250
251 // Declarators may be grouped together ("int X, *Y, Z();"). Provide info so
252 // that they can be chained properly if the actions want this.
253 Parser::DeclTy *LastDeclInGroup = 0;
254
255 // At this point, we know that it is not a function definition. Parse the
256 // rest of the init-declarator-list.
257 while (1) {
258 // If a simple-asm-expr is present, parse it.
259 if (Tok.getKind() == tok::kw_asm)
260 ParseSimpleAsm();
261
262 // If attributes are present, parse them.
263 if (Tok.getKind() == tok::kw___attribute)
264 D.AddAttributes(ParseAttributes());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000265
266 // Inform the current actions module that we just parsed this declarator.
267 // FIXME: pass asm & attributes.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000268 LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000269
Chris Lattner4b009652007-07-25 00:24:17 +0000270 // Parse declarator '=' initializer.
271 ExprResult Init;
272 if (Tok.getKind() == tok::equal) {
273 ConsumeToken();
274 Init = ParseInitializer();
275 if (Init.isInvalid) {
276 SkipUntil(tok::semi);
277 return 0;
278 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000279 Actions.AddInitializerToDecl(LastDeclInGroup, Init.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000280 }
281
Chris Lattner4b009652007-07-25 00:24:17 +0000282 // If we don't have a comma, it is either the end of the list (a ';') or an
283 // error, bail out.
284 if (Tok.getKind() != tok::comma)
285 break;
286
287 // Consume the comma.
288 ConsumeToken();
289
290 // Parse the next declarator.
291 D.clear();
292 ParseDeclarator(D);
293 }
294
295 if (Tok.getKind() == tok::semi) {
296 ConsumeToken();
297 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
298 }
299
300 Diag(Tok, diag::err_parse_error);
301 // Skip to end of block or statement
Chris Lattnerf491b412007-08-21 18:36:18 +0000302 SkipUntil(tok::r_brace, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000303 if (Tok.getKind() == tok::semi)
304 ConsumeToken();
305 return 0;
306}
307
308/// ParseSpecifierQualifierList
309/// specifier-qualifier-list:
310/// type-specifier specifier-qualifier-list[opt]
311/// type-qualifier specifier-qualifier-list[opt]
312/// [GNU] attributes specifier-qualifier-list[opt]
313///
314void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
315 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
316 /// parse declaration-specifiers and complain about extra stuff.
317 ParseDeclarationSpecifiers(DS);
318
319 // Validate declspec for type-name.
320 unsigned Specs = DS.getParsedSpecifiers();
321 if (Specs == DeclSpec::PQ_None)
322 Diag(Tok, diag::err_typename_requires_specqual);
323
324 // Issue diagnostic and remove storage class if present.
325 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
326 if (DS.getStorageClassSpecLoc().isValid())
327 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
328 else
329 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
330 DS.ClearStorageClassSpecs();
331 }
332
333 // Issue diagnostic and remove function specfier if present.
334 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
335 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
336 DS.ClearFunctionSpecs();
337 }
338}
339
340/// ParseDeclarationSpecifiers
341/// declaration-specifiers: [C99 6.7]
342/// storage-class-specifier declaration-specifiers[opt]
343/// type-specifier declaration-specifiers[opt]
344/// type-qualifier declaration-specifiers[opt]
345/// [C99] function-specifier declaration-specifiers[opt]
346/// [GNU] attributes declaration-specifiers[opt]
347///
348/// storage-class-specifier: [C99 6.7.1]
349/// 'typedef'
350/// 'extern'
351/// 'static'
352/// 'auto'
353/// 'register'
354/// [GNU] '__thread'
355/// type-specifier: [C99 6.7.2]
356/// 'void'
357/// 'char'
358/// 'short'
359/// 'int'
360/// 'long'
361/// 'float'
362/// 'double'
363/// 'signed'
364/// 'unsigned'
365/// struct-or-union-specifier
366/// enum-specifier
367/// typedef-name
368/// [C++] 'bool'
369/// [C99] '_Bool'
370/// [C99] '_Complex'
371/// [C99] '_Imaginary' // Removed in TC2?
372/// [GNU] '_Decimal32'
373/// [GNU] '_Decimal64'
374/// [GNU] '_Decimal128'
Steve Naroff4c255ab2007-07-31 23:56:32 +0000375/// [GNU] typeof-specifier
Chris Lattner4b009652007-07-25 00:24:17 +0000376/// [OBJC] class-name objc-protocol-refs[opt] [TODO]
Steve Naroffa8ee2262007-08-22 23:18:22 +0000377/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
Chris Lattner4b009652007-07-25 00:24:17 +0000378/// type-qualifier:
379/// 'const'
380/// 'volatile'
381/// [C99] 'restrict'
382/// function-specifier: [C99 6.7.4]
383/// [C99] 'inline'
384///
385void Parser::ParseDeclarationSpecifiers(DeclSpec &DS) {
386 DS.Range.setBegin(Tok.getLocation());
387 while (1) {
388 int isInvalid = false;
389 const char *PrevSpec = 0;
390 SourceLocation Loc = Tok.getLocation();
391
392 switch (Tok.getKind()) {
393 // typedef-name
394 case tok::identifier:
395 // This identifier can only be a typedef name if we haven't already seen
396 // a type-specifier. Without this check we misparse:
397 // typedef int X; struct Y { short X; }; as 'short int'.
398 if (!DS.hasTypeSpecifier()) {
399 // It has to be available as a typedef too!
400 if (void *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(),
401 CurScope)) {
402 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
403 TypeRep);
Steve Naroffa8ee2262007-08-22 23:18:22 +0000404 if (isInvalid)
405 break;
406 else { // FIXME: restrict this to "id" and ObjC classnames.
407 DS.Range.setEnd(Tok.getLocation());
408 ConsumeToken(); // The identifier
Steve Naroff304ed392007-09-05 23:30:30 +0000409 if (Tok.getKind() == tok::less) {
410 llvm::SmallVector<IdentifierInfo *, 8> ProtocolRefs;
411 ParseObjCProtocolReferences(ProtocolRefs);
412 }
Steve Naroffa8ee2262007-08-22 23:18:22 +0000413 continue;
414 }
Chris Lattner4b009652007-07-25 00:24:17 +0000415 }
416 }
417 // FALL THROUGH.
418 default:
419 // If this is not a declaration specifier token, we're done reading decl
420 // specifiers. First verify that DeclSpec's are consistent.
421 DS.Finish(Diags, getLang());
422 return;
423
424 // GNU attributes support.
425 case tok::kw___attribute:
426 DS.AddAttributes(ParseAttributes());
427 continue;
428
429 // storage-class-specifier
430 case tok::kw_typedef:
431 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
432 break;
433 case tok::kw_extern:
434 if (DS.isThreadSpecified())
435 Diag(Tok, diag::ext_thread_before, "extern");
436 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
437 break;
438 case tok::kw_static:
439 if (DS.isThreadSpecified())
440 Diag(Tok, diag::ext_thread_before, "static");
441 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
442 break;
443 case tok::kw_auto:
444 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
445 break;
446 case tok::kw_register:
447 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
448 break;
449 case tok::kw___thread:
450 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
451 break;
452
453 // type-specifiers
454 case tok::kw_short:
455 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
456 break;
457 case tok::kw_long:
458 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
459 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
460 else
461 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
462 break;
463 case tok::kw_signed:
464 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
465 break;
466 case tok::kw_unsigned:
467 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
468 break;
469 case tok::kw__Complex:
470 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
471 break;
472 case tok::kw__Imaginary:
473 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
474 break;
475 case tok::kw_void:
476 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
477 break;
478 case tok::kw_char:
479 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
480 break;
481 case tok::kw_int:
482 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
483 break;
484 case tok::kw_float:
485 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
486 break;
487 case tok::kw_double:
488 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
489 break;
490 case tok::kw_bool: // [C++ 2.11p1]
491 case tok::kw__Bool:
492 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
493 break;
494 case tok::kw__Decimal32:
495 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
496 break;
497 case tok::kw__Decimal64:
498 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
499 break;
500 case tok::kw__Decimal128:
501 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
502 break;
503
504 case tok::kw_struct:
505 case tok::kw_union:
506 ParseStructUnionSpecifier(DS);
507 continue;
508 case tok::kw_enum:
509 ParseEnumSpecifier(DS);
510 continue;
511
Steve Naroff7cbb1462007-07-31 12:34:36 +0000512 // GNU typeof support.
513 case tok::kw_typeof:
514 ParseTypeofSpecifier(DS);
515 continue;
516
Chris Lattner4b009652007-07-25 00:24:17 +0000517 // type-qualifier
518 case tok::kw_const:
519 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
520 getLang())*2;
521 break;
522 case tok::kw_volatile:
523 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
524 getLang())*2;
525 break;
526 case tok::kw_restrict:
527 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
528 getLang())*2;
529 break;
530
531 // function-specifier
532 case tok::kw_inline:
533 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
534 break;
535 }
536 // If the specifier combination wasn't legal, issue a diagnostic.
537 if (isInvalid) {
538 assert(PrevSpec && "Method did not return previous specifier!");
539 if (isInvalid == 1) // Error.
540 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
541 else // extwarn.
542 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
543 }
544 DS.Range.setEnd(Tok.getLocation());
545 ConsumeToken();
546 }
547}
548
549/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
550/// the first token has already been read and has been turned into an instance
551/// of DeclSpec::TST (TagType). This returns true if there is an error parsing,
552/// otherwise it returns false and fills in Decl.
553bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
554 AttributeList *Attr = 0;
555 // If attributes exist after tag, parse them.
556 if (Tok.getKind() == tok::kw___attribute)
557 Attr = ParseAttributes();
558
559 // Must have either 'struct name' or 'struct {...}'.
560 if (Tok.getKind() != tok::identifier &&
561 Tok.getKind() != tok::l_brace) {
562 Diag(Tok, diag::err_expected_ident_lbrace);
563
564 // Skip the rest of this declarator, up until the comma or semicolon.
565 SkipUntil(tok::comma, true);
566 return true;
567 }
568
569 // If an identifier is present, consume and remember it.
570 IdentifierInfo *Name = 0;
571 SourceLocation NameLoc;
572 if (Tok.getKind() == tok::identifier) {
573 Name = Tok.getIdentifierInfo();
574 NameLoc = ConsumeToken();
575 }
576
577 // There are three options here. If we have 'struct foo;', then this is a
578 // forward declaration. If we have 'struct foo {...' then this is a
579 // definition. Otherwise we have something like 'struct foo xyz', a reference.
580 //
581 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
582 // struct foo {..}; void bar() { struct foo; } <- new foo in bar.
583 // struct foo {..}; void bar() { struct foo x; } <- use of old foo.
584 //
585 Action::TagKind TK;
586 if (Tok.getKind() == tok::l_brace)
587 TK = Action::TK_Definition;
588 else if (Tok.getKind() == tok::semi)
589 TK = Action::TK_Declaration;
590 else
591 TK = Action::TK_Reference;
Steve Naroff0acc9c92007-09-15 18:49:24 +0000592 Decl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +0000593 return false;
594}
595
596
597/// ParseStructUnionSpecifier
598/// struct-or-union-specifier: [C99 6.7.2.1]
599/// struct-or-union identifier[opt] '{' struct-contents '}'
600/// struct-or-union identifier
601/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
602/// '}' attributes[opt]
603/// [GNU] struct-or-union attributes[opt] identifier
604/// struct-or-union:
605/// 'struct'
606/// 'union'
607///
608void Parser::ParseStructUnionSpecifier(DeclSpec &DS) {
609 assert((Tok.getKind() == tok::kw_struct ||
610 Tok.getKind() == tok::kw_union) && "Not a struct/union specifier");
611 DeclSpec::TST TagType =
612 Tok.getKind() == tok::kw_union ? DeclSpec::TST_union : DeclSpec::TST_struct;
613 SourceLocation StartLoc = ConsumeToken();
614
615 // Parse the tag portion of this.
616 DeclTy *TagDecl;
617 if (ParseTag(TagDecl, TagType, StartLoc))
618 return;
619
620 // If there is a body, parse it and inform the actions module.
621 if (Tok.getKind() == tok::l_brace)
622 ParseStructUnionBody(StartLoc, TagType, TagDecl);
623
624 const char *PrevSpec = 0;
625 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
626 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
627}
628
Steve Naroffa9adf112007-08-20 22:28:22 +0000629/// ParseStructDeclaration
Chris Lattner4b009652007-07-25 00:24:17 +0000630/// struct-declaration:
631/// specifier-qualifier-list struct-declarator-list ';'
632/// [GNU] __extension__ struct-declaration
633/// [GNU] specifier-qualifier-list ';'
634/// struct-declarator-list:
635/// struct-declarator
636/// struct-declarator-list ',' struct-declarator
637/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
638/// struct-declarator:
639/// declarator
640/// [GNU] declarator attributes[opt]
641/// declarator[opt] ':' constant-expression
642/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
643///
Steve Naroffa9adf112007-08-20 22:28:22 +0000644void Parser::ParseStructDeclaration(DeclTy *TagDecl,
Steve Naroffc02f4a92007-08-28 16:31:47 +0000645 llvm::SmallVectorImpl<DeclTy*> &FieldDecls) {
Steve Naroffa9adf112007-08-20 22:28:22 +0000646 // FIXME: When __extension__ is specified, disable extension diagnostics.
647 if (Tok.getKind() == tok::kw___extension__)
648 ConsumeToken();
649
650 // Parse the common specifier-qualifiers-list piece.
651 DeclSpec DS;
652 SourceLocation SpecQualLoc = Tok.getLocation();
653 ParseSpecifierQualifierList(DS);
654 // TODO: Does specifier-qualifier list correctly check that *something* is
655 // specified?
656
657 // If there are no declarators, issue a warning.
658 if (Tok.getKind() == tok::semi) {
659 Diag(SpecQualLoc, diag::w_no_declarators);
660 ConsumeToken();
661 return;
662 }
663
664 // Read struct-declarators until we find the semicolon.
665 Declarator DeclaratorInfo(DS, Declarator::MemberContext);
666
667 while (1) {
668 /// struct-declarator: declarator
669 /// struct-declarator: declarator[opt] ':' constant-expression
670 if (Tok.getKind() != tok::colon)
671 ParseDeclarator(DeclaratorInfo);
672
673 ExprTy *BitfieldSize = 0;
674 if (Tok.getKind() == tok::colon) {
675 ConsumeToken();
676 ExprResult Res = ParseConstantExpression();
677 if (Res.isInvalid) {
678 SkipUntil(tok::semi, true, true);
679 } else {
680 BitfieldSize = Res.Val;
681 }
682 }
683
684 // If attributes exist after the declarator, parse them.
685 if (Tok.getKind() == tok::kw___attribute)
686 DeclaratorInfo.AddAttributes(ParseAttributes());
687
688 // Install the declarator into the current TagDecl.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000689 DeclTy *Field = Actions.ActOnField(CurScope, TagDecl, SpecQualLoc,
Steve Naroffa9adf112007-08-20 22:28:22 +0000690 DeclaratorInfo, BitfieldSize);
691 FieldDecls.push_back(Field);
692
693 // If we don't have a comma, it is either the end of the list (a ';')
694 // or an error, bail out.
695 if (Tok.getKind() != tok::comma)
696 break;
697
698 // Consume the comma.
699 ConsumeToken();
700
701 // Parse the next declarator.
702 DeclaratorInfo.clear();
703
704 // Attributes are only allowed on the second declarator.
705 if (Tok.getKind() == tok::kw___attribute)
706 DeclaratorInfo.AddAttributes(ParseAttributes());
707 }
708 return;
709}
710
711/// ParseStructUnionBody
712/// struct-contents:
713/// struct-declaration-list
714/// [EXT] empty
715/// [GNU] "struct-declaration-list" without terminatoring ';'
716/// struct-declaration-list:
717/// struct-declaration
718/// struct-declaration-list struct-declaration
719/// [OBC] '@' 'defs' '(' class-name ')' [TODO]
720///
Chris Lattner4b009652007-07-25 00:24:17 +0000721void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
722 unsigned TagType, DeclTy *TagDecl) {
723 SourceLocation LBraceLoc = ConsumeBrace();
724
725 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
726 // C++.
727 if (Tok.getKind() == tok::r_brace)
728 Diag(Tok, diag::ext_empty_struct_union_enum,
729 DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
730
731 llvm::SmallVector<DeclTy*, 32> FieldDecls;
732
733 // While we still have something to read, read the declarations in the struct.
734 while (Tok.getKind() != tok::r_brace &&
735 Tok.getKind() != tok::eof) {
736 // Each iteration of this loop reads one struct-declaration.
737
738 // Check for extraneous top-level semicolon.
739 if (Tok.getKind() == tok::semi) {
740 Diag(Tok, diag::ext_extra_struct_semi);
741 ConsumeToken();
742 continue;
743 }
Steve Naroffa9adf112007-08-20 22:28:22 +0000744 ParseStructDeclaration(TagDecl, FieldDecls);
Chris Lattner4b009652007-07-25 00:24:17 +0000745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 if (Tok.getKind() == tok::semi) {
747 ConsumeToken();
748 } else if (Tok.getKind() == tok::r_brace) {
749 Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
750 break;
751 } else {
752 Diag(Tok, diag::err_expected_semi_decl_list);
753 // Skip to end of block or statement
754 SkipUntil(tok::r_brace, true, true);
755 }
756 }
757
758 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
759
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000760 Actions.ActOnFields(CurScope,
761 RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000762
763 AttributeList *AttrList = 0;
764 // If attributes exist after struct contents, parse them.
765 if (Tok.getKind() == tok::kw___attribute)
766 AttrList = ParseAttributes(); // FIXME: where should I put them?
767}
768
769
770/// ParseEnumSpecifier
771/// enum-specifier: [C99 6.7.2.2]
772/// 'enum' identifier[opt] '{' enumerator-list '}'
773/// [C99] 'enum' identifier[opt] '{' enumerator-list ',' '}'
774/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
775/// '}' attributes[opt]
776/// 'enum' identifier
777/// [GNU] 'enum' attributes[opt] identifier
778void Parser::ParseEnumSpecifier(DeclSpec &DS) {
779 assert(Tok.getKind() == tok::kw_enum && "Not an enum specifier");
780 SourceLocation StartLoc = ConsumeToken();
781
782 // Parse the tag portion of this.
783 DeclTy *TagDecl;
784 if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
785 return;
786
787 if (Tok.getKind() == tok::l_brace)
788 ParseEnumBody(StartLoc, TagDecl);
789
790 // TODO: semantic analysis on the declspec for enums.
791 const char *PrevSpec = 0;
792 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
793 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
794}
795
796/// ParseEnumBody - Parse a {} enclosed enumerator-list.
797/// enumerator-list:
798/// enumerator
799/// enumerator-list ',' enumerator
800/// enumerator:
801/// enumeration-constant
802/// enumeration-constant '=' constant-expression
803/// enumeration-constant:
804/// identifier
805///
806void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
807 SourceLocation LBraceLoc = ConsumeBrace();
808
Chris Lattnerc9a92452007-08-27 17:24:30 +0000809 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
810 if (Tok.getKind() == tok::r_brace && !getLang().CPlusPlus)
Chris Lattner4b009652007-07-25 00:24:17 +0000811 Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
812
813 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
814
815 DeclTy *LastEnumConstDecl = 0;
816
817 // Parse the enumerator-list.
818 while (Tok.getKind() == tok::identifier) {
819 IdentifierInfo *Ident = Tok.getIdentifierInfo();
820 SourceLocation IdentLoc = ConsumeToken();
821
822 SourceLocation EqualLoc;
823 ExprTy *AssignedVal = 0;
824 if (Tok.getKind() == tok::equal) {
825 EqualLoc = ConsumeToken();
826 ExprResult Res = ParseConstantExpression();
827 if (Res.isInvalid)
828 SkipUntil(tok::comma, tok::r_brace, true, true);
829 else
830 AssignedVal = Res.Val;
831 }
832
833 // Install the enumerator constant into EnumDecl.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000834 DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +0000835 LastEnumConstDecl,
836 IdentLoc, Ident,
837 EqualLoc, AssignedVal);
838 EnumConstantDecls.push_back(EnumConstDecl);
839 LastEnumConstDecl = EnumConstDecl;
840
841 if (Tok.getKind() != tok::comma)
842 break;
843 SourceLocation CommaLoc = ConsumeToken();
844
845 if (Tok.getKind() != tok::identifier && !getLang().C99)
846 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
847 }
848
849 // Eat the }.
850 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
851
Steve Naroff0acc9c92007-09-15 18:49:24 +0000852 Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
Chris Lattner4b009652007-07-25 00:24:17 +0000853 EnumConstantDecls.size());
854
855 DeclTy *AttrList = 0;
856 // If attributes exist after the identifier list, parse them.
857 if (Tok.getKind() == tok::kw___attribute)
858 AttrList = ParseAttributes(); // FIXME: where do they do?
859}
860
861/// isTypeSpecifierQualifier - Return true if the current token could be the
862/// start of a specifier-qualifier-list.
863bool Parser::isTypeSpecifierQualifier() const {
864 switch (Tok.getKind()) {
865 default: return false;
866 // GNU attributes support.
867 case tok::kw___attribute:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000868 // GNU typeof support.
869 case tok::kw_typeof:
870
Chris Lattner4b009652007-07-25 00:24:17 +0000871 // type-specifiers
872 case tok::kw_short:
873 case tok::kw_long:
874 case tok::kw_signed:
875 case tok::kw_unsigned:
876 case tok::kw__Complex:
877 case tok::kw__Imaginary:
878 case tok::kw_void:
879 case tok::kw_char:
880 case tok::kw_int:
881 case tok::kw_float:
882 case tok::kw_double:
883 case tok::kw__Bool:
884 case tok::kw__Decimal32:
885 case tok::kw__Decimal64:
886 case tok::kw__Decimal128:
887
888 // struct-or-union-specifier
889 case tok::kw_struct:
890 case tok::kw_union:
891 // enum-specifier
892 case tok::kw_enum:
893
894 // type-qualifier
895 case tok::kw_const:
896 case tok::kw_volatile:
897 case tok::kw_restrict:
898 return true;
899
900 // typedef-name
901 case tok::identifier:
902 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000903 }
904}
905
906/// isDeclarationSpecifier() - Return true if the current token is part of a
907/// declaration specifier.
908bool Parser::isDeclarationSpecifier() const {
909 switch (Tok.getKind()) {
910 default: return false;
911 // storage-class-specifier
912 case tok::kw_typedef:
913 case tok::kw_extern:
914 case tok::kw_static:
915 case tok::kw_auto:
916 case tok::kw_register:
917 case tok::kw___thread:
918
919 // type-specifiers
920 case tok::kw_short:
921 case tok::kw_long:
922 case tok::kw_signed:
923 case tok::kw_unsigned:
924 case tok::kw__Complex:
925 case tok::kw__Imaginary:
926 case tok::kw_void:
927 case tok::kw_char:
928 case tok::kw_int:
929 case tok::kw_float:
930 case tok::kw_double:
931 case tok::kw__Bool:
932 case tok::kw__Decimal32:
933 case tok::kw__Decimal64:
934 case tok::kw__Decimal128:
935
936 // struct-or-union-specifier
937 case tok::kw_struct:
938 case tok::kw_union:
939 // enum-specifier
940 case tok::kw_enum:
941
942 // type-qualifier
943 case tok::kw_const:
944 case tok::kw_volatile:
945 case tok::kw_restrict:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000946
Chris Lattner4b009652007-07-25 00:24:17 +0000947 // function-specifier
948 case tok::kw_inline:
Chris Lattnere35d2582007-08-09 16:40:21 +0000949
Chris Lattnerb707a7a2007-08-09 17:01:07 +0000950 // GNU typeof support.
951 case tok::kw_typeof:
952
953 // GNU attributes.
Chris Lattnere35d2582007-08-09 16:40:21 +0000954 case tok::kw___attribute:
Chris Lattner4b009652007-07-25 00:24:17 +0000955 return true;
956
957 // typedef-name
958 case tok::identifier:
959 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000960 }
961}
962
963
964/// ParseTypeQualifierListOpt
965/// type-qualifier-list: [C99 6.7.5]
966/// type-qualifier
967/// [GNU] attributes
968/// type-qualifier-list type-qualifier
969/// [GNU] type-qualifier-list attributes
970///
971void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
972 while (1) {
973 int isInvalid = false;
974 const char *PrevSpec = 0;
975 SourceLocation Loc = Tok.getLocation();
976
977 switch (Tok.getKind()) {
978 default:
979 // If this is not a type-qualifier token, we're done reading type
980 // qualifiers. First verify that DeclSpec's are consistent.
981 DS.Finish(Diags, getLang());
982 return;
983 case tok::kw_const:
984 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
985 getLang())*2;
986 break;
987 case tok::kw_volatile:
988 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
989 getLang())*2;
990 break;
991 case tok::kw_restrict:
992 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
993 getLang())*2;
994 break;
995 case tok::kw___attribute:
996 DS.AddAttributes(ParseAttributes());
997 continue; // do *not* consume the next token!
998 }
999
1000 // If the specifier combination wasn't legal, issue a diagnostic.
1001 if (isInvalid) {
1002 assert(PrevSpec && "Method did not return previous specifier!");
1003 if (isInvalid == 1) // Error.
1004 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
1005 else // extwarn.
1006 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
1007 }
1008 ConsumeToken();
1009 }
1010}
1011
1012
1013/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1014///
1015void Parser::ParseDeclarator(Declarator &D) {
1016 /// This implements the 'declarator' production in the C grammar, then checks
1017 /// for well-formedness and issues diagnostics.
1018 ParseDeclaratorInternal(D);
1019
1020 // TODO: validate D.
1021
1022}
1023
1024/// ParseDeclaratorInternal
1025/// declarator: [C99 6.7.5]
1026/// pointer[opt] direct-declarator
1027/// [C++] '&' declarator [C++ 8p4, dcl.decl]
1028/// [GNU] '&' restrict[opt] attributes[opt] declarator
1029///
1030/// pointer: [C99 6.7.5]
1031/// '*' type-qualifier-list[opt]
1032/// '*' type-qualifier-list[opt] pointer
1033///
1034void Parser::ParseDeclaratorInternal(Declarator &D) {
1035 tok::TokenKind Kind = Tok.getKind();
1036
1037 // Not a pointer or C++ reference.
1038 if (Kind != tok::star && !(Kind == tok::amp && getLang().CPlusPlus))
1039 return ParseDirectDeclarator(D);
1040
1041 // Otherwise, '*' -> pointer or '&' -> reference.
1042 SourceLocation Loc = ConsumeToken(); // Eat the * or &.
1043
1044 if (Kind == tok::star) {
1045 // Is a pointer
1046 DeclSpec DS;
1047
1048 ParseTypeQualifierListOpt(DS);
1049
1050 // Recursively parse the declarator.
1051 ParseDeclaratorInternal(D);
1052
1053 // Remember that we parsed a pointer type, and remember the type-quals.
1054 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc));
1055 } else {
1056 // Is a reference
1057 DeclSpec DS;
1058
1059 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1060 // cv-qualifiers are introduced through the use of a typedef or of a
1061 // template type argument, in which case the cv-qualifiers are ignored.
1062 //
1063 // [GNU] Retricted references are allowed.
1064 // [GNU] Attributes on references are allowed.
1065 ParseTypeQualifierListOpt(DS);
1066
1067 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1068 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1069 Diag(DS.getConstSpecLoc(),
1070 diag::err_invalid_reference_qualifier_application,
1071 "const");
1072 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1073 Diag(DS.getVolatileSpecLoc(),
1074 diag::err_invalid_reference_qualifier_application,
1075 "volatile");
1076 }
1077
1078 // Recursively parse the declarator.
1079 ParseDeclaratorInternal(D);
1080
1081 // Remember that we parsed a reference type. It doesn't have type-quals.
1082 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc));
1083 }
1084}
1085
1086/// ParseDirectDeclarator
1087/// direct-declarator: [C99 6.7.5]
1088/// identifier
1089/// '(' declarator ')'
1090/// [GNU] '(' attributes declarator ')'
1091/// [C90] direct-declarator '[' constant-expression[opt] ']'
1092/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1093/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1094/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1095/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1096/// direct-declarator '(' parameter-type-list ')'
1097/// direct-declarator '(' identifier-list[opt] ')'
1098/// [GNU] direct-declarator '(' parameter-forward-declarations
1099/// parameter-type-list[opt] ')'
1100///
1101void Parser::ParseDirectDeclarator(Declarator &D) {
1102 // Parse the first direct-declarator seen.
1103 if (Tok.getKind() == tok::identifier && D.mayHaveIdentifier()) {
1104 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1105 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1106 ConsumeToken();
1107 } else if (Tok.getKind() == tok::l_paren) {
1108 // direct-declarator: '(' declarator ')'
1109 // direct-declarator: '(' attributes declarator ')'
1110 // Example: 'char (*X)' or 'int (*XX)(void)'
1111 ParseParenDeclarator(D);
1112 } else if (D.mayOmitIdentifier()) {
1113 // This could be something simple like "int" (in which case the declarator
1114 // portion is empty), if an abstract-declarator is allowed.
1115 D.SetIdentifier(0, Tok.getLocation());
1116 } else {
1117 // Expected identifier or '('.
1118 Diag(Tok, diag::err_expected_ident_lparen);
1119 D.SetIdentifier(0, Tok.getLocation());
1120 }
1121
1122 assert(D.isPastIdentifier() &&
1123 "Haven't past the location of the identifier yet?");
1124
1125 while (1) {
1126 if (Tok.getKind() == tok::l_paren) {
1127 ParseParenDeclarator(D);
1128 } else if (Tok.getKind() == tok::l_square) {
1129 ParseBracketDeclarator(D);
1130 } else {
1131 break;
1132 }
1133 }
1134}
1135
1136/// ParseParenDeclarator - We parsed the declarator D up to a paren. This may
1137/// either be before the identifier (in which case these are just grouping
1138/// parens for precedence) or it may be after the identifier, in which case
1139/// these are function arguments.
1140///
1141/// This method also handles this portion of the grammar:
1142/// parameter-type-list: [C99 6.7.5]
1143/// parameter-list
1144/// parameter-list ',' '...'
1145///
1146/// parameter-list: [C99 6.7.5]
1147/// parameter-declaration
1148/// parameter-list ',' parameter-declaration
1149///
1150/// parameter-declaration: [C99 6.7.5]
1151/// declaration-specifiers declarator
1152/// [GNU] declaration-specifiers declarator attributes
1153/// declaration-specifiers abstract-declarator[opt]
1154/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
1155///
1156/// identifier-list: [C99 6.7.5]
1157/// identifier
1158/// identifier-list ',' identifier
1159///
1160void Parser::ParseParenDeclarator(Declarator &D) {
1161 SourceLocation StartLoc = ConsumeParen();
1162
1163 // If we haven't past the identifier yet (or where the identifier would be
1164 // stored, if this is an abstract declarator), then this is probably just
1165 // grouping parens.
1166 if (!D.isPastIdentifier()) {
1167 // Okay, this is probably a grouping paren. However, if this could be an
1168 // abstract-declarator, then this could also be the start of function
1169 // arguments (consider 'void()').
1170 bool isGrouping;
1171
1172 if (!D.mayOmitIdentifier()) {
1173 // If this can't be an abstract-declarator, this *must* be a grouping
1174 // paren, because we haven't seen the identifier yet.
1175 isGrouping = true;
1176 } else if (Tok.getKind() == tok::r_paren || // 'int()' is a function.
1177 isDeclarationSpecifier()) { // 'int(int)' is a function.
1178 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1179 // considered to be a type, not a K&R identifier-list.
1180 isGrouping = false;
1181 } else {
1182 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1183 isGrouping = true;
1184 }
1185
1186 // If this is a grouping paren, handle:
1187 // direct-declarator: '(' declarator ')'
1188 // direct-declarator: '(' attributes declarator ')'
1189 if (isGrouping) {
1190 if (Tok.getKind() == tok::kw___attribute)
1191 D.AddAttributes(ParseAttributes());
1192
1193 ParseDeclaratorInternal(D);
1194 // Match the ')'.
1195 MatchRHSPunctuation(tok::r_paren, StartLoc);
1196 return;
1197 }
1198
1199 // Okay, if this wasn't a grouping paren, it must be the start of a function
1200 // argument list. Recognize that this declarator will never have an
1201 // identifier (and remember where it would have been), then fall through to
1202 // the handling of argument lists.
1203 D.SetIdentifier(0, Tok.getLocation());
1204 }
1205
1206 // Okay, this is the parameter list of a function definition, or it is an
1207 // identifier list of a K&R-style function.
1208 bool IsVariadic;
1209 bool HasPrototype;
1210 bool ErrorEmitted = false;
1211
1212 // Build up an array of information about the parsed arguments.
1213 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1214 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1215
1216 if (Tok.getKind() == tok::r_paren) {
1217 // int() -> no prototype, no '...'.
1218 IsVariadic = false;
1219 HasPrototype = false;
1220 } else if (Tok.getKind() == tok::identifier &&
1221 // K&R identifier lists can't have typedefs as identifiers, per
1222 // C99 6.7.5.3p11.
1223 !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1224 // Identifier list. Note that '(' identifier-list ')' is only allowed for
1225 // normal declarators, not for abstract-declarators.
1226 assert(D.isPastIdentifier() && "Identifier (if present) must be passed!");
1227
1228 // If there was no identifier specified, either we are in an
1229 // abstract-declarator, or we are in a parameter declarator which was found
1230 // to be abstract. In abstract-declarators, identifier lists are not valid,
1231 // diagnose this.
1232 if (!D.getIdentifier())
1233 Diag(Tok, diag::ext_ident_list_in_param);
1234
1235 // Remember this identifier in ParamInfo.
1236 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1237 Tok.getLocation(), 0));
1238
1239 ConsumeToken();
1240 while (Tok.getKind() == tok::comma) {
1241 // Eat the comma.
1242 ConsumeToken();
1243
1244 if (Tok.getKind() != tok::identifier) {
1245 Diag(Tok, diag::err_expected_ident);
1246 ErrorEmitted = true;
1247 break;
1248 }
1249
1250 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1251
1252 // Verify that the argument identifier has not already been mentioned.
1253 if (!ParamsSoFar.insert(ParmII)) {
1254 Diag(Tok.getLocation(), diag::err_param_redefinition,ParmII->getName());
1255 ParmII = 0;
1256 }
1257
1258 // Remember this identifier in ParamInfo.
1259 if (ParmII)
1260 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1261 Tok.getLocation(), 0));
1262
1263 // Eat the identifier.
1264 ConsumeToken();
1265 }
1266
1267 // K&R 'prototype'.
1268 IsVariadic = false;
1269 HasPrototype = false;
1270 } else {
1271 // Finally, a normal, non-empty parameter type list.
1272
1273 // Enter function-declaration scope, limiting any declarators for struct
1274 // tags to the function prototype scope.
1275 // FIXME: is this needed?
Chris Lattnera7549902007-08-26 06:24:45 +00001276 EnterScope(Scope::DeclScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001277
1278 IsVariadic = false;
1279 while (1) {
1280 if (Tok.getKind() == tok::ellipsis) {
1281 IsVariadic = true;
1282
1283 // Check to see if this is "void(...)" which is not allowed.
1284 if (ParamInfo.empty()) {
1285 // Otherwise, parse parameter type list. If it starts with an
1286 // ellipsis, diagnose the malformed function.
1287 Diag(Tok, diag::err_ellipsis_first_arg);
1288 IsVariadic = false; // Treat this like 'void()'.
1289 }
1290
1291 // Consume the ellipsis.
1292 ConsumeToken();
1293 break;
1294 }
1295
1296 // Parse the declaration-specifiers.
1297 DeclSpec DS;
1298 ParseDeclarationSpecifiers(DS);
1299
1300 // Parse the declarator. This is "PrototypeContext", because we must
1301 // accept either 'declarator' or 'abstract-declarator' here.
1302 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1303 ParseDeclarator(ParmDecl);
1304
1305 // Parse GNU attributes, if present.
1306 if (Tok.getKind() == tok::kw___attribute)
1307 ParmDecl.AddAttributes(ParseAttributes());
1308
1309 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1310 // NOTE: we could trivially allow 'int foo(auto int X)' if we wanted.
1311 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1312 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1313 Diag(DS.getStorageClassSpecLoc(),
1314 diag::err_invalid_storage_class_in_func_decl);
1315 DS.ClearStorageClassSpecs();
1316 }
1317 if (DS.isThreadSpecified()) {
1318 Diag(DS.getThreadSpecLoc(),
1319 diag::err_invalid_storage_class_in_func_decl);
1320 DS.ClearStorageClassSpecs();
1321 }
1322
1323 // Inform the actions module about the parameter declarator, so it gets
1324 // added to the current scope.
1325 Action::TypeResult ParamTy =
Steve Naroff0acc9c92007-09-15 18:49:24 +00001326 Actions.ActOnParamDeclaratorType(CurScope, ParmDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001327
1328 // Remember this parsed parameter in ParamInfo.
1329 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1330
1331 // Verify that the argument identifier has not already been mentioned.
1332 if (ParmII && !ParamsSoFar.insert(ParmII)) {
1333 Diag(ParmDecl.getIdentifierLoc(), diag::err_param_redefinition,
1334 ParmII->getName());
1335 ParmII = 0;
1336 }
1337
Steve Naroff91b03f72007-08-28 03:03:08 +00001338 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1339 ParmDecl.getIdentifierLoc(), ParamTy.Val, ParmDecl.getInvalidType()));
Chris Lattner4b009652007-07-25 00:24:17 +00001340
1341 // If the next token is a comma, consume it and keep reading arguments.
1342 if (Tok.getKind() != tok::comma) break;
1343
1344 // Consume the comma.
1345 ConsumeToken();
1346 }
1347
1348 HasPrototype = true;
1349
1350 // Leave prototype scope.
1351 ExitScope();
1352 }
1353
1354 // Remember that we parsed a function type, and remember the attributes.
1355 if (!ErrorEmitted)
1356 D.AddTypeInfo(DeclaratorChunk::getFunction(HasPrototype, IsVariadic,
1357 &ParamInfo[0], ParamInfo.size(),
1358 StartLoc));
1359
1360 // If we have the closing ')', eat it and we're done.
1361 if (Tok.getKind() == tok::r_paren) {
1362 ConsumeParen();
1363 } else {
1364 // If an error happened earlier parsing something else in the proto, don't
1365 // issue another error.
1366 if (!ErrorEmitted)
1367 Diag(Tok, diag::err_expected_rparen);
1368 SkipUntil(tok::r_paren);
1369 }
1370}
1371
1372
1373/// [C90] direct-declarator '[' constant-expression[opt] ']'
1374/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1375/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1376/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1377/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1378void Parser::ParseBracketDeclarator(Declarator &D) {
1379 SourceLocation StartLoc = ConsumeBracket();
1380
1381 // If valid, this location is the position where we read the 'static' keyword.
1382 SourceLocation StaticLoc;
1383 if (Tok.getKind() == tok::kw_static)
1384 StaticLoc = ConsumeToken();
1385
1386 // If there is a type-qualifier-list, read it now.
1387 DeclSpec DS;
1388 ParseTypeQualifierListOpt(DS);
1389
1390 // If we haven't already read 'static', check to see if there is one after the
1391 // type-qualifier-list.
1392 if (!StaticLoc.isValid() && Tok.getKind() == tok::kw_static)
1393 StaticLoc = ConsumeToken();
1394
1395 // Handle "direct-declarator [ type-qual-list[opt] * ]".
1396 bool isStar = false;
1397 ExprResult NumElements(false);
1398 if (Tok.getKind() == tok::star) {
1399 // Remember the '*' token, in case we have to un-get it.
1400 Token StarTok = Tok;
1401 ConsumeToken();
1402
1403 // Check that the ']' token is present to avoid incorrectly parsing
1404 // expressions starting with '*' as [*].
1405 if (Tok.getKind() == tok::r_square) {
1406 if (StaticLoc.isValid())
1407 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1408 StaticLoc = SourceLocation(); // Drop the static.
1409 isStar = true;
1410 } else {
1411 // Otherwise, the * must have been some expression (such as '*ptr') that
1412 // started an assignment-expr. We already consumed the token, but now we
1413 // need to reparse it. This handles cases like 'X[*p + 4]'
1414 NumElements = ParseAssignmentExpressionWithLeadingStar(StarTok);
1415 }
1416 } else if (Tok.getKind() != tok::r_square) {
1417 // Parse the assignment-expression now.
1418 NumElements = ParseAssignmentExpression();
1419 }
1420
1421 // If there was an error parsing the assignment-expression, recover.
1422 if (NumElements.isInvalid) {
1423 // If the expression was invalid, skip it.
1424 SkipUntil(tok::r_square);
1425 return;
1426 }
1427
1428 MatchRHSPunctuation(tok::r_square, StartLoc);
1429
1430 // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1431 // it was not a constant expression.
1432 if (!getLang().C99) {
1433 // TODO: check C90 array constant exprness.
1434 if (isStar || StaticLoc.isValid() ||
1435 0/*TODO: NumElts is not a C90 constantexpr */)
1436 Diag(StartLoc, diag::ext_c99_array_usage);
1437 }
1438
1439 // Remember that we parsed a pointer type, and remember the type-quals.
1440 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1441 StaticLoc.isValid(), isStar,
1442 NumElements.Val, StartLoc));
1443}
1444
Steve Naroff7cbb1462007-07-31 12:34:36 +00001445/// [GNU] typeof-specifier:
1446/// typeof ( expressions )
1447/// typeof ( type-name )
1448///
1449void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1450 assert(Tok.getKind() == tok::kw_typeof && "Not a typeof specifier");
Steve Naroff14bbce82007-08-02 02:53:48 +00001451 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
Steve Naroff7cbb1462007-07-31 12:34:36 +00001452 SourceLocation StartLoc = ConsumeToken();
1453
1454 if (Tok.getKind() != tok::l_paren) {
Steve Naroff14bbce82007-08-02 02:53:48 +00001455 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
1456 return;
Steve Naroff7cbb1462007-07-31 12:34:36 +00001457 }
1458 SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
1459
1460 if (isTypeSpecifierQualifier()) {
1461 TypeTy *Ty = ParseTypeName();
1462
Steve Naroff4c255ab2007-07-31 23:56:32 +00001463 assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
1464
Steve Naroff14bbce82007-08-02 02:53:48 +00001465 if (Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001466 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001467 return;
1468 }
1469 RParenLoc = ConsumeParen();
1470 const char *PrevSpec = 0;
1471 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1472 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
1473 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001474 } else { // we have an expression.
1475 ExprResult Result = ParseExpression();
Steve Naroff4c255ab2007-07-31 23:56:32 +00001476
Steve Naroff14bbce82007-08-02 02:53:48 +00001477 if (Result.isInvalid || Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001478 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001479 return;
1480 }
1481 RParenLoc = ConsumeParen();
1482 const char *PrevSpec = 0;
1483 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1484 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1485 Result.Val))
1486 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001487 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001488}
1489