blob: 8bdcd4e652ac405270d8464cc9e54c3b21231d9f [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);
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +0000412 Actions.ActOnFindProtocolDeclaration(CurScope,
413 Loc,
414 &ProtocolRefs[0],
415 ProtocolRefs.size());
Steve Naroff304ed392007-09-05 23:30:30 +0000416 }
Steve Naroffa8ee2262007-08-22 23:18:22 +0000417 continue;
418 }
Chris Lattner4b009652007-07-25 00:24:17 +0000419 }
420 }
421 // FALL THROUGH.
422 default:
423 // If this is not a declaration specifier token, we're done reading decl
424 // specifiers. First verify that DeclSpec's are consistent.
425 DS.Finish(Diags, getLang());
426 return;
427
428 // GNU attributes support.
429 case tok::kw___attribute:
430 DS.AddAttributes(ParseAttributes());
431 continue;
432
433 // storage-class-specifier
434 case tok::kw_typedef:
435 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
436 break;
437 case tok::kw_extern:
438 if (DS.isThreadSpecified())
439 Diag(Tok, diag::ext_thread_before, "extern");
440 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
441 break;
442 case tok::kw_static:
443 if (DS.isThreadSpecified())
444 Diag(Tok, diag::ext_thread_before, "static");
445 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
446 break;
447 case tok::kw_auto:
448 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
449 break;
450 case tok::kw_register:
451 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
452 break;
453 case tok::kw___thread:
454 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
455 break;
456
457 // type-specifiers
458 case tok::kw_short:
459 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
460 break;
461 case tok::kw_long:
462 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
463 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
464 else
465 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
466 break;
467 case tok::kw_signed:
468 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
469 break;
470 case tok::kw_unsigned:
471 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
472 break;
473 case tok::kw__Complex:
474 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
475 break;
476 case tok::kw__Imaginary:
477 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
478 break;
479 case tok::kw_void:
480 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
481 break;
482 case tok::kw_char:
483 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
484 break;
485 case tok::kw_int:
486 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
487 break;
488 case tok::kw_float:
489 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
490 break;
491 case tok::kw_double:
492 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
493 break;
494 case tok::kw_bool: // [C++ 2.11p1]
495 case tok::kw__Bool:
496 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
497 break;
498 case tok::kw__Decimal32:
499 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
500 break;
501 case tok::kw__Decimal64:
502 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
503 break;
504 case tok::kw__Decimal128:
505 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
506 break;
507
508 case tok::kw_struct:
509 case tok::kw_union:
510 ParseStructUnionSpecifier(DS);
511 continue;
512 case tok::kw_enum:
513 ParseEnumSpecifier(DS);
514 continue;
515
Steve Naroff7cbb1462007-07-31 12:34:36 +0000516 // GNU typeof support.
517 case tok::kw_typeof:
518 ParseTypeofSpecifier(DS);
519 continue;
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 // type-qualifier
522 case tok::kw_const:
523 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
524 getLang())*2;
525 break;
526 case tok::kw_volatile:
527 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
528 getLang())*2;
529 break;
530 case tok::kw_restrict:
531 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
532 getLang())*2;
533 break;
534
535 // function-specifier
536 case tok::kw_inline:
537 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
538 break;
539 }
540 // If the specifier combination wasn't legal, issue a diagnostic.
541 if (isInvalid) {
542 assert(PrevSpec && "Method did not return previous specifier!");
543 if (isInvalid == 1) // Error.
544 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
545 else // extwarn.
546 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
547 }
548 DS.Range.setEnd(Tok.getLocation());
549 ConsumeToken();
550 }
551}
552
553/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
554/// the first token has already been read and has been turned into an instance
555/// of DeclSpec::TST (TagType). This returns true if there is an error parsing,
556/// otherwise it returns false and fills in Decl.
557bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
558 AttributeList *Attr = 0;
559 // If attributes exist after tag, parse them.
560 if (Tok.getKind() == tok::kw___attribute)
561 Attr = ParseAttributes();
562
563 // Must have either 'struct name' or 'struct {...}'.
564 if (Tok.getKind() != tok::identifier &&
565 Tok.getKind() != tok::l_brace) {
566 Diag(Tok, diag::err_expected_ident_lbrace);
567
568 // Skip the rest of this declarator, up until the comma or semicolon.
569 SkipUntil(tok::comma, true);
570 return true;
571 }
572
573 // If an identifier is present, consume and remember it.
574 IdentifierInfo *Name = 0;
575 SourceLocation NameLoc;
576 if (Tok.getKind() == tok::identifier) {
577 Name = Tok.getIdentifierInfo();
578 NameLoc = ConsumeToken();
579 }
580
581 // There are three options here. If we have 'struct foo;', then this is a
582 // forward declaration. If we have 'struct foo {...' then this is a
583 // definition. Otherwise we have something like 'struct foo xyz', a reference.
584 //
585 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
586 // struct foo {..}; void bar() { struct foo; } <- new foo in bar.
587 // struct foo {..}; void bar() { struct foo x; } <- use of old foo.
588 //
589 Action::TagKind TK;
590 if (Tok.getKind() == tok::l_brace)
591 TK = Action::TK_Definition;
592 else if (Tok.getKind() == tok::semi)
593 TK = Action::TK_Declaration;
594 else
595 TK = Action::TK_Reference;
Steve Naroff0acc9c92007-09-15 18:49:24 +0000596 Decl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +0000597 return false;
598}
599
600
601/// ParseStructUnionSpecifier
602/// struct-or-union-specifier: [C99 6.7.2.1]
603/// struct-or-union identifier[opt] '{' struct-contents '}'
604/// struct-or-union identifier
605/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
606/// '}' attributes[opt]
607/// [GNU] struct-or-union attributes[opt] identifier
608/// struct-or-union:
609/// 'struct'
610/// 'union'
611///
612void Parser::ParseStructUnionSpecifier(DeclSpec &DS) {
613 assert((Tok.getKind() == tok::kw_struct ||
614 Tok.getKind() == tok::kw_union) && "Not a struct/union specifier");
615 DeclSpec::TST TagType =
616 Tok.getKind() == tok::kw_union ? DeclSpec::TST_union : DeclSpec::TST_struct;
617 SourceLocation StartLoc = ConsumeToken();
618
619 // Parse the tag portion of this.
620 DeclTy *TagDecl;
621 if (ParseTag(TagDecl, TagType, StartLoc))
622 return;
623
624 // If there is a body, parse it and inform the actions module.
625 if (Tok.getKind() == tok::l_brace)
626 ParseStructUnionBody(StartLoc, TagType, TagDecl);
627
628 const char *PrevSpec = 0;
629 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
630 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
631}
632
Steve Naroffa9adf112007-08-20 22:28:22 +0000633/// ParseStructDeclaration
Chris Lattner4b009652007-07-25 00:24:17 +0000634/// struct-declaration:
635/// specifier-qualifier-list struct-declarator-list ';'
636/// [GNU] __extension__ struct-declaration
637/// [GNU] specifier-qualifier-list ';'
638/// struct-declarator-list:
639/// struct-declarator
640/// struct-declarator-list ',' struct-declarator
641/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
642/// struct-declarator:
643/// declarator
644/// [GNU] declarator attributes[opt]
645/// declarator[opt] ':' constant-expression
646/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
647///
Steve Naroffa9adf112007-08-20 22:28:22 +0000648void Parser::ParseStructDeclaration(DeclTy *TagDecl,
Steve Naroffc02f4a92007-08-28 16:31:47 +0000649 llvm::SmallVectorImpl<DeclTy*> &FieldDecls) {
Steve Naroffa9adf112007-08-20 22:28:22 +0000650 // FIXME: When __extension__ is specified, disable extension diagnostics.
651 if (Tok.getKind() == tok::kw___extension__)
652 ConsumeToken();
653
654 // Parse the common specifier-qualifiers-list piece.
655 DeclSpec DS;
656 SourceLocation SpecQualLoc = Tok.getLocation();
657 ParseSpecifierQualifierList(DS);
658 // TODO: Does specifier-qualifier list correctly check that *something* is
659 // specified?
660
661 // If there are no declarators, issue a warning.
662 if (Tok.getKind() == tok::semi) {
663 Diag(SpecQualLoc, diag::w_no_declarators);
664 ConsumeToken();
665 return;
666 }
667
668 // Read struct-declarators until we find the semicolon.
669 Declarator DeclaratorInfo(DS, Declarator::MemberContext);
670
671 while (1) {
672 /// struct-declarator: declarator
673 /// struct-declarator: declarator[opt] ':' constant-expression
674 if (Tok.getKind() != tok::colon)
675 ParseDeclarator(DeclaratorInfo);
676
677 ExprTy *BitfieldSize = 0;
678 if (Tok.getKind() == tok::colon) {
679 ConsumeToken();
680 ExprResult Res = ParseConstantExpression();
681 if (Res.isInvalid) {
682 SkipUntil(tok::semi, true, true);
683 } else {
684 BitfieldSize = Res.Val;
685 }
686 }
687
688 // If attributes exist after the declarator, parse them.
689 if (Tok.getKind() == tok::kw___attribute)
690 DeclaratorInfo.AddAttributes(ParseAttributes());
691
692 // Install the declarator into the current TagDecl.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000693 DeclTy *Field = Actions.ActOnField(CurScope, TagDecl, SpecQualLoc,
Steve Naroffa9adf112007-08-20 22:28:22 +0000694 DeclaratorInfo, BitfieldSize);
695 FieldDecls.push_back(Field);
696
697 // If we don't have a comma, it is either the end of the list (a ';')
698 // or an error, bail out.
699 if (Tok.getKind() != tok::comma)
700 break;
701
702 // Consume the comma.
703 ConsumeToken();
704
705 // Parse the next declarator.
706 DeclaratorInfo.clear();
707
708 // Attributes are only allowed on the second declarator.
709 if (Tok.getKind() == tok::kw___attribute)
710 DeclaratorInfo.AddAttributes(ParseAttributes());
711 }
712 return;
713}
714
715/// ParseStructUnionBody
716/// struct-contents:
717/// struct-declaration-list
718/// [EXT] empty
719/// [GNU] "struct-declaration-list" without terminatoring ';'
720/// struct-declaration-list:
721/// struct-declaration
722/// struct-declaration-list struct-declaration
723/// [OBC] '@' 'defs' '(' class-name ')' [TODO]
724///
Chris Lattner4b009652007-07-25 00:24:17 +0000725void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
726 unsigned TagType, DeclTy *TagDecl) {
727 SourceLocation LBraceLoc = ConsumeBrace();
728
729 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
730 // C++.
731 if (Tok.getKind() == tok::r_brace)
732 Diag(Tok, diag::ext_empty_struct_union_enum,
733 DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
734
735 llvm::SmallVector<DeclTy*, 32> FieldDecls;
736
737 // While we still have something to read, read the declarations in the struct.
738 while (Tok.getKind() != tok::r_brace &&
739 Tok.getKind() != tok::eof) {
740 // Each iteration of this loop reads one struct-declaration.
741
742 // Check for extraneous top-level semicolon.
743 if (Tok.getKind() == tok::semi) {
744 Diag(Tok, diag::ext_extra_struct_semi);
745 ConsumeToken();
746 continue;
747 }
Steve Naroffa9adf112007-08-20 22:28:22 +0000748 ParseStructDeclaration(TagDecl, FieldDecls);
Chris Lattner4b009652007-07-25 00:24:17 +0000749
Chris Lattner4b009652007-07-25 00:24:17 +0000750 if (Tok.getKind() == tok::semi) {
751 ConsumeToken();
752 } else if (Tok.getKind() == tok::r_brace) {
753 Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
754 break;
755 } else {
756 Diag(Tok, diag::err_expected_semi_decl_list);
757 // Skip to end of block or statement
758 SkipUntil(tok::r_brace, true, true);
759 }
760 }
761
762 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
763
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000764 Actions.ActOnFields(CurScope,
765 RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000766
767 AttributeList *AttrList = 0;
768 // If attributes exist after struct contents, parse them.
769 if (Tok.getKind() == tok::kw___attribute)
770 AttrList = ParseAttributes(); // FIXME: where should I put them?
771}
772
773
774/// ParseEnumSpecifier
775/// enum-specifier: [C99 6.7.2.2]
776/// 'enum' identifier[opt] '{' enumerator-list '}'
777/// [C99] 'enum' identifier[opt] '{' enumerator-list ',' '}'
778/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
779/// '}' attributes[opt]
780/// 'enum' identifier
781/// [GNU] 'enum' attributes[opt] identifier
782void Parser::ParseEnumSpecifier(DeclSpec &DS) {
783 assert(Tok.getKind() == tok::kw_enum && "Not an enum specifier");
784 SourceLocation StartLoc = ConsumeToken();
785
786 // Parse the tag portion of this.
787 DeclTy *TagDecl;
788 if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
789 return;
790
791 if (Tok.getKind() == tok::l_brace)
792 ParseEnumBody(StartLoc, TagDecl);
793
794 // TODO: semantic analysis on the declspec for enums.
795 const char *PrevSpec = 0;
796 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
797 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
798}
799
800/// ParseEnumBody - Parse a {} enclosed enumerator-list.
801/// enumerator-list:
802/// enumerator
803/// enumerator-list ',' enumerator
804/// enumerator:
805/// enumeration-constant
806/// enumeration-constant '=' constant-expression
807/// enumeration-constant:
808/// identifier
809///
810void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
811 SourceLocation LBraceLoc = ConsumeBrace();
812
Chris Lattnerc9a92452007-08-27 17:24:30 +0000813 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
814 if (Tok.getKind() == tok::r_brace && !getLang().CPlusPlus)
Chris Lattner4b009652007-07-25 00:24:17 +0000815 Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
816
817 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
818
819 DeclTy *LastEnumConstDecl = 0;
820
821 // Parse the enumerator-list.
822 while (Tok.getKind() == tok::identifier) {
823 IdentifierInfo *Ident = Tok.getIdentifierInfo();
824 SourceLocation IdentLoc = ConsumeToken();
825
826 SourceLocation EqualLoc;
827 ExprTy *AssignedVal = 0;
828 if (Tok.getKind() == tok::equal) {
829 EqualLoc = ConsumeToken();
830 ExprResult Res = ParseConstantExpression();
831 if (Res.isInvalid)
832 SkipUntil(tok::comma, tok::r_brace, true, true);
833 else
834 AssignedVal = Res.Val;
835 }
836
837 // Install the enumerator constant into EnumDecl.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000838 DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +0000839 LastEnumConstDecl,
840 IdentLoc, Ident,
841 EqualLoc, AssignedVal);
842 EnumConstantDecls.push_back(EnumConstDecl);
843 LastEnumConstDecl = EnumConstDecl;
844
845 if (Tok.getKind() != tok::comma)
846 break;
847 SourceLocation CommaLoc = ConsumeToken();
848
849 if (Tok.getKind() != tok::identifier && !getLang().C99)
850 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
851 }
852
853 // Eat the }.
854 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
855
Steve Naroff0acc9c92007-09-15 18:49:24 +0000856 Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
Chris Lattner4b009652007-07-25 00:24:17 +0000857 EnumConstantDecls.size());
858
859 DeclTy *AttrList = 0;
860 // If attributes exist after the identifier list, parse them.
861 if (Tok.getKind() == tok::kw___attribute)
862 AttrList = ParseAttributes(); // FIXME: where do they do?
863}
864
865/// isTypeSpecifierQualifier - Return true if the current token could be the
866/// start of a specifier-qualifier-list.
867bool Parser::isTypeSpecifierQualifier() const {
868 switch (Tok.getKind()) {
869 default: return false;
870 // GNU attributes support.
871 case tok::kw___attribute:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000872 // GNU typeof support.
873 case tok::kw_typeof:
874
Chris Lattner4b009652007-07-25 00:24:17 +0000875 // type-specifiers
876 case tok::kw_short:
877 case tok::kw_long:
878 case tok::kw_signed:
879 case tok::kw_unsigned:
880 case tok::kw__Complex:
881 case tok::kw__Imaginary:
882 case tok::kw_void:
883 case tok::kw_char:
884 case tok::kw_int:
885 case tok::kw_float:
886 case tok::kw_double:
887 case tok::kw__Bool:
888 case tok::kw__Decimal32:
889 case tok::kw__Decimal64:
890 case tok::kw__Decimal128:
891
892 // struct-or-union-specifier
893 case tok::kw_struct:
894 case tok::kw_union:
895 // enum-specifier
896 case tok::kw_enum:
897
898 // type-qualifier
899 case tok::kw_const:
900 case tok::kw_volatile:
901 case tok::kw_restrict:
902 return true;
903
904 // typedef-name
905 case tok::identifier:
906 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000907 }
908}
909
910/// isDeclarationSpecifier() - Return true if the current token is part of a
911/// declaration specifier.
912bool Parser::isDeclarationSpecifier() const {
913 switch (Tok.getKind()) {
914 default: return false;
915 // storage-class-specifier
916 case tok::kw_typedef:
917 case tok::kw_extern:
918 case tok::kw_static:
919 case tok::kw_auto:
920 case tok::kw_register:
921 case tok::kw___thread:
922
923 // type-specifiers
924 case tok::kw_short:
925 case tok::kw_long:
926 case tok::kw_signed:
927 case tok::kw_unsigned:
928 case tok::kw__Complex:
929 case tok::kw__Imaginary:
930 case tok::kw_void:
931 case tok::kw_char:
932 case tok::kw_int:
933 case tok::kw_float:
934 case tok::kw_double:
935 case tok::kw__Bool:
936 case tok::kw__Decimal32:
937 case tok::kw__Decimal64:
938 case tok::kw__Decimal128:
939
940 // struct-or-union-specifier
941 case tok::kw_struct:
942 case tok::kw_union:
943 // enum-specifier
944 case tok::kw_enum:
945
946 // type-qualifier
947 case tok::kw_const:
948 case tok::kw_volatile:
949 case tok::kw_restrict:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000950
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // function-specifier
952 case tok::kw_inline:
Chris Lattnere35d2582007-08-09 16:40:21 +0000953
Chris Lattnerb707a7a2007-08-09 17:01:07 +0000954 // GNU typeof support.
955 case tok::kw_typeof:
956
957 // GNU attributes.
Chris Lattnere35d2582007-08-09 16:40:21 +0000958 case tok::kw___attribute:
Chris Lattner4b009652007-07-25 00:24:17 +0000959 return true;
960
961 // typedef-name
962 case tok::identifier:
963 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000964 }
965}
966
967
968/// ParseTypeQualifierListOpt
969/// type-qualifier-list: [C99 6.7.5]
970/// type-qualifier
971/// [GNU] attributes
972/// type-qualifier-list type-qualifier
973/// [GNU] type-qualifier-list attributes
974///
975void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
976 while (1) {
977 int isInvalid = false;
978 const char *PrevSpec = 0;
979 SourceLocation Loc = Tok.getLocation();
980
981 switch (Tok.getKind()) {
982 default:
983 // If this is not a type-qualifier token, we're done reading type
984 // qualifiers. First verify that DeclSpec's are consistent.
985 DS.Finish(Diags, getLang());
986 return;
987 case tok::kw_const:
988 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
989 getLang())*2;
990 break;
991 case tok::kw_volatile:
992 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
993 getLang())*2;
994 break;
995 case tok::kw_restrict:
996 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
997 getLang())*2;
998 break;
999 case tok::kw___attribute:
1000 DS.AddAttributes(ParseAttributes());
1001 continue; // do *not* consume the next token!
1002 }
1003
1004 // If the specifier combination wasn't legal, issue a diagnostic.
1005 if (isInvalid) {
1006 assert(PrevSpec && "Method did not return previous specifier!");
1007 if (isInvalid == 1) // Error.
1008 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
1009 else // extwarn.
1010 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
1011 }
1012 ConsumeToken();
1013 }
1014}
1015
1016
1017/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1018///
1019void Parser::ParseDeclarator(Declarator &D) {
1020 /// This implements the 'declarator' production in the C grammar, then checks
1021 /// for well-formedness and issues diagnostics.
1022 ParseDeclaratorInternal(D);
1023
1024 // TODO: validate D.
1025
1026}
1027
1028/// ParseDeclaratorInternal
1029/// declarator: [C99 6.7.5]
1030/// pointer[opt] direct-declarator
1031/// [C++] '&' declarator [C++ 8p4, dcl.decl]
1032/// [GNU] '&' restrict[opt] attributes[opt] declarator
1033///
1034/// pointer: [C99 6.7.5]
1035/// '*' type-qualifier-list[opt]
1036/// '*' type-qualifier-list[opt] pointer
1037///
1038void Parser::ParseDeclaratorInternal(Declarator &D) {
1039 tok::TokenKind Kind = Tok.getKind();
1040
1041 // Not a pointer or C++ reference.
1042 if (Kind != tok::star && !(Kind == tok::amp && getLang().CPlusPlus))
1043 return ParseDirectDeclarator(D);
1044
1045 // Otherwise, '*' -> pointer or '&' -> reference.
1046 SourceLocation Loc = ConsumeToken(); // Eat the * or &.
1047
1048 if (Kind == tok::star) {
1049 // Is a pointer
1050 DeclSpec DS;
1051
1052 ParseTypeQualifierListOpt(DS);
1053
1054 // Recursively parse the declarator.
1055 ParseDeclaratorInternal(D);
1056
1057 // Remember that we parsed a pointer type, and remember the type-quals.
1058 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc));
1059 } else {
1060 // Is a reference
1061 DeclSpec DS;
1062
1063 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1064 // cv-qualifiers are introduced through the use of a typedef or of a
1065 // template type argument, in which case the cv-qualifiers are ignored.
1066 //
1067 // [GNU] Retricted references are allowed.
1068 // [GNU] Attributes on references are allowed.
1069 ParseTypeQualifierListOpt(DS);
1070
1071 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1072 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1073 Diag(DS.getConstSpecLoc(),
1074 diag::err_invalid_reference_qualifier_application,
1075 "const");
1076 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1077 Diag(DS.getVolatileSpecLoc(),
1078 diag::err_invalid_reference_qualifier_application,
1079 "volatile");
1080 }
1081
1082 // Recursively parse the declarator.
1083 ParseDeclaratorInternal(D);
1084
1085 // Remember that we parsed a reference type. It doesn't have type-quals.
1086 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc));
1087 }
1088}
1089
1090/// ParseDirectDeclarator
1091/// direct-declarator: [C99 6.7.5]
1092/// identifier
1093/// '(' declarator ')'
1094/// [GNU] '(' attributes declarator ')'
1095/// [C90] direct-declarator '[' constant-expression[opt] ']'
1096/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1097/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1098/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1099/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1100/// direct-declarator '(' parameter-type-list ')'
1101/// direct-declarator '(' identifier-list[opt] ')'
1102/// [GNU] direct-declarator '(' parameter-forward-declarations
1103/// parameter-type-list[opt] ')'
1104///
1105void Parser::ParseDirectDeclarator(Declarator &D) {
1106 // Parse the first direct-declarator seen.
1107 if (Tok.getKind() == tok::identifier && D.mayHaveIdentifier()) {
1108 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1109 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1110 ConsumeToken();
1111 } else if (Tok.getKind() == tok::l_paren) {
1112 // direct-declarator: '(' declarator ')'
1113 // direct-declarator: '(' attributes declarator ')'
1114 // Example: 'char (*X)' or 'int (*XX)(void)'
1115 ParseParenDeclarator(D);
1116 } else if (D.mayOmitIdentifier()) {
1117 // This could be something simple like "int" (in which case the declarator
1118 // portion is empty), if an abstract-declarator is allowed.
1119 D.SetIdentifier(0, Tok.getLocation());
1120 } else {
1121 // Expected identifier or '('.
1122 Diag(Tok, diag::err_expected_ident_lparen);
1123 D.SetIdentifier(0, Tok.getLocation());
1124 }
1125
1126 assert(D.isPastIdentifier() &&
1127 "Haven't past the location of the identifier yet?");
1128
1129 while (1) {
1130 if (Tok.getKind() == tok::l_paren) {
1131 ParseParenDeclarator(D);
1132 } else if (Tok.getKind() == tok::l_square) {
1133 ParseBracketDeclarator(D);
1134 } else {
1135 break;
1136 }
1137 }
1138}
1139
1140/// ParseParenDeclarator - We parsed the declarator D up to a paren. This may
1141/// either be before the identifier (in which case these are just grouping
1142/// parens for precedence) or it may be after the identifier, in which case
1143/// these are function arguments.
1144///
1145/// This method also handles this portion of the grammar:
1146/// parameter-type-list: [C99 6.7.5]
1147/// parameter-list
1148/// parameter-list ',' '...'
1149///
1150/// parameter-list: [C99 6.7.5]
1151/// parameter-declaration
1152/// parameter-list ',' parameter-declaration
1153///
1154/// parameter-declaration: [C99 6.7.5]
1155/// declaration-specifiers declarator
1156/// [GNU] declaration-specifiers declarator attributes
1157/// declaration-specifiers abstract-declarator[opt]
1158/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
1159///
1160/// identifier-list: [C99 6.7.5]
1161/// identifier
1162/// identifier-list ',' identifier
1163///
1164void Parser::ParseParenDeclarator(Declarator &D) {
1165 SourceLocation StartLoc = ConsumeParen();
1166
1167 // If we haven't past the identifier yet (or where the identifier would be
1168 // stored, if this is an abstract declarator), then this is probably just
1169 // grouping parens.
1170 if (!D.isPastIdentifier()) {
1171 // Okay, this is probably a grouping paren. However, if this could be an
1172 // abstract-declarator, then this could also be the start of function
1173 // arguments (consider 'void()').
1174 bool isGrouping;
1175
1176 if (!D.mayOmitIdentifier()) {
1177 // If this can't be an abstract-declarator, this *must* be a grouping
1178 // paren, because we haven't seen the identifier yet.
1179 isGrouping = true;
1180 } else if (Tok.getKind() == tok::r_paren || // 'int()' is a function.
1181 isDeclarationSpecifier()) { // 'int(int)' is a function.
1182 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1183 // considered to be a type, not a K&R identifier-list.
1184 isGrouping = false;
1185 } else {
1186 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1187 isGrouping = true;
1188 }
1189
1190 // If this is a grouping paren, handle:
1191 // direct-declarator: '(' declarator ')'
1192 // direct-declarator: '(' attributes declarator ')'
1193 if (isGrouping) {
1194 if (Tok.getKind() == tok::kw___attribute)
1195 D.AddAttributes(ParseAttributes());
1196
1197 ParseDeclaratorInternal(D);
1198 // Match the ')'.
1199 MatchRHSPunctuation(tok::r_paren, StartLoc);
1200 return;
1201 }
1202
1203 // Okay, if this wasn't a grouping paren, it must be the start of a function
1204 // argument list. Recognize that this declarator will never have an
1205 // identifier (and remember where it would have been), then fall through to
1206 // the handling of argument lists.
1207 D.SetIdentifier(0, Tok.getLocation());
1208 }
1209
1210 // Okay, this is the parameter list of a function definition, or it is an
1211 // identifier list of a K&R-style function.
1212 bool IsVariadic;
1213 bool HasPrototype;
1214 bool ErrorEmitted = false;
1215
1216 // Build up an array of information about the parsed arguments.
1217 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1218 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1219
1220 if (Tok.getKind() == tok::r_paren) {
1221 // int() -> no prototype, no '...'.
1222 IsVariadic = false;
1223 HasPrototype = false;
1224 } else if (Tok.getKind() == tok::identifier &&
1225 // K&R identifier lists can't have typedefs as identifiers, per
1226 // C99 6.7.5.3p11.
1227 !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1228 // Identifier list. Note that '(' identifier-list ')' is only allowed for
1229 // normal declarators, not for abstract-declarators.
1230 assert(D.isPastIdentifier() && "Identifier (if present) must be passed!");
1231
1232 // If there was no identifier specified, either we are in an
1233 // abstract-declarator, or we are in a parameter declarator which was found
1234 // to be abstract. In abstract-declarators, identifier lists are not valid,
1235 // diagnose this.
1236 if (!D.getIdentifier())
1237 Diag(Tok, diag::ext_ident_list_in_param);
1238
1239 // Remember this identifier in ParamInfo.
1240 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1241 Tok.getLocation(), 0));
1242
1243 ConsumeToken();
1244 while (Tok.getKind() == tok::comma) {
1245 // Eat the comma.
1246 ConsumeToken();
1247
1248 if (Tok.getKind() != tok::identifier) {
1249 Diag(Tok, diag::err_expected_ident);
1250 ErrorEmitted = true;
1251 break;
1252 }
1253
1254 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1255
1256 // Verify that the argument identifier has not already been mentioned.
1257 if (!ParamsSoFar.insert(ParmII)) {
1258 Diag(Tok.getLocation(), diag::err_param_redefinition,ParmII->getName());
1259 ParmII = 0;
1260 }
1261
1262 // Remember this identifier in ParamInfo.
1263 if (ParmII)
1264 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1265 Tok.getLocation(), 0));
1266
1267 // Eat the identifier.
1268 ConsumeToken();
1269 }
1270
1271 // K&R 'prototype'.
1272 IsVariadic = false;
1273 HasPrototype = false;
1274 } else {
1275 // Finally, a normal, non-empty parameter type list.
1276
1277 // Enter function-declaration scope, limiting any declarators for struct
1278 // tags to the function prototype scope.
1279 // FIXME: is this needed?
Chris Lattnera7549902007-08-26 06:24:45 +00001280 EnterScope(Scope::DeclScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001281
1282 IsVariadic = false;
1283 while (1) {
1284 if (Tok.getKind() == tok::ellipsis) {
1285 IsVariadic = true;
1286
1287 // Check to see if this is "void(...)" which is not allowed.
1288 if (ParamInfo.empty()) {
1289 // Otherwise, parse parameter type list. If it starts with an
1290 // ellipsis, diagnose the malformed function.
1291 Diag(Tok, diag::err_ellipsis_first_arg);
1292 IsVariadic = false; // Treat this like 'void()'.
1293 }
1294
1295 // Consume the ellipsis.
1296 ConsumeToken();
1297 break;
1298 }
1299
1300 // Parse the declaration-specifiers.
1301 DeclSpec DS;
1302 ParseDeclarationSpecifiers(DS);
1303
1304 // Parse the declarator. This is "PrototypeContext", because we must
1305 // accept either 'declarator' or 'abstract-declarator' here.
1306 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1307 ParseDeclarator(ParmDecl);
1308
1309 // Parse GNU attributes, if present.
1310 if (Tok.getKind() == tok::kw___attribute)
1311 ParmDecl.AddAttributes(ParseAttributes());
1312
1313 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1314 // NOTE: we could trivially allow 'int foo(auto int X)' if we wanted.
1315 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1316 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1317 Diag(DS.getStorageClassSpecLoc(),
1318 diag::err_invalid_storage_class_in_func_decl);
1319 DS.ClearStorageClassSpecs();
1320 }
1321 if (DS.isThreadSpecified()) {
1322 Diag(DS.getThreadSpecLoc(),
1323 diag::err_invalid_storage_class_in_func_decl);
1324 DS.ClearStorageClassSpecs();
1325 }
1326
1327 // Inform the actions module about the parameter declarator, so it gets
1328 // added to the current scope.
1329 Action::TypeResult ParamTy =
Steve Naroff0acc9c92007-09-15 18:49:24 +00001330 Actions.ActOnParamDeclaratorType(CurScope, ParmDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001331
1332 // Remember this parsed parameter in ParamInfo.
1333 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1334
1335 // Verify that the argument identifier has not already been mentioned.
1336 if (ParmII && !ParamsSoFar.insert(ParmII)) {
1337 Diag(ParmDecl.getIdentifierLoc(), diag::err_param_redefinition,
1338 ParmII->getName());
1339 ParmII = 0;
1340 }
1341
Steve Naroff91b03f72007-08-28 03:03:08 +00001342 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1343 ParmDecl.getIdentifierLoc(), ParamTy.Val, ParmDecl.getInvalidType()));
Chris Lattner4b009652007-07-25 00:24:17 +00001344
1345 // If the next token is a comma, consume it and keep reading arguments.
1346 if (Tok.getKind() != tok::comma) break;
1347
1348 // Consume the comma.
1349 ConsumeToken();
1350 }
1351
1352 HasPrototype = true;
1353
1354 // Leave prototype scope.
1355 ExitScope();
1356 }
1357
1358 // Remember that we parsed a function type, and remember the attributes.
1359 if (!ErrorEmitted)
1360 D.AddTypeInfo(DeclaratorChunk::getFunction(HasPrototype, IsVariadic,
1361 &ParamInfo[0], ParamInfo.size(),
1362 StartLoc));
1363
1364 // If we have the closing ')', eat it and we're done.
1365 if (Tok.getKind() == tok::r_paren) {
1366 ConsumeParen();
1367 } else {
1368 // If an error happened earlier parsing something else in the proto, don't
1369 // issue another error.
1370 if (!ErrorEmitted)
1371 Diag(Tok, diag::err_expected_rparen);
1372 SkipUntil(tok::r_paren);
1373 }
1374}
1375
1376
1377/// [C90] direct-declarator '[' constant-expression[opt] ']'
1378/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1379/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1380/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1381/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1382void Parser::ParseBracketDeclarator(Declarator &D) {
1383 SourceLocation StartLoc = ConsumeBracket();
1384
1385 // If valid, this location is the position where we read the 'static' keyword.
1386 SourceLocation StaticLoc;
1387 if (Tok.getKind() == tok::kw_static)
1388 StaticLoc = ConsumeToken();
1389
1390 // If there is a type-qualifier-list, read it now.
1391 DeclSpec DS;
1392 ParseTypeQualifierListOpt(DS);
1393
1394 // If we haven't already read 'static', check to see if there is one after the
1395 // type-qualifier-list.
1396 if (!StaticLoc.isValid() && Tok.getKind() == tok::kw_static)
1397 StaticLoc = ConsumeToken();
1398
1399 // Handle "direct-declarator [ type-qual-list[opt] * ]".
1400 bool isStar = false;
1401 ExprResult NumElements(false);
1402 if (Tok.getKind() == tok::star) {
1403 // Remember the '*' token, in case we have to un-get it.
1404 Token StarTok = Tok;
1405 ConsumeToken();
1406
1407 // Check that the ']' token is present to avoid incorrectly parsing
1408 // expressions starting with '*' as [*].
1409 if (Tok.getKind() == tok::r_square) {
1410 if (StaticLoc.isValid())
1411 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1412 StaticLoc = SourceLocation(); // Drop the static.
1413 isStar = true;
1414 } else {
1415 // Otherwise, the * must have been some expression (such as '*ptr') that
1416 // started an assignment-expr. We already consumed the token, but now we
1417 // need to reparse it. This handles cases like 'X[*p + 4]'
1418 NumElements = ParseAssignmentExpressionWithLeadingStar(StarTok);
1419 }
1420 } else if (Tok.getKind() != tok::r_square) {
1421 // Parse the assignment-expression now.
1422 NumElements = ParseAssignmentExpression();
1423 }
1424
1425 // If there was an error parsing the assignment-expression, recover.
1426 if (NumElements.isInvalid) {
1427 // If the expression was invalid, skip it.
1428 SkipUntil(tok::r_square);
1429 return;
1430 }
1431
1432 MatchRHSPunctuation(tok::r_square, StartLoc);
1433
1434 // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1435 // it was not a constant expression.
1436 if (!getLang().C99) {
1437 // TODO: check C90 array constant exprness.
1438 if (isStar || StaticLoc.isValid() ||
1439 0/*TODO: NumElts is not a C90 constantexpr */)
1440 Diag(StartLoc, diag::ext_c99_array_usage);
1441 }
1442
1443 // Remember that we parsed a pointer type, and remember the type-quals.
1444 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1445 StaticLoc.isValid(), isStar,
1446 NumElements.Val, StartLoc));
1447}
1448
Steve Naroff7cbb1462007-07-31 12:34:36 +00001449/// [GNU] typeof-specifier:
1450/// typeof ( expressions )
1451/// typeof ( type-name )
1452///
1453void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1454 assert(Tok.getKind() == tok::kw_typeof && "Not a typeof specifier");
Steve Naroff14bbce82007-08-02 02:53:48 +00001455 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
Steve Naroff7cbb1462007-07-31 12:34:36 +00001456 SourceLocation StartLoc = ConsumeToken();
1457
1458 if (Tok.getKind() != tok::l_paren) {
Steve Naroff14bbce82007-08-02 02:53:48 +00001459 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
1460 return;
Steve Naroff7cbb1462007-07-31 12:34:36 +00001461 }
1462 SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
1463
1464 if (isTypeSpecifierQualifier()) {
1465 TypeTy *Ty = ParseTypeName();
1466
Steve Naroff4c255ab2007-07-31 23:56:32 +00001467 assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
1468
Steve Naroff14bbce82007-08-02 02:53:48 +00001469 if (Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001470 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001471 return;
1472 }
1473 RParenLoc = ConsumeParen();
1474 const char *PrevSpec = 0;
1475 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1476 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
1477 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001478 } else { // we have an expression.
1479 ExprResult Result = ParseExpression();
Steve Naroff4c255ab2007-07-31 23:56:32 +00001480
Steve Naroff14bbce82007-08-02 02:53:48 +00001481 if (Result.isInvalid || Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001482 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001483 return;
1484 }
1485 RParenLoc = ConsumeParen();
1486 const char *PrevSpec = 0;
1487 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1488 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1489 Result.Val))
1490 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001491 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001492}
1493