blob: a96211df7d20b223c424c5bbc656183a2ff5adab [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.
193Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
194 // Parse the common declaration-specifiers piece.
195 DeclSpec DS;
196 ParseDeclarationSpecifiers(DS);
197
198 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
199 // declaration-specifiers init-declarator-list[opt] ';'
200 if (Tok.getKind() == tok::semi) {
201 ConsumeToken();
202 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
203 }
204
205 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
206 ParseDeclarator(DeclaratorInfo);
207
208 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
209}
210
211/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
212/// parsing 'declaration-specifiers declarator'. This method is split out this
213/// way to handle the ambiguity between top-level function-definitions and
214/// declarations.
215///
216/// declaration: [C99 6.7]
217/// declaration-specifiers init-declarator-list[opt] ';' [TODO]
218/// [!C99] init-declarator-list ';' [TODO]
219/// [OMP] threadprivate-directive [TODO]
220///
221/// init-declarator-list: [C99 6.7]
222/// init-declarator
223/// init-declarator-list ',' init-declarator
224/// init-declarator: [C99 6.7]
225/// declarator
226/// declarator '=' initializer
227/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
228/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
229///
230Parser::DeclTy *Parser::
231ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
232
233 // Declarators may be grouped together ("int X, *Y, Z();"). Provide info so
234 // that they can be chained properly if the actions want this.
235 Parser::DeclTy *LastDeclInGroup = 0;
236
237 // At this point, we know that it is not a function definition. Parse the
238 // rest of the init-declarator-list.
239 while (1) {
240 // If a simple-asm-expr is present, parse it.
241 if (Tok.getKind() == tok::kw_asm)
242 ParseSimpleAsm();
243
244 // If attributes are present, parse them.
245 if (Tok.getKind() == tok::kw___attribute)
246 D.AddAttributes(ParseAttributes());
247
248 // Parse declarator '=' initializer.
249 ExprResult Init;
250 if (Tok.getKind() == tok::equal) {
251 ConsumeToken();
252 Init = ParseInitializer();
253 if (Init.isInvalid) {
254 SkipUntil(tok::semi);
255 return 0;
256 }
257 }
258
259 // Inform the current actions module that we just parsed this declarator.
260 // FIXME: pass asm & attributes.
261 LastDeclInGroup = Actions.ParseDeclarator(CurScope, D, Init.Val,
262 LastDeclInGroup);
263
264 // If we don't have a comma, it is either the end of the list (a ';') or an
265 // error, bail out.
266 if (Tok.getKind() != tok::comma)
267 break;
268
269 // Consume the comma.
270 ConsumeToken();
271
272 // Parse the next declarator.
273 D.clear();
274 ParseDeclarator(D);
275 }
276
277 if (Tok.getKind() == tok::semi) {
278 ConsumeToken();
279 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
280 }
281
282 Diag(Tok, diag::err_parse_error);
283 // Skip to end of block or statement
284 SkipUntil(tok::r_brace, true);
285 if (Tok.getKind() == tok::semi)
286 ConsumeToken();
287 return 0;
288}
289
290/// ParseSpecifierQualifierList
291/// specifier-qualifier-list:
292/// type-specifier specifier-qualifier-list[opt]
293/// type-qualifier specifier-qualifier-list[opt]
294/// [GNU] attributes specifier-qualifier-list[opt]
295///
296void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
297 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
298 /// parse declaration-specifiers and complain about extra stuff.
299 ParseDeclarationSpecifiers(DS);
300
301 // Validate declspec for type-name.
302 unsigned Specs = DS.getParsedSpecifiers();
303 if (Specs == DeclSpec::PQ_None)
304 Diag(Tok, diag::err_typename_requires_specqual);
305
306 // Issue diagnostic and remove storage class if present.
307 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
308 if (DS.getStorageClassSpecLoc().isValid())
309 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
310 else
311 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
312 DS.ClearStorageClassSpecs();
313 }
314
315 // Issue diagnostic and remove function specfier if present.
316 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
317 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
318 DS.ClearFunctionSpecs();
319 }
320}
321
322/// ParseDeclarationSpecifiers
323/// declaration-specifiers: [C99 6.7]
324/// storage-class-specifier declaration-specifiers[opt]
325/// type-specifier declaration-specifiers[opt]
326/// type-qualifier declaration-specifiers[opt]
327/// [C99] function-specifier declaration-specifiers[opt]
328/// [GNU] attributes declaration-specifiers[opt]
329///
330/// storage-class-specifier: [C99 6.7.1]
331/// 'typedef'
332/// 'extern'
333/// 'static'
334/// 'auto'
335/// 'register'
336/// [GNU] '__thread'
337/// type-specifier: [C99 6.7.2]
338/// 'void'
339/// 'char'
340/// 'short'
341/// 'int'
342/// 'long'
343/// 'float'
344/// 'double'
345/// 'signed'
346/// 'unsigned'
347/// struct-or-union-specifier
348/// enum-specifier
349/// typedef-name
350/// [C++] 'bool'
351/// [C99] '_Bool'
352/// [C99] '_Complex'
353/// [C99] '_Imaginary' // Removed in TC2?
354/// [GNU] '_Decimal32'
355/// [GNU] '_Decimal64'
356/// [GNU] '_Decimal128'
Steve Naroff4c255ab2007-07-31 23:56:32 +0000357/// [GNU] typeof-specifier
Chris Lattner4b009652007-07-25 00:24:17 +0000358/// [OBJC] class-name objc-protocol-refs[opt] [TODO]
359/// [OBJC] typedef-name objc-protocol-refs [TODO]
360/// [OBJC] objc-protocol-refs [TODO]
361/// type-qualifier:
362/// 'const'
363/// 'volatile'
364/// [C99] 'restrict'
365/// function-specifier: [C99 6.7.4]
366/// [C99] 'inline'
367///
368void Parser::ParseDeclarationSpecifiers(DeclSpec &DS) {
369 DS.Range.setBegin(Tok.getLocation());
370 while (1) {
371 int isInvalid = false;
372 const char *PrevSpec = 0;
373 SourceLocation Loc = Tok.getLocation();
374
375 switch (Tok.getKind()) {
376 // typedef-name
377 case tok::identifier:
378 // This identifier can only be a typedef name if we haven't already seen
379 // a type-specifier. Without this check we misparse:
380 // typedef int X; struct Y { short X; }; as 'short int'.
381 if (!DS.hasTypeSpecifier()) {
382 // It has to be available as a typedef too!
383 if (void *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(),
384 CurScope)) {
385 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
386 TypeRep);
387 break;
388 }
389 }
390 // FALL THROUGH.
391 default:
392 // If this is not a declaration specifier token, we're done reading decl
393 // specifiers. First verify that DeclSpec's are consistent.
394 DS.Finish(Diags, getLang());
395 return;
396
397 // GNU attributes support.
398 case tok::kw___attribute:
399 DS.AddAttributes(ParseAttributes());
400 continue;
401
402 // storage-class-specifier
403 case tok::kw_typedef:
404 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
405 break;
406 case tok::kw_extern:
407 if (DS.isThreadSpecified())
408 Diag(Tok, diag::ext_thread_before, "extern");
409 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
410 break;
411 case tok::kw_static:
412 if (DS.isThreadSpecified())
413 Diag(Tok, diag::ext_thread_before, "static");
414 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
415 break;
416 case tok::kw_auto:
417 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
418 break;
419 case tok::kw_register:
420 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
421 break;
422 case tok::kw___thread:
423 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
424 break;
425
426 // type-specifiers
427 case tok::kw_short:
428 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
429 break;
430 case tok::kw_long:
431 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
432 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
433 else
434 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
435 break;
436 case tok::kw_signed:
437 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
438 break;
439 case tok::kw_unsigned:
440 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
441 break;
442 case tok::kw__Complex:
443 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
444 break;
445 case tok::kw__Imaginary:
446 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
447 break;
448 case tok::kw_void:
449 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
450 break;
451 case tok::kw_char:
452 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
453 break;
454 case tok::kw_int:
455 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
456 break;
457 case tok::kw_float:
458 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
459 break;
460 case tok::kw_double:
461 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
462 break;
463 case tok::kw_bool: // [C++ 2.11p1]
464 case tok::kw__Bool:
465 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
466 break;
467 case tok::kw__Decimal32:
468 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
469 break;
470 case tok::kw__Decimal64:
471 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
472 break;
473 case tok::kw__Decimal128:
474 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
475 break;
476
477 case tok::kw_struct:
478 case tok::kw_union:
479 ParseStructUnionSpecifier(DS);
480 continue;
481 case tok::kw_enum:
482 ParseEnumSpecifier(DS);
483 continue;
484
Steve Naroff7cbb1462007-07-31 12:34:36 +0000485 // GNU typeof support.
486 case tok::kw_typeof:
487 ParseTypeofSpecifier(DS);
488 continue;
489
Chris Lattner4b009652007-07-25 00:24:17 +0000490 // type-qualifier
491 case tok::kw_const:
492 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
493 getLang())*2;
494 break;
495 case tok::kw_volatile:
496 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
497 getLang())*2;
498 break;
499 case tok::kw_restrict:
500 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
501 getLang())*2;
502 break;
503
504 // function-specifier
505 case tok::kw_inline:
506 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
507 break;
508 }
509 // If the specifier combination wasn't legal, issue a diagnostic.
510 if (isInvalid) {
511 assert(PrevSpec && "Method did not return previous specifier!");
512 if (isInvalid == 1) // Error.
513 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
514 else // extwarn.
515 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
516 }
517 DS.Range.setEnd(Tok.getLocation());
518 ConsumeToken();
519 }
520}
521
522/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
523/// the first token has already been read and has been turned into an instance
524/// of DeclSpec::TST (TagType). This returns true if there is an error parsing,
525/// otherwise it returns false and fills in Decl.
526bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
527 AttributeList *Attr = 0;
528 // If attributes exist after tag, parse them.
529 if (Tok.getKind() == tok::kw___attribute)
530 Attr = ParseAttributes();
531
532 // Must have either 'struct name' or 'struct {...}'.
533 if (Tok.getKind() != tok::identifier &&
534 Tok.getKind() != tok::l_brace) {
535 Diag(Tok, diag::err_expected_ident_lbrace);
536
537 // Skip the rest of this declarator, up until the comma or semicolon.
538 SkipUntil(tok::comma, true);
539 return true;
540 }
541
542 // If an identifier is present, consume and remember it.
543 IdentifierInfo *Name = 0;
544 SourceLocation NameLoc;
545 if (Tok.getKind() == tok::identifier) {
546 Name = Tok.getIdentifierInfo();
547 NameLoc = ConsumeToken();
548 }
549
550 // There are three options here. If we have 'struct foo;', then this is a
551 // forward declaration. If we have 'struct foo {...' then this is a
552 // definition. Otherwise we have something like 'struct foo xyz', a reference.
553 //
554 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
555 // struct foo {..}; void bar() { struct foo; } <- new foo in bar.
556 // struct foo {..}; void bar() { struct foo x; } <- use of old foo.
557 //
558 Action::TagKind TK;
559 if (Tok.getKind() == tok::l_brace)
560 TK = Action::TK_Definition;
561 else if (Tok.getKind() == tok::semi)
562 TK = Action::TK_Declaration;
563 else
564 TK = Action::TK_Reference;
565 Decl = Actions.ParseTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
566 return false;
567}
568
569
570/// ParseStructUnionSpecifier
571/// struct-or-union-specifier: [C99 6.7.2.1]
572/// struct-or-union identifier[opt] '{' struct-contents '}'
573/// struct-or-union identifier
574/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
575/// '}' attributes[opt]
576/// [GNU] struct-or-union attributes[opt] identifier
577/// struct-or-union:
578/// 'struct'
579/// 'union'
580///
581void Parser::ParseStructUnionSpecifier(DeclSpec &DS) {
582 assert((Tok.getKind() == tok::kw_struct ||
583 Tok.getKind() == tok::kw_union) && "Not a struct/union specifier");
584 DeclSpec::TST TagType =
585 Tok.getKind() == tok::kw_union ? DeclSpec::TST_union : DeclSpec::TST_struct;
586 SourceLocation StartLoc = ConsumeToken();
587
588 // Parse the tag portion of this.
589 DeclTy *TagDecl;
590 if (ParseTag(TagDecl, TagType, StartLoc))
591 return;
592
593 // If there is a body, parse it and inform the actions module.
594 if (Tok.getKind() == tok::l_brace)
595 ParseStructUnionBody(StartLoc, TagType, TagDecl);
596
597 const char *PrevSpec = 0;
598 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
599 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
600}
601
602
603/// ParseStructUnionBody
604/// struct-contents:
605/// struct-declaration-list
606/// [EXT] empty
607/// [GNU] "struct-declaration-list" without terminatoring ';'
608/// struct-declaration-list:
609/// struct-declaration
610/// struct-declaration-list struct-declaration
611/// [OBC] '@' 'defs' '(' class-name ')' [TODO]
612/// struct-declaration:
613/// specifier-qualifier-list struct-declarator-list ';'
614/// [GNU] __extension__ struct-declaration
615/// [GNU] specifier-qualifier-list ';'
616/// struct-declarator-list:
617/// struct-declarator
618/// struct-declarator-list ',' struct-declarator
619/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
620/// struct-declarator:
621/// declarator
622/// [GNU] declarator attributes[opt]
623/// declarator[opt] ':' constant-expression
624/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
625///
626void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
627 unsigned TagType, DeclTy *TagDecl) {
628 SourceLocation LBraceLoc = ConsumeBrace();
629
630 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
631 // C++.
632 if (Tok.getKind() == tok::r_brace)
633 Diag(Tok, diag::ext_empty_struct_union_enum,
634 DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
635
636 llvm::SmallVector<DeclTy*, 32> FieldDecls;
637
638 // While we still have something to read, read the declarations in the struct.
639 while (Tok.getKind() != tok::r_brace &&
640 Tok.getKind() != tok::eof) {
641 // Each iteration of this loop reads one struct-declaration.
642
643 // Check for extraneous top-level semicolon.
644 if (Tok.getKind() == tok::semi) {
645 Diag(Tok, diag::ext_extra_struct_semi);
646 ConsumeToken();
647 continue;
648 }
649
650 // 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 continue;
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.
693 DeclTy *Field = Actions.ParseField(CurScope, TagDecl, SpecQualLoc,
694 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
713 if (Tok.getKind() == tok::semi) {
714 ConsumeToken();
715 } else if (Tok.getKind() == tok::r_brace) {
716 Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
717 break;
718 } else {
719 Diag(Tok, diag::err_expected_semi_decl_list);
720 // Skip to end of block or statement
721 SkipUntil(tok::r_brace, true, true);
722 }
723 }
724
725 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
726
727 Actions.ParseRecordBody(RecordLoc, TagDecl, &FieldDecls[0],FieldDecls.size());
728
729 AttributeList *AttrList = 0;
730 // If attributes exist after struct contents, parse them.
731 if (Tok.getKind() == tok::kw___attribute)
732 AttrList = ParseAttributes(); // FIXME: where should I put them?
733}
734
735
736/// ParseEnumSpecifier
737/// enum-specifier: [C99 6.7.2.2]
738/// 'enum' identifier[opt] '{' enumerator-list '}'
739/// [C99] 'enum' identifier[opt] '{' enumerator-list ',' '}'
740/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
741/// '}' attributes[opt]
742/// 'enum' identifier
743/// [GNU] 'enum' attributes[opt] identifier
744void Parser::ParseEnumSpecifier(DeclSpec &DS) {
745 assert(Tok.getKind() == tok::kw_enum && "Not an enum specifier");
746 SourceLocation StartLoc = ConsumeToken();
747
748 // Parse the tag portion of this.
749 DeclTy *TagDecl;
750 if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
751 return;
752
753 if (Tok.getKind() == tok::l_brace)
754 ParseEnumBody(StartLoc, TagDecl);
755
756 // TODO: semantic analysis on the declspec for enums.
757 const char *PrevSpec = 0;
758 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
759 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
760}
761
762/// ParseEnumBody - Parse a {} enclosed enumerator-list.
763/// enumerator-list:
764/// enumerator
765/// enumerator-list ',' enumerator
766/// enumerator:
767/// enumeration-constant
768/// enumeration-constant '=' constant-expression
769/// enumeration-constant:
770/// identifier
771///
772void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
773 SourceLocation LBraceLoc = ConsumeBrace();
774
775 if (Tok.getKind() == tok::r_brace)
776 Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
777
778 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
779
780 DeclTy *LastEnumConstDecl = 0;
781
782 // Parse the enumerator-list.
783 while (Tok.getKind() == tok::identifier) {
784 IdentifierInfo *Ident = Tok.getIdentifierInfo();
785 SourceLocation IdentLoc = ConsumeToken();
786
787 SourceLocation EqualLoc;
788 ExprTy *AssignedVal = 0;
789 if (Tok.getKind() == tok::equal) {
790 EqualLoc = ConsumeToken();
791 ExprResult Res = ParseConstantExpression();
792 if (Res.isInvalid)
793 SkipUntil(tok::comma, tok::r_brace, true, true);
794 else
795 AssignedVal = Res.Val;
796 }
797
798 // Install the enumerator constant into EnumDecl.
799 DeclTy *EnumConstDecl = Actions.ParseEnumConstant(CurScope, EnumDecl,
800 LastEnumConstDecl,
801 IdentLoc, Ident,
802 EqualLoc, AssignedVal);
803 EnumConstantDecls.push_back(EnumConstDecl);
804 LastEnumConstDecl = EnumConstDecl;
805
806 if (Tok.getKind() != tok::comma)
807 break;
808 SourceLocation CommaLoc = ConsumeToken();
809
810 if (Tok.getKind() != tok::identifier && !getLang().C99)
811 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
812 }
813
814 // Eat the }.
815 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
816
817 Actions.ParseEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
818 EnumConstantDecls.size());
819
820 DeclTy *AttrList = 0;
821 // If attributes exist after the identifier list, parse them.
822 if (Tok.getKind() == tok::kw___attribute)
823 AttrList = ParseAttributes(); // FIXME: where do they do?
824}
825
826/// isTypeSpecifierQualifier - Return true if the current token could be the
827/// start of a specifier-qualifier-list.
828bool Parser::isTypeSpecifierQualifier() const {
829 switch (Tok.getKind()) {
830 default: return false;
831 // GNU attributes support.
832 case tok::kw___attribute:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000833 // GNU typeof support.
834 case tok::kw_typeof:
835
Chris Lattner4b009652007-07-25 00:24:17 +0000836 // type-specifiers
837 case tok::kw_short:
838 case tok::kw_long:
839 case tok::kw_signed:
840 case tok::kw_unsigned:
841 case tok::kw__Complex:
842 case tok::kw__Imaginary:
843 case tok::kw_void:
844 case tok::kw_char:
845 case tok::kw_int:
846 case tok::kw_float:
847 case tok::kw_double:
848 case tok::kw__Bool:
849 case tok::kw__Decimal32:
850 case tok::kw__Decimal64:
851 case tok::kw__Decimal128:
852
853 // struct-or-union-specifier
854 case tok::kw_struct:
855 case tok::kw_union:
856 // enum-specifier
857 case tok::kw_enum:
858
859 // type-qualifier
860 case tok::kw_const:
861 case tok::kw_volatile:
862 case tok::kw_restrict:
863 return true;
864
865 // typedef-name
866 case tok::identifier:
867 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
868
869 // TODO: Attributes.
870 }
871}
872
873/// isDeclarationSpecifier() - Return true if the current token is part of a
874/// declaration specifier.
875bool Parser::isDeclarationSpecifier() const {
876 switch (Tok.getKind()) {
877 default: return false;
878 // storage-class-specifier
879 case tok::kw_typedef:
880 case tok::kw_extern:
881 case tok::kw_static:
882 case tok::kw_auto:
883 case tok::kw_register:
884 case tok::kw___thread:
885
886 // type-specifiers
887 case tok::kw_short:
888 case tok::kw_long:
889 case tok::kw_signed:
890 case tok::kw_unsigned:
891 case tok::kw__Complex:
892 case tok::kw__Imaginary:
893 case tok::kw_void:
894 case tok::kw_char:
895 case tok::kw_int:
896 case tok::kw_float:
897 case tok::kw_double:
898 case tok::kw__Bool:
899 case tok::kw__Decimal32:
900 case tok::kw__Decimal64:
901 case tok::kw__Decimal128:
902
903 // struct-or-union-specifier
904 case tok::kw_struct:
905 case tok::kw_union:
906 // enum-specifier
907 case tok::kw_enum:
908
909 // type-qualifier
910 case tok::kw_const:
911 case tok::kw_volatile:
912 case tok::kw_restrict:
Steve Naroff7cbb1462007-07-31 12:34:36 +0000913
914 // GNU typeof support.
915 case tok::kw_typeof:
Chris Lattner4b009652007-07-25 00:24:17 +0000916
917 // function-specifier
918 case tok::kw_inline:
Chris Lattnere35d2582007-08-09 16:40:21 +0000919
920 // attributes.
921 case tok::kw___attribute:
Chris Lattner4b009652007-07-25 00:24:17 +0000922 return true;
923
924 // typedef-name
925 case tok::identifier:
926 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000927 }
928}
929
930
931/// ParseTypeQualifierListOpt
932/// type-qualifier-list: [C99 6.7.5]
933/// type-qualifier
934/// [GNU] attributes
935/// type-qualifier-list type-qualifier
936/// [GNU] type-qualifier-list attributes
937///
938void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
939 while (1) {
940 int isInvalid = false;
941 const char *PrevSpec = 0;
942 SourceLocation Loc = Tok.getLocation();
943
944 switch (Tok.getKind()) {
945 default:
946 // If this is not a type-qualifier token, we're done reading type
947 // qualifiers. First verify that DeclSpec's are consistent.
948 DS.Finish(Diags, getLang());
949 return;
950 case tok::kw_const:
951 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
952 getLang())*2;
953 break;
954 case tok::kw_volatile:
955 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
956 getLang())*2;
957 break;
958 case tok::kw_restrict:
959 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
960 getLang())*2;
961 break;
962 case tok::kw___attribute:
963 DS.AddAttributes(ParseAttributes());
964 continue; // do *not* consume the next token!
965 }
966
967 // If the specifier combination wasn't legal, issue a diagnostic.
968 if (isInvalid) {
969 assert(PrevSpec && "Method did not return previous specifier!");
970 if (isInvalid == 1) // Error.
971 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
972 else // extwarn.
973 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
974 }
975 ConsumeToken();
976 }
977}
978
979
980/// ParseDeclarator - Parse and verify a newly-initialized declarator.
981///
982void Parser::ParseDeclarator(Declarator &D) {
983 /// This implements the 'declarator' production in the C grammar, then checks
984 /// for well-formedness and issues diagnostics.
985 ParseDeclaratorInternal(D);
986
987 // TODO: validate D.
988
989}
990
991/// ParseDeclaratorInternal
992/// declarator: [C99 6.7.5]
993/// pointer[opt] direct-declarator
994/// [C++] '&' declarator [C++ 8p4, dcl.decl]
995/// [GNU] '&' restrict[opt] attributes[opt] declarator
996///
997/// pointer: [C99 6.7.5]
998/// '*' type-qualifier-list[opt]
999/// '*' type-qualifier-list[opt] pointer
1000///
1001void Parser::ParseDeclaratorInternal(Declarator &D) {
1002 tok::TokenKind Kind = Tok.getKind();
1003
1004 // Not a pointer or C++ reference.
1005 if (Kind != tok::star && !(Kind == tok::amp && getLang().CPlusPlus))
1006 return ParseDirectDeclarator(D);
1007
1008 // Otherwise, '*' -> pointer or '&' -> reference.
1009 SourceLocation Loc = ConsumeToken(); // Eat the * or &.
1010
1011 if (Kind == tok::star) {
1012 // Is a pointer
1013 DeclSpec DS;
1014
1015 ParseTypeQualifierListOpt(DS);
1016
1017 // Recursively parse the declarator.
1018 ParseDeclaratorInternal(D);
1019
1020 // Remember that we parsed a pointer type, and remember the type-quals.
1021 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc));
1022 } else {
1023 // Is a reference
1024 DeclSpec DS;
1025
1026 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1027 // cv-qualifiers are introduced through the use of a typedef or of a
1028 // template type argument, in which case the cv-qualifiers are ignored.
1029 //
1030 // [GNU] Retricted references are allowed.
1031 // [GNU] Attributes on references are allowed.
1032 ParseTypeQualifierListOpt(DS);
1033
1034 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1035 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1036 Diag(DS.getConstSpecLoc(),
1037 diag::err_invalid_reference_qualifier_application,
1038 "const");
1039 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1040 Diag(DS.getVolatileSpecLoc(),
1041 diag::err_invalid_reference_qualifier_application,
1042 "volatile");
1043 }
1044
1045 // Recursively parse the declarator.
1046 ParseDeclaratorInternal(D);
1047
1048 // Remember that we parsed a reference type. It doesn't have type-quals.
1049 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc));
1050 }
1051}
1052
1053/// ParseDirectDeclarator
1054/// direct-declarator: [C99 6.7.5]
1055/// identifier
1056/// '(' declarator ')'
1057/// [GNU] '(' attributes declarator ')'
1058/// [C90] direct-declarator '[' constant-expression[opt] ']'
1059/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1060/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1061/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1062/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1063/// direct-declarator '(' parameter-type-list ')'
1064/// direct-declarator '(' identifier-list[opt] ')'
1065/// [GNU] direct-declarator '(' parameter-forward-declarations
1066/// parameter-type-list[opt] ')'
1067///
1068void Parser::ParseDirectDeclarator(Declarator &D) {
1069 // Parse the first direct-declarator seen.
1070 if (Tok.getKind() == tok::identifier && D.mayHaveIdentifier()) {
1071 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1072 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1073 ConsumeToken();
1074 } else if (Tok.getKind() == tok::l_paren) {
1075 // direct-declarator: '(' declarator ')'
1076 // direct-declarator: '(' attributes declarator ')'
1077 // Example: 'char (*X)' or 'int (*XX)(void)'
1078 ParseParenDeclarator(D);
1079 } else if (D.mayOmitIdentifier()) {
1080 // This could be something simple like "int" (in which case the declarator
1081 // portion is empty), if an abstract-declarator is allowed.
1082 D.SetIdentifier(0, Tok.getLocation());
1083 } else {
1084 // Expected identifier or '('.
1085 Diag(Tok, diag::err_expected_ident_lparen);
1086 D.SetIdentifier(0, Tok.getLocation());
1087 }
1088
1089 assert(D.isPastIdentifier() &&
1090 "Haven't past the location of the identifier yet?");
1091
1092 while (1) {
1093 if (Tok.getKind() == tok::l_paren) {
1094 ParseParenDeclarator(D);
1095 } else if (Tok.getKind() == tok::l_square) {
1096 ParseBracketDeclarator(D);
1097 } else {
1098 break;
1099 }
1100 }
1101}
1102
1103/// ParseParenDeclarator - We parsed the declarator D up to a paren. This may
1104/// either be before the identifier (in which case these are just grouping
1105/// parens for precedence) or it may be after the identifier, in which case
1106/// these are function arguments.
1107///
1108/// This method also handles this portion of the grammar:
1109/// parameter-type-list: [C99 6.7.5]
1110/// parameter-list
1111/// parameter-list ',' '...'
1112///
1113/// parameter-list: [C99 6.7.5]
1114/// parameter-declaration
1115/// parameter-list ',' parameter-declaration
1116///
1117/// parameter-declaration: [C99 6.7.5]
1118/// declaration-specifiers declarator
1119/// [GNU] declaration-specifiers declarator attributes
1120/// declaration-specifiers abstract-declarator[opt]
1121/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
1122///
1123/// identifier-list: [C99 6.7.5]
1124/// identifier
1125/// identifier-list ',' identifier
1126///
1127void Parser::ParseParenDeclarator(Declarator &D) {
1128 SourceLocation StartLoc = ConsumeParen();
1129
1130 // If we haven't past the identifier yet (or where the identifier would be
1131 // stored, if this is an abstract declarator), then this is probably just
1132 // grouping parens.
1133 if (!D.isPastIdentifier()) {
1134 // Okay, this is probably a grouping paren. However, if this could be an
1135 // abstract-declarator, then this could also be the start of function
1136 // arguments (consider 'void()').
1137 bool isGrouping;
1138
1139 if (!D.mayOmitIdentifier()) {
1140 // If this can't be an abstract-declarator, this *must* be a grouping
1141 // paren, because we haven't seen the identifier yet.
1142 isGrouping = true;
1143 } else if (Tok.getKind() == tok::r_paren || // 'int()' is a function.
1144 isDeclarationSpecifier()) { // 'int(int)' is a function.
1145 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1146 // considered to be a type, not a K&R identifier-list.
1147 isGrouping = false;
1148 } else {
1149 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1150 isGrouping = true;
1151 }
1152
1153 // If this is a grouping paren, handle:
1154 // direct-declarator: '(' declarator ')'
1155 // direct-declarator: '(' attributes declarator ')'
1156 if (isGrouping) {
1157 if (Tok.getKind() == tok::kw___attribute)
1158 D.AddAttributes(ParseAttributes());
1159
1160 ParseDeclaratorInternal(D);
1161 // Match the ')'.
1162 MatchRHSPunctuation(tok::r_paren, StartLoc);
1163 return;
1164 }
1165
1166 // Okay, if this wasn't a grouping paren, it must be the start of a function
1167 // argument list. Recognize that this declarator will never have an
1168 // identifier (and remember where it would have been), then fall through to
1169 // the handling of argument lists.
1170 D.SetIdentifier(0, Tok.getLocation());
1171 }
1172
1173 // Okay, this is the parameter list of a function definition, or it is an
1174 // identifier list of a K&R-style function.
1175 bool IsVariadic;
1176 bool HasPrototype;
1177 bool ErrorEmitted = false;
1178
1179 // Build up an array of information about the parsed arguments.
1180 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1181 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1182
1183 if (Tok.getKind() == tok::r_paren) {
1184 // int() -> no prototype, no '...'.
1185 IsVariadic = false;
1186 HasPrototype = false;
1187 } else if (Tok.getKind() == tok::identifier &&
1188 // K&R identifier lists can't have typedefs as identifiers, per
1189 // C99 6.7.5.3p11.
1190 !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1191 // Identifier list. Note that '(' identifier-list ')' is only allowed for
1192 // normal declarators, not for abstract-declarators.
1193 assert(D.isPastIdentifier() && "Identifier (if present) must be passed!");
1194
1195 // If there was no identifier specified, either we are in an
1196 // abstract-declarator, or we are in a parameter declarator which was found
1197 // to be abstract. In abstract-declarators, identifier lists are not valid,
1198 // diagnose this.
1199 if (!D.getIdentifier())
1200 Diag(Tok, diag::ext_ident_list_in_param);
1201
1202 // Remember this identifier in ParamInfo.
1203 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1204 Tok.getLocation(), 0));
1205
1206 ConsumeToken();
1207 while (Tok.getKind() == tok::comma) {
1208 // Eat the comma.
1209 ConsumeToken();
1210
1211 if (Tok.getKind() != tok::identifier) {
1212 Diag(Tok, diag::err_expected_ident);
1213 ErrorEmitted = true;
1214 break;
1215 }
1216
1217 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1218
1219 // Verify that the argument identifier has not already been mentioned.
1220 if (!ParamsSoFar.insert(ParmII)) {
1221 Diag(Tok.getLocation(), diag::err_param_redefinition,ParmII->getName());
1222 ParmII = 0;
1223 }
1224
1225 // Remember this identifier in ParamInfo.
1226 if (ParmII)
1227 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1228 Tok.getLocation(), 0));
1229
1230 // Eat the identifier.
1231 ConsumeToken();
1232 }
1233
1234 // K&R 'prototype'.
1235 IsVariadic = false;
1236 HasPrototype = false;
1237 } else {
1238 // Finally, a normal, non-empty parameter type list.
1239
1240 // Enter function-declaration scope, limiting any declarators for struct
1241 // tags to the function prototype scope.
1242 // FIXME: is this needed?
1243 EnterScope(0);
1244
1245 IsVariadic = false;
1246 while (1) {
1247 if (Tok.getKind() == tok::ellipsis) {
1248 IsVariadic = true;
1249
1250 // Check to see if this is "void(...)" which is not allowed.
1251 if (ParamInfo.empty()) {
1252 // Otherwise, parse parameter type list. If it starts with an
1253 // ellipsis, diagnose the malformed function.
1254 Diag(Tok, diag::err_ellipsis_first_arg);
1255 IsVariadic = false; // Treat this like 'void()'.
1256 }
1257
1258 // Consume the ellipsis.
1259 ConsumeToken();
1260 break;
1261 }
1262
1263 // Parse the declaration-specifiers.
1264 DeclSpec DS;
1265 ParseDeclarationSpecifiers(DS);
1266
1267 // Parse the declarator. This is "PrototypeContext", because we must
1268 // accept either 'declarator' or 'abstract-declarator' here.
1269 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1270 ParseDeclarator(ParmDecl);
1271
1272 // Parse GNU attributes, if present.
1273 if (Tok.getKind() == tok::kw___attribute)
1274 ParmDecl.AddAttributes(ParseAttributes());
1275
1276 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1277 // NOTE: we could trivially allow 'int foo(auto int X)' if we wanted.
1278 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1279 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1280 Diag(DS.getStorageClassSpecLoc(),
1281 diag::err_invalid_storage_class_in_func_decl);
1282 DS.ClearStorageClassSpecs();
1283 }
1284 if (DS.isThreadSpecified()) {
1285 Diag(DS.getThreadSpecLoc(),
1286 diag::err_invalid_storage_class_in_func_decl);
1287 DS.ClearStorageClassSpecs();
1288 }
1289
1290 // Inform the actions module about the parameter declarator, so it gets
1291 // added to the current scope.
1292 Action::TypeResult ParamTy =
1293 Actions.ParseParamDeclaratorType(CurScope, ParmDecl);
1294
1295 // Remember this parsed parameter in ParamInfo.
1296 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1297
1298 // Verify that the argument identifier has not already been mentioned.
1299 if (ParmII && !ParamsSoFar.insert(ParmII)) {
1300 Diag(ParmDecl.getIdentifierLoc(), diag::err_param_redefinition,
1301 ParmII->getName());
1302 ParmII = 0;
1303 }
1304
1305 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1306 ParmDecl.getIdentifierLoc(),
1307 ParamTy.Val));
1308
1309 // If the next token is a comma, consume it and keep reading arguments.
1310 if (Tok.getKind() != tok::comma) break;
1311
1312 // Consume the comma.
1313 ConsumeToken();
1314 }
1315
1316 HasPrototype = true;
1317
1318 // Leave prototype scope.
1319 ExitScope();
1320 }
1321
1322 // Remember that we parsed a function type, and remember the attributes.
1323 if (!ErrorEmitted)
1324 D.AddTypeInfo(DeclaratorChunk::getFunction(HasPrototype, IsVariadic,
1325 &ParamInfo[0], ParamInfo.size(),
1326 StartLoc));
1327
1328 // If we have the closing ')', eat it and we're done.
1329 if (Tok.getKind() == tok::r_paren) {
1330 ConsumeParen();
1331 } else {
1332 // If an error happened earlier parsing something else in the proto, don't
1333 // issue another error.
1334 if (!ErrorEmitted)
1335 Diag(Tok, diag::err_expected_rparen);
1336 SkipUntil(tok::r_paren);
1337 }
1338}
1339
1340
1341/// [C90] direct-declarator '[' constant-expression[opt] ']'
1342/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1343/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1344/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1345/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1346void Parser::ParseBracketDeclarator(Declarator &D) {
1347 SourceLocation StartLoc = ConsumeBracket();
1348
1349 // If valid, this location is the position where we read the 'static' keyword.
1350 SourceLocation StaticLoc;
1351 if (Tok.getKind() == tok::kw_static)
1352 StaticLoc = ConsumeToken();
1353
1354 // If there is a type-qualifier-list, read it now.
1355 DeclSpec DS;
1356 ParseTypeQualifierListOpt(DS);
1357
1358 // If we haven't already read 'static', check to see if there is one after the
1359 // type-qualifier-list.
1360 if (!StaticLoc.isValid() && Tok.getKind() == tok::kw_static)
1361 StaticLoc = ConsumeToken();
1362
1363 // Handle "direct-declarator [ type-qual-list[opt] * ]".
1364 bool isStar = false;
1365 ExprResult NumElements(false);
1366 if (Tok.getKind() == tok::star) {
1367 // Remember the '*' token, in case we have to un-get it.
1368 Token StarTok = Tok;
1369 ConsumeToken();
1370
1371 // Check that the ']' token is present to avoid incorrectly parsing
1372 // expressions starting with '*' as [*].
1373 if (Tok.getKind() == tok::r_square) {
1374 if (StaticLoc.isValid())
1375 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1376 StaticLoc = SourceLocation(); // Drop the static.
1377 isStar = true;
1378 } else {
1379 // Otherwise, the * must have been some expression (such as '*ptr') that
1380 // started an assignment-expr. We already consumed the token, but now we
1381 // need to reparse it. This handles cases like 'X[*p + 4]'
1382 NumElements = ParseAssignmentExpressionWithLeadingStar(StarTok);
1383 }
1384 } else if (Tok.getKind() != tok::r_square) {
1385 // Parse the assignment-expression now.
1386 NumElements = ParseAssignmentExpression();
1387 }
1388
1389 // If there was an error parsing the assignment-expression, recover.
1390 if (NumElements.isInvalid) {
1391 // If the expression was invalid, skip it.
1392 SkipUntil(tok::r_square);
1393 return;
1394 }
1395
1396 MatchRHSPunctuation(tok::r_square, StartLoc);
1397
1398 // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1399 // it was not a constant expression.
1400 if (!getLang().C99) {
1401 // TODO: check C90 array constant exprness.
1402 if (isStar || StaticLoc.isValid() ||
1403 0/*TODO: NumElts is not a C90 constantexpr */)
1404 Diag(StartLoc, diag::ext_c99_array_usage);
1405 }
1406
1407 // Remember that we parsed a pointer type, and remember the type-quals.
1408 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1409 StaticLoc.isValid(), isStar,
1410 NumElements.Val, StartLoc));
1411}
1412
Steve Naroff7cbb1462007-07-31 12:34:36 +00001413/// [GNU] typeof-specifier:
1414/// typeof ( expressions )
1415/// typeof ( type-name )
1416///
1417void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1418 assert(Tok.getKind() == tok::kw_typeof && "Not a typeof specifier");
Steve Naroff14bbce82007-08-02 02:53:48 +00001419 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
Steve Naroff7cbb1462007-07-31 12:34:36 +00001420 SourceLocation StartLoc = ConsumeToken();
1421
1422 if (Tok.getKind() != tok::l_paren) {
Steve Naroff14bbce82007-08-02 02:53:48 +00001423 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
1424 return;
Steve Naroff7cbb1462007-07-31 12:34:36 +00001425 }
1426 SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
1427
1428 if (isTypeSpecifierQualifier()) {
1429 TypeTy *Ty = ParseTypeName();
1430
Steve Naroff4c255ab2007-07-31 23:56:32 +00001431 assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
1432
Steve Naroff14bbce82007-08-02 02:53:48 +00001433 if (Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001434 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001435 return;
1436 }
1437 RParenLoc = ConsumeParen();
1438 const char *PrevSpec = 0;
1439 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1440 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
1441 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001442 } else { // we have an expression.
1443 ExprResult Result = ParseExpression();
Steve Naroff4c255ab2007-07-31 23:56:32 +00001444
Steve Naroff14bbce82007-08-02 02:53:48 +00001445 if (Result.isInvalid || Tok.getKind() != tok::r_paren) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00001446 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00001447 return;
1448 }
1449 RParenLoc = ConsumeParen();
1450 const char *PrevSpec = 0;
1451 // Check for duplicate type specifiers (e.g. "int typeof(int)").
1452 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1453 Result.Val))
1454 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001455 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001456}
1457