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