blob: c40e7496592643cd9db44499f239f2f3d4be39b2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 SourceLocation Loc = Tok.getLocation();
300 ParseDeclarationSpecifiers(DS);
301
302 // Validate declspec for type-name.
303 unsigned Specs = DS.getParsedSpecifiers();
304 if (Specs == DeclSpec::PQ_None)
305 Diag(Tok, diag::err_typename_requires_specqual);
306
307 // Issue diagnostic and remove storage class if present.
308 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
309 if (DS.getStorageClassSpecLoc().isValid())
310 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
311 else
312 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
313 DS.ClearStorageClassSpecs();
314 }
315
316 // Issue diagnostic and remove function specfier if present.
317 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
318 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
319 DS.ClearFunctionSpecs();
320 }
321}
322
323/// ParseDeclarationSpecifiers
324/// declaration-specifiers: [C99 6.7]
325/// storage-class-specifier declaration-specifiers[opt]
326/// type-specifier declaration-specifiers[opt]
327/// type-qualifier declaration-specifiers[opt]
328/// [C99] function-specifier declaration-specifiers[opt]
329/// [GNU] attributes declaration-specifiers[opt]
330///
331/// storage-class-specifier: [C99 6.7.1]
332/// 'typedef'
333/// 'extern'
334/// 'static'
335/// 'auto'
336/// 'register'
337/// [GNU] '__thread'
338/// type-specifier: [C99 6.7.2]
339/// 'void'
340/// 'char'
341/// 'short'
342/// 'int'
343/// 'long'
344/// 'float'
345/// 'double'
346/// 'signed'
347/// 'unsigned'
348/// struct-or-union-specifier
349/// enum-specifier
350/// typedef-name
351/// [C++] 'bool'
352/// [C99] '_Bool'
353/// [C99] '_Complex'
354/// [C99] '_Imaginary' // Removed in TC2?
355/// [GNU] '_Decimal32'
356/// [GNU] '_Decimal64'
357/// [GNU] '_Decimal128'
358/// [GNU] typeof-specifier [TODO]
359/// [OBJC] class-name objc-protocol-refs[opt] [TODO]
360/// [OBJC] typedef-name objc-protocol-refs [TODO]
361/// [OBJC] objc-protocol-refs [TODO]
362/// type-qualifier:
363/// 'const'
364/// 'volatile'
365/// [C99] 'restrict'
366/// function-specifier: [C99 6.7.4]
367/// [C99] 'inline'
368///
369void Parser::ParseDeclarationSpecifiers(DeclSpec &DS) {
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
485 // type-qualifier
486 case tok::kw_const:
487 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
488 getLang())*2;
489 break;
490 case tok::kw_volatile:
491 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
492 getLang())*2;
493 break;
494 case tok::kw_restrict:
495 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
496 getLang())*2;
497 break;
498
499 // function-specifier
500 case tok::kw_inline:
501 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
502 break;
503 }
504 // If the specifier combination wasn't legal, issue a diagnostic.
505 if (isInvalid) {
506 assert(PrevSpec && "Method did not return previous specifier!");
507 if (isInvalid == 1) // Error.
508 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
509 else // extwarn.
510 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
511 }
512 ConsumeToken();
513 }
514}
515
516/// ParseTag - Parse "struct-or-union-or-class-or-enum identifier[opt]", where
517/// the first token has already been read and has been turned into an instance
518/// of DeclSpec::TST (TagType). This returns true if there is an error parsing,
519/// otherwise it returns false and fills in Decl.
520bool Parser::ParseTag(DeclTy *&Decl, unsigned TagType, SourceLocation StartLoc){
521 AttributeList *Attr = 0;
522 // If attributes exist after tag, parse them.
523 if (Tok.getKind() == tok::kw___attribute)
524 Attr = ParseAttributes();
525
526 // Must have either 'struct name' or 'struct {...}'.
527 if (Tok.getKind() != tok::identifier &&
528 Tok.getKind() != tok::l_brace) {
529 Diag(Tok, diag::err_expected_ident_lbrace);
530 // TODO: better error recovery here.
531 return true;
532 }
533
534 // If an identifier is present, consume and remember it.
535 IdentifierInfo *Name = 0;
536 SourceLocation NameLoc;
537 if (Tok.getKind() == tok::identifier) {
538 Name = Tok.getIdentifierInfo();
539 NameLoc = ConsumeToken();
540 }
541
542 // There are three options here. If we have 'struct foo;', then this is a
543 // forward declaration. If we have 'struct foo {...' then this is a
544 // definition. Otherwise we have something like 'struct foo xyz', a reference.
545 //
546 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
547 // struct foo {..}; void bar() { struct foo; } <- new foo in bar.
548 // struct foo {..}; void bar() { struct foo x; } <- use of old foo.
549 //
550 Action::TagKind TK;
551 if (Tok.getKind() == tok::l_brace)
552 TK = Action::TK_Definition;
553 else if (Tok.getKind() == tok::semi)
554 TK = Action::TK_Declaration;
555 else
556 TK = Action::TK_Reference;
557 Decl = Actions.ParseTag(CurScope, TagType, TK, StartLoc, Name, NameLoc, Attr);
558 return false;
559}
560
561
562/// ParseStructUnionSpecifier
563/// struct-or-union-specifier: [C99 6.7.2.1]
564/// struct-or-union identifier[opt] '{' struct-contents '}'
565/// struct-or-union identifier
566/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
567/// '}' attributes[opt]
568/// [GNU] struct-or-union attributes[opt] identifier
569/// struct-or-union:
570/// 'struct'
571/// 'union'
572///
573void Parser::ParseStructUnionSpecifier(DeclSpec &DS) {
574 assert((Tok.getKind() == tok::kw_struct ||
575 Tok.getKind() == tok::kw_union) && "Not a struct/union specifier");
576 DeclSpec::TST TagType =
577 Tok.getKind() == tok::kw_union ? DeclSpec::TST_union : DeclSpec::TST_struct;
578 SourceLocation StartLoc = ConsumeToken();
579
580 // Parse the tag portion of this.
581 DeclTy *TagDecl;
582 if (ParseTag(TagDecl, TagType, StartLoc))
583 return;
584
585 // If there is a body, parse it and inform the actions module.
586 if (Tok.getKind() == tok::l_brace)
587 ParseStructUnionBody(StartLoc, TagType, TagDecl);
588
589 const char *PrevSpec = 0;
590 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
591 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
592}
593
594
595/// ParseStructUnionBody
596/// struct-contents:
597/// struct-declaration-list
598/// [EXT] empty
599/// [GNU] "struct-declaration-list" without terminatoring ';'
600/// struct-declaration-list:
601/// struct-declaration
602/// struct-declaration-list struct-declaration
603/// [OBC] '@' 'defs' '(' class-name ')' [TODO]
604/// struct-declaration:
605/// specifier-qualifier-list struct-declarator-list ';'
606/// [GNU] __extension__ struct-declaration
607/// [GNU] specifier-qualifier-list ';'
608/// struct-declarator-list:
609/// struct-declarator
610/// struct-declarator-list ',' struct-declarator
611/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
612/// struct-declarator:
613/// declarator
614/// [GNU] declarator attributes[opt]
615/// declarator[opt] ':' constant-expression
616/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
617///
618void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
619 unsigned TagType, DeclTy *TagDecl) {
620 SourceLocation LBraceLoc = ConsumeBrace();
621
622 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
623 // C++.
624 if (Tok.getKind() == tok::r_brace)
625 Diag(Tok, diag::ext_empty_struct_union_enum,
626 DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
627
628 llvm::SmallVector<DeclTy*, 32> FieldDecls;
629
630 // While we still have something to read, read the declarations in the struct.
631 while (Tok.getKind() != tok::r_brace &&
632 Tok.getKind() != tok::eof) {
633 // Each iteration of this loop reads one struct-declaration.
634
635 // Check for extraneous top-level semicolon.
636 if (Tok.getKind() == tok::semi) {
637 Diag(Tok, diag::ext_extra_struct_semi);
638 ConsumeToken();
639 continue;
640 }
641
642 // FIXME: When __extension__ is specified, disable extension diagnostics.
643 if (Tok.getKind() == tok::kw___extension__)
644 ConsumeToken();
645
646 // Parse the common specifier-qualifiers-list piece.
647 DeclSpec DS;
648 SourceLocation SpecQualLoc = Tok.getLocation();
649 ParseSpecifierQualifierList(DS);
650 // TODO: Does specifier-qualifier list correctly check that *something* is
651 // specified?
652
653 // If there are no declarators, issue a warning.
654 if (Tok.getKind() == tok::semi) {
655 Diag(SpecQualLoc, diag::w_no_declarators);
656 ConsumeToken();
657 continue;
658 }
659
660 // Read struct-declarators until we find the semicolon.
661 Declarator DeclaratorInfo(DS, Declarator::MemberContext);
662
663 while (1) {
664 /// struct-declarator: declarator
665 /// struct-declarator: declarator[opt] ':' constant-expression
666 if (Tok.getKind() != tok::colon)
667 ParseDeclarator(DeclaratorInfo);
668
669 ExprTy *BitfieldSize = 0;
670 if (Tok.getKind() == tok::colon) {
671 ConsumeToken();
672 ExprResult Res = ParseConstantExpression();
673 if (Res.isInvalid) {
674 SkipUntil(tok::semi, true, true);
675 } else {
676 BitfieldSize = Res.Val;
677 }
678 }
679
680 // If attributes exist after the declarator, parse them.
681 if (Tok.getKind() == tok::kw___attribute)
682 DeclaratorInfo.AddAttributes(ParseAttributes());
683
684 // Install the declarator into the current TagDecl.
685 DeclTy *Field = Actions.ParseField(CurScope, TagDecl, SpecQualLoc,
686 DeclaratorInfo, BitfieldSize);
687 FieldDecls.push_back(Field);
688
689 // If we don't have a comma, it is either the end of the list (a ';')
690 // or an error, bail out.
691 if (Tok.getKind() != tok::comma)
692 break;
693
694 // Consume the comma.
695 ConsumeToken();
696
697 // Parse the next declarator.
698 DeclaratorInfo.clear();
699
700 // Attributes are only allowed on the second declarator.
701 if (Tok.getKind() == tok::kw___attribute)
702 DeclaratorInfo.AddAttributes(ParseAttributes());
703 }
704
705 if (Tok.getKind() == tok::semi) {
706 ConsumeToken();
707 } else if (Tok.getKind() == tok::r_brace) {
708 Diag(Tok.getLocation(), diag::ext_expected_semi_decl_list);
709 break;
710 } else {
711 Diag(Tok, diag::err_expected_semi_decl_list);
712 // Skip to end of block or statement
713 SkipUntil(tok::r_brace, true, true);
714 }
715 }
716
717 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
718
719 Actions.ParseRecordBody(RecordLoc, TagDecl, &FieldDecls[0],FieldDecls.size());
720
721 AttributeList *AttrList = 0;
722 // If attributes exist after struct contents, parse them.
723 if (Tok.getKind() == tok::kw___attribute)
724 AttrList = ParseAttributes(); // FIXME: where should I put them?
725}
726
727
728/// ParseEnumSpecifier
729/// enum-specifier: [C99 6.7.2.2]
730/// 'enum' identifier[opt] '{' enumerator-list '}'
731/// [C99] 'enum' identifier[opt] '{' enumerator-list ',' '}'
732/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
733/// '}' attributes[opt]
734/// 'enum' identifier
735/// [GNU] 'enum' attributes[opt] identifier
736void Parser::ParseEnumSpecifier(DeclSpec &DS) {
737 assert(Tok.getKind() == tok::kw_enum && "Not an enum specifier");
738 SourceLocation StartLoc = ConsumeToken();
739
740 // Parse the tag portion of this.
741 DeclTy *TagDecl;
742 if (ParseTag(TagDecl, DeclSpec::TST_enum, StartLoc))
743 return;
744
745 if (Tok.getKind() == tok::l_brace)
746 ParseEnumBody(StartLoc, TagDecl);
747
748 // TODO: semantic analysis on the declspec for enums.
749 const char *PrevSpec = 0;
750 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
751 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
752}
753
754/// ParseEnumBody - Parse a {} enclosed enumerator-list.
755/// enumerator-list:
756/// enumerator
757/// enumerator-list ',' enumerator
758/// enumerator:
759/// enumeration-constant
760/// enumeration-constant '=' constant-expression
761/// enumeration-constant:
762/// identifier
763///
764void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
765 SourceLocation LBraceLoc = ConsumeBrace();
766
767 if (Tok.getKind() == tok::r_brace)
768 Diag(Tok, diag::ext_empty_struct_union_enum, "enum");
769
770 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
771
772 DeclTy *LastEnumConstDecl = 0;
773
774 // Parse the enumerator-list.
775 while (Tok.getKind() == tok::identifier) {
776 IdentifierInfo *Ident = Tok.getIdentifierInfo();
777 SourceLocation IdentLoc = ConsumeToken();
778
779 SourceLocation EqualLoc;
780 ExprTy *AssignedVal = 0;
781 if (Tok.getKind() == tok::equal) {
782 EqualLoc = ConsumeToken();
783 ExprResult Res = ParseConstantExpression();
784 if (Res.isInvalid)
785 SkipUntil(tok::comma, tok::r_brace, true, true);
786 else
787 AssignedVal = Res.Val;
788 }
789
790 // Install the enumerator constant into EnumDecl.
791 DeclTy *EnumConstDecl = Actions.ParseEnumConstant(CurScope, EnumDecl,
792 LastEnumConstDecl,
793 IdentLoc, Ident,
794 EqualLoc, AssignedVal);
795 EnumConstantDecls.push_back(EnumConstDecl);
796 LastEnumConstDecl = EnumConstDecl;
797
798 if (Tok.getKind() != tok::comma)
799 break;
800 SourceLocation CommaLoc = ConsumeToken();
801
802 if (Tok.getKind() != tok::identifier && !getLang().C99)
803 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
804 }
805
806 // Eat the }.
807 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
808
809 Actions.ParseEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
810 EnumConstantDecls.size());
811
812 DeclTy *AttrList = 0;
813 // If attributes exist after the identifier list, parse them.
814 if (Tok.getKind() == tok::kw___attribute)
815 AttrList = ParseAttributes(); // FIXME: where do they do?
816}
817
818/// isTypeSpecifierQualifier - Return true if the current token could be the
819/// start of a specifier-qualifier-list.
820bool Parser::isTypeSpecifierQualifier() const {
821 switch (Tok.getKind()) {
822 default: return false;
823 // GNU attributes support.
824 case tok::kw___attribute:
825 // type-specifiers
826 case tok::kw_short:
827 case tok::kw_long:
828 case tok::kw_signed:
829 case tok::kw_unsigned:
830 case tok::kw__Complex:
831 case tok::kw__Imaginary:
832 case tok::kw_void:
833 case tok::kw_char:
834 case tok::kw_int:
835 case tok::kw_float:
836 case tok::kw_double:
837 case tok::kw__Bool:
838 case tok::kw__Decimal32:
839 case tok::kw__Decimal64:
840 case tok::kw__Decimal128:
841
842 // struct-or-union-specifier
843 case tok::kw_struct:
844 case tok::kw_union:
845 // enum-specifier
846 case tok::kw_enum:
847
848 // type-qualifier
849 case tok::kw_const:
850 case tok::kw_volatile:
851 case tok::kw_restrict:
852 return true;
853
854 // typedef-name
855 case tok::identifier:
856 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
857
858 // TODO: Attributes.
859 }
860}
861
862/// isDeclarationSpecifier() - Return true if the current token is part of a
863/// declaration specifier.
864bool Parser::isDeclarationSpecifier() const {
865 switch (Tok.getKind()) {
866 default: return false;
867 // storage-class-specifier
868 case tok::kw_typedef:
869 case tok::kw_extern:
870 case tok::kw_static:
871 case tok::kw_auto:
872 case tok::kw_register:
873 case tok::kw___thread:
874
875 // 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
903 // function-specifier
904 case tok::kw_inline:
905 return true;
906
907 // typedef-name
908 case tok::identifier:
909 return Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope) != 0;
910 // TODO: Attributes.
911 }
912}
913
914
915/// ParseTypeQualifierListOpt
916/// type-qualifier-list: [C99 6.7.5]
917/// type-qualifier
918/// [GNU] attributes
919/// type-qualifier-list type-qualifier
920/// [GNU] type-qualifier-list attributes
921///
922void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
923 while (1) {
924 int isInvalid = false;
925 const char *PrevSpec = 0;
926 SourceLocation Loc = Tok.getLocation();
927
928 switch (Tok.getKind()) {
929 default:
930 // If this is not a type-qualifier token, we're done reading type
931 // qualifiers. First verify that DeclSpec's are consistent.
932 DS.Finish(Diags, getLang());
933 return;
934 case tok::kw_const:
935 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
936 getLang())*2;
937 break;
938 case tok::kw_volatile:
939 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
940 getLang())*2;
941 break;
942 case tok::kw_restrict:
943 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
944 getLang())*2;
945 break;
946 case tok::kw___attribute:
947 DS.AddAttributes(ParseAttributes());
948 continue; // do *not* consume the next token!
949 }
950
951 // If the specifier combination wasn't legal, issue a diagnostic.
952 if (isInvalid) {
953 assert(PrevSpec && "Method did not return previous specifier!");
954 if (isInvalid == 1) // Error.
955 Diag(Tok, diag::err_invalid_decl_spec_combination, PrevSpec);
956 else // extwarn.
957 Diag(Tok, diag::ext_duplicate_declspec, PrevSpec);
958 }
959 ConsumeToken();
960 }
961}
962
963
964/// ParseDeclarator - Parse and verify a newly-initialized declarator.
965///
966void Parser::ParseDeclarator(Declarator &D) {
967 /// This implements the 'declarator' production in the C grammar, then checks
968 /// for well-formedness and issues diagnostics.
969 ParseDeclaratorInternal(D);
970
971 // TODO: validate D.
972
973}
974
975/// ParseDeclaratorInternal
976/// declarator: [C99 6.7.5]
977/// pointer[opt] direct-declarator
978/// [C++] '&' declarator [C++ 8p4, dcl.decl]
979/// [GNU] '&' restrict[opt] attributes[opt] declarator
980///
981/// pointer: [C99 6.7.5]
982/// '*' type-qualifier-list[opt]
983/// '*' type-qualifier-list[opt] pointer
984///
985void Parser::ParseDeclaratorInternal(Declarator &D) {
986 tok::TokenKind Kind = Tok.getKind();
987
988 // Not a pointer or C++ reference.
989 if (Kind != tok::star && !(Kind == tok::amp && getLang().CPlusPlus))
990 return ParseDirectDeclarator(D);
991
992 // Otherwise, '*' -> pointer or '&' -> reference.
993 SourceLocation Loc = ConsumeToken(); // Eat the * or &.
994
995 if (Kind == tok::star) {
996 // Is a pointer
997 DeclSpec DS;
998
999 ParseTypeQualifierListOpt(DS);
1000
1001 // Recursively parse the declarator.
1002 ParseDeclaratorInternal(D);
1003
1004 // Remember that we parsed a pointer type, and remember the type-quals.
1005 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc));
1006 } else {
1007 // Is a reference
1008 DeclSpec DS;
1009
1010 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1011 // cv-qualifiers are introduced through the use of a typedef or of a
1012 // template type argument, in which case the cv-qualifiers are ignored.
1013 //
1014 // [GNU] Retricted references are allowed.
1015 // [GNU] Attributes on references are allowed.
1016 ParseTypeQualifierListOpt(DS);
1017
1018 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1019 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1020 Diag(DS.getConstSpecLoc(),
1021 diag::err_invalid_reference_qualifier_application,
1022 "const");
1023 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1024 Diag(DS.getVolatileSpecLoc(),
1025 diag::err_invalid_reference_qualifier_application,
1026 "volatile");
1027 }
1028
1029 // Recursively parse the declarator.
1030 ParseDeclaratorInternal(D);
1031
1032 // Remember that we parsed a reference type. It doesn't have type-quals.
1033 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc));
1034 }
1035}
1036
1037/// ParseDirectDeclarator
1038/// direct-declarator: [C99 6.7.5]
1039/// identifier
1040/// '(' declarator ')'
1041/// [GNU] '(' attributes declarator ')'
1042/// [C90] direct-declarator '[' constant-expression[opt] ']'
1043/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1044/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1045/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1046/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1047/// direct-declarator '(' parameter-type-list ')'
1048/// direct-declarator '(' identifier-list[opt] ')'
1049/// [GNU] direct-declarator '(' parameter-forward-declarations
1050/// parameter-type-list[opt] ')'
1051///
1052void Parser::ParseDirectDeclarator(Declarator &D) {
1053 // Parse the first direct-declarator seen.
1054 if (Tok.getKind() == tok::identifier && D.mayHaveIdentifier()) {
1055 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1056 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1057 ConsumeToken();
1058 } else if (Tok.getKind() == tok::l_paren) {
1059 // direct-declarator: '(' declarator ')'
1060 // direct-declarator: '(' attributes declarator ')'
1061 // Example: 'char (*X)' or 'int (*XX)(void)'
1062 ParseParenDeclarator(D);
1063 } else if (D.mayOmitIdentifier()) {
1064 // This could be something simple like "int" (in which case the declarator
1065 // portion is empty), if an abstract-declarator is allowed.
1066 D.SetIdentifier(0, Tok.getLocation());
1067 } else {
1068 // Expected identifier or '('.
1069 Diag(Tok, diag::err_expected_ident_lparen);
1070 D.SetIdentifier(0, Tok.getLocation());
1071 }
1072
1073 assert(D.isPastIdentifier() &&
1074 "Haven't past the location of the identifier yet?");
1075
1076 while (1) {
1077 if (Tok.getKind() == tok::l_paren) {
1078 ParseParenDeclarator(D);
1079 } else if (Tok.getKind() == tok::l_square) {
1080 ParseBracketDeclarator(D);
1081 } else {
1082 break;
1083 }
1084 }
1085}
1086
1087/// ParseParenDeclarator - We parsed the declarator D up to a paren. This may
1088/// either be before the identifier (in which case these are just grouping
1089/// parens for precedence) or it may be after the identifier, in which case
1090/// these are function arguments.
1091///
1092/// This method also handles this portion of the grammar:
1093/// parameter-type-list: [C99 6.7.5]
1094/// parameter-list
1095/// parameter-list ',' '...'
1096///
1097/// parameter-list: [C99 6.7.5]
1098/// parameter-declaration
1099/// parameter-list ',' parameter-declaration
1100///
1101/// parameter-declaration: [C99 6.7.5]
1102/// declaration-specifiers declarator
1103/// [GNU] declaration-specifiers declarator attributes
1104/// declaration-specifiers abstract-declarator[opt]
1105/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
1106///
1107/// identifier-list: [C99 6.7.5]
1108/// identifier
1109/// identifier-list ',' identifier
1110///
1111void Parser::ParseParenDeclarator(Declarator &D) {
1112 SourceLocation StartLoc = ConsumeParen();
1113
1114 // If we haven't past the identifier yet (or where the identifier would be
1115 // stored, if this is an abstract declarator), then this is probably just
1116 // grouping parens.
1117 if (!D.isPastIdentifier()) {
1118 // Okay, this is probably a grouping paren. However, if this could be an
1119 // abstract-declarator, then this could also be the start of function
1120 // arguments (consider 'void()').
1121 bool isGrouping;
1122
1123 if (!D.mayOmitIdentifier()) {
1124 // If this can't be an abstract-declarator, this *must* be a grouping
1125 // paren, because we haven't seen the identifier yet.
1126 isGrouping = true;
1127 } else if (Tok.getKind() == tok::r_paren || // 'int()' is a function.
1128 isDeclarationSpecifier()) { // 'int(int)' is a function.
1129 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1130 // considered to be a type, not a K&R identifier-list.
1131 isGrouping = false;
1132 } else {
1133 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1134 isGrouping = true;
1135 }
1136
1137 // If this is a grouping paren, handle:
1138 // direct-declarator: '(' declarator ')'
1139 // direct-declarator: '(' attributes declarator ')'
1140 if (isGrouping) {
1141 if (Tok.getKind() == tok::kw___attribute)
1142 D.AddAttributes(ParseAttributes());
1143
1144 ParseDeclaratorInternal(D);
1145 // Match the ')'.
1146 MatchRHSPunctuation(tok::r_paren, StartLoc);
1147 return;
1148 }
1149
1150 // Okay, if this wasn't a grouping paren, it must be the start of a function
1151 // argument list. Recognize that this declarator will never have an
1152 // identifier (and remember where it would have been), then fall through to
1153 // the handling of argument lists.
1154 D.SetIdentifier(0, Tok.getLocation());
1155 }
1156
1157 // Okay, this is the parameter list of a function definition, or it is an
1158 // identifier list of a K&R-style function.
1159 bool IsVariadic;
1160 bool HasPrototype;
1161 bool ErrorEmitted = false;
1162
1163 // Build up an array of information about the parsed arguments.
1164 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1165 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1166
1167 if (Tok.getKind() == tok::r_paren) {
1168 // int() -> no prototype, no '...'.
1169 IsVariadic = false;
1170 HasPrototype = false;
1171 } else if (Tok.getKind() == tok::identifier &&
1172 // K&R identifier lists can't have typedefs as identifiers, per
1173 // C99 6.7.5.3p11.
1174 !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1175 // Identifier list. Note that '(' identifier-list ')' is only allowed for
1176 // normal declarators, not for abstract-declarators.
1177 assert(D.isPastIdentifier() && "Identifier (if present) must be passed!");
1178
1179 // If there was no identifier specified, either we are in an
1180 // abstract-declarator, or we are in a parameter declarator which was found
1181 // to be abstract. In abstract-declarators, identifier lists are not valid,
1182 // diagnose this.
1183 if (!D.getIdentifier())
1184 Diag(Tok, diag::ext_ident_list_in_param);
1185
1186 // Remember this identifier in ParamInfo.
1187 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1188 Tok.getLocation(), 0));
1189
1190 ConsumeToken();
1191 while (Tok.getKind() == tok::comma) {
1192 // Eat the comma.
1193 ConsumeToken();
1194
1195 if (Tok.getKind() != tok::identifier) {
1196 Diag(Tok, diag::err_expected_ident);
1197 ErrorEmitted = true;
1198 break;
1199 }
1200
1201 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1202
1203 // Verify that the argument identifier has not already been mentioned.
1204 if (!ParamsSoFar.insert(ParmII)) {
1205 Diag(Tok.getLocation(), diag::err_param_redefinition,ParmII->getName());
1206 ParmII = 0;
1207 }
1208
1209 // Remember this identifier in ParamInfo.
1210 if (ParmII)
1211 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1212 Tok.getLocation(), 0));
1213
1214 // Eat the identifier.
1215 ConsumeToken();
1216 }
1217
1218 // K&R 'prototype'.
1219 IsVariadic = false;
1220 HasPrototype = false;
1221 } else {
1222 // Finally, a normal, non-empty parameter type list.
1223
1224 // Enter function-declaration scope, limiting any declarators for struct
1225 // tags to the function prototype scope.
1226 // FIXME: is this needed?
1227 EnterScope(0);
1228
1229 IsVariadic = false;
1230 while (1) {
1231 if (Tok.getKind() == tok::ellipsis) {
1232 IsVariadic = true;
1233
1234 // Check to see if this is "void(...)" which is not allowed.
1235 if (ParamInfo.empty()) {
1236 // Otherwise, parse parameter type list. If it starts with an
1237 // ellipsis, diagnose the malformed function.
1238 Diag(Tok, diag::err_ellipsis_first_arg);
1239 IsVariadic = false; // Treat this like 'void()'.
1240 }
1241
1242 // Consume the ellipsis.
1243 ConsumeToken();
1244 break;
1245 }
1246
1247 // Parse the declaration-specifiers.
1248 DeclSpec DS;
1249 ParseDeclarationSpecifiers(DS);
1250
1251 // Parse the declarator. This is "PrototypeContext", because we must
1252 // accept either 'declarator' or 'abstract-declarator' here.
1253 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1254 ParseDeclarator(ParmDecl);
1255
1256 // Parse GNU attributes, if present.
1257 if (Tok.getKind() == tok::kw___attribute)
1258 ParmDecl.AddAttributes(ParseAttributes());
1259
1260 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1261 // NOTE: we could trivially allow 'int foo(auto int X)' if we wanted.
1262 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1263 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1264 Diag(DS.getStorageClassSpecLoc(),
1265 diag::err_invalid_storage_class_in_func_decl);
1266 DS.ClearStorageClassSpecs();
1267 }
1268 if (DS.isThreadSpecified()) {
1269 Diag(DS.getThreadSpecLoc(),
1270 diag::err_invalid_storage_class_in_func_decl);
1271 DS.ClearStorageClassSpecs();
1272 }
1273
1274 // Inform the actions module about the parameter declarator, so it gets
1275 // added to the current scope.
1276 Action::TypeResult ParamTy =
1277 Actions.ParseParamDeclaratorType(CurScope, ParmDecl);
1278
1279 // Remember this parsed parameter in ParamInfo.
1280 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1281
1282 // Verify that the argument identifier has not already been mentioned.
1283 if (ParmII && !ParamsSoFar.insert(ParmII)) {
1284 Diag(ParmDecl.getIdentifierLoc(), diag::err_param_redefinition,
1285 ParmII->getName());
1286 ParmII = 0;
1287 }
1288
1289 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1290 ParmDecl.getIdentifierLoc(),
1291 ParamTy.Val));
1292
1293 // If the next token is a comma, consume it and keep reading arguments.
1294 if (Tok.getKind() != tok::comma) break;
1295
1296 // Consume the comma.
1297 ConsumeToken();
1298 }
1299
1300 HasPrototype = true;
1301
1302 // Leave prototype scope.
1303 ExitScope();
1304 }
1305
1306 // Remember that we parsed a function type, and remember the attributes.
1307 if (!ErrorEmitted)
1308 D.AddTypeInfo(DeclaratorChunk::getFunction(HasPrototype, IsVariadic,
1309 &ParamInfo[0], ParamInfo.size(),
1310 StartLoc));
1311
1312 // If we have the closing ')', eat it and we're done.
1313 if (Tok.getKind() == tok::r_paren) {
1314 ConsumeParen();
1315 } else {
1316 // If an error happened earlier parsing something else in the proto, don't
1317 // issue another error.
1318 if (!ErrorEmitted)
1319 Diag(Tok, diag::err_expected_rparen);
1320 SkipUntil(tok::r_paren);
1321 }
1322}
1323
1324
1325/// [C90] direct-declarator '[' constant-expression[opt] ']'
1326/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1327/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1328/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1329/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1330void Parser::ParseBracketDeclarator(Declarator &D) {
1331 SourceLocation StartLoc = ConsumeBracket();
1332
1333 // If valid, this location is the position where we read the 'static' keyword.
1334 SourceLocation StaticLoc;
1335 if (Tok.getKind() == tok::kw_static)
1336 StaticLoc = ConsumeToken();
1337
1338 // If there is a type-qualifier-list, read it now.
1339 DeclSpec DS;
1340 ParseTypeQualifierListOpt(DS);
1341
1342 // If we haven't already read 'static', check to see if there is one after the
1343 // type-qualifier-list.
1344 if (!StaticLoc.isValid() && Tok.getKind() == tok::kw_static)
1345 StaticLoc = ConsumeToken();
1346
1347 // Handle "direct-declarator [ type-qual-list[opt] * ]".
1348 bool isStar = false;
1349 ExprResult NumElements(false);
1350 if (Tok.getKind() == tok::star) {
1351 // Remember the '*' token, in case we have to un-get it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001352 Token StarTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 ConsumeToken();
1354
1355 // Check that the ']' token is present to avoid incorrectly parsing
1356 // expressions starting with '*' as [*].
1357 if (Tok.getKind() == tok::r_square) {
1358 if (StaticLoc.isValid())
1359 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1360 StaticLoc = SourceLocation(); // Drop the static.
1361 isStar = true;
1362 } else {
1363 // Otherwise, the * must have been some expression (such as '*ptr') that
1364 // started an assignment-expr. We already consumed the token, but now we
1365 // need to reparse it. This handles cases like 'X[*p + 4]'
1366 NumElements = ParseAssignmentExpressionWithLeadingStar(StarTok);
1367 }
1368 } else if (Tok.getKind() != tok::r_square) {
1369 // Parse the assignment-expression now.
1370 NumElements = ParseAssignmentExpression();
1371 }
1372
1373 // If there was an error parsing the assignment-expression, recover.
1374 if (NumElements.isInvalid) {
1375 // If the expression was invalid, skip it.
1376 SkipUntil(tok::r_square);
1377 return;
1378 }
1379
1380 MatchRHSPunctuation(tok::r_square, StartLoc);
1381
1382 // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1383 // it was not a constant expression.
1384 if (!getLang().C99) {
1385 // TODO: check C90 array constant exprness.
1386 if (isStar || StaticLoc.isValid() ||
1387 0/*TODO: NumElts is not a C90 constantexpr */)
1388 Diag(StartLoc, diag::ext_c99_array_usage);
1389 }
1390
1391 // Remember that we parsed a pointer type, and remember the type-quals.
1392 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1393 StaticLoc.isValid(), isStar,
1394 NumElements.Val, StartLoc));
1395}
1396