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