blob: 4280c6050c308dcfab9ff7f01573427bb91dcbb7 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattnera7549902007-08-26 06:24:45 +000016#include "clang/Parse/Scope.h"
Chris Lattnerdaa5c002008-10-20 06:45:43 +000017#include "ExtensionRAIIObject.h"
Sebastian Redl6008ac32008-11-25 22:21:31 +000018#include "AstGuard.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "llvm/ADT/SmallSet.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// C99 6.7: Declarations.
24//===----------------------------------------------------------------------===//
25
26/// ParseTypeName
27/// type-name: [C99 6.7.6]
28/// specifier-qualifier-list abstract-declarator[opt]
Sebastian Redl19fec9d2008-11-21 19:14:01 +000029///
30/// Called type-id in C++.
31/// CXXNewMode is a special flag used by the parser of C++ new-expressions. It
32/// is simply passed on to ActOnTypeName.
33Parser::TypeTy *Parser::ParseTypeName(bool CXXNewMode) {
Chris Lattner4b009652007-07-25 00:24:17 +000034 // Parse the common declaration-specifiers piece.
35 DeclSpec DS;
36 ParseSpecifierQualifierList(DS);
37
38 // Parse the abstract-declarator, if present.
39 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
40 ParseDeclarator(DeclaratorInfo);
41
Sebastian Redl19fec9d2008-11-21 19:14:01 +000042 return Actions.ActOnTypeName(CurScope, DeclaratorInfo, CXXNewMode).Val;
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
45/// ParseAttributes - Parse a non-empty attributes list.
46///
47/// [GNU] attributes:
48/// attribute
49/// attributes attribute
50///
51/// [GNU] attribute:
52/// '__attribute__' '(' '(' attribute-list ')' ')'
53///
54/// [GNU] attribute-list:
55/// attrib
56/// attribute_list ',' attrib
57///
58/// [GNU] attrib:
59/// empty
60/// attrib-name
61/// attrib-name '(' identifier ')'
62/// attrib-name '(' identifier ',' nonempty-expr-list ')'
63/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
64///
65/// [GNU] attrib-name:
66/// identifier
67/// typespec
68/// typequal
69/// storageclass
70///
71/// FIXME: The GCC grammar/code for this construct implies we need two
72/// token lookahead. Comment from gcc: "If they start with an identifier
73/// which is followed by a comma or close parenthesis, then the arguments
74/// start with that identifier; otherwise they are an expression list."
75///
76/// At the moment, I am not doing 2 token lookahead. I am also unaware of
77/// any attributes that don't work (based on my limited testing). Most
78/// attributes are very simple in practice. Until we find a bug, I don't see
79/// a pressing need to implement the 2 token lookahead.
80
81AttributeList *Parser::ParseAttributes() {
Chris Lattner34a01ad2007-10-09 17:33:22 +000082 assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
Chris Lattner4b009652007-07-25 00:24:17 +000083
84 AttributeList *CurrAttr = 0;
85
Chris Lattner34a01ad2007-10-09 17:33:22 +000086 while (Tok.is(tok::kw___attribute)) {
Chris Lattner4b009652007-07-25 00:24:17 +000087 ConsumeToken();
88 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
89 "attribute")) {
90 SkipUntil(tok::r_paren, true); // skip until ) or ;
91 return CurrAttr;
92 }
93 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
94 SkipUntil(tok::r_paren, true); // skip until ) or ;
95 return CurrAttr;
96 }
97 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
Chris Lattner34a01ad2007-10-09 17:33:22 +000098 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
99 Tok.is(tok::comma)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000100
Chris Lattner34a01ad2007-10-09 17:33:22 +0000101 if (Tok.is(tok::comma)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000102 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
103 ConsumeToken();
104 continue;
105 }
106 // we have an identifier or declaration specifier (const, int, etc.)
107 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
108 SourceLocation AttrNameLoc = ConsumeToken();
109
110 // check if we have a "paramterized" attribute
Chris Lattner34a01ad2007-10-09 17:33:22 +0000111 if (Tok.is(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000112 ConsumeParen(); // ignore the left paren loc for now
113
Chris Lattner34a01ad2007-10-09 17:33:22 +0000114 if (Tok.is(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000115 IdentifierInfo *ParmName = Tok.getIdentifierInfo();
116 SourceLocation ParmLoc = ConsumeToken();
117
Chris Lattner34a01ad2007-10-09 17:33:22 +0000118 if (Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000119 // __attribute__(( mode(byte) ))
120 ConsumeParen(); // ignore the right paren loc for now
121 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
122 ParmName, ParmLoc, 0, 0, CurrAttr);
Chris Lattner34a01ad2007-10-09 17:33:22 +0000123 } else if (Tok.is(tok::comma)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000124 ConsumeToken();
125 // __attribute__(( format(printf, 1, 2) ))
Sebastian Redl6008ac32008-11-25 22:21:31 +0000126 ExprVector ArgExprs(Actions);
Chris Lattner4b009652007-07-25 00:24:17 +0000127 bool ArgExprsOk = true;
128
129 // now parse the non-empty comma separated list of expressions
130 while (1) {
131 ExprResult ArgExpr = ParseAssignmentExpression();
132 if (ArgExpr.isInvalid) {
133 ArgExprsOk = false;
134 SkipUntil(tok::r_paren);
135 break;
136 } else {
137 ArgExprs.push_back(ArgExpr.Val);
138 }
Chris Lattner34a01ad2007-10-09 17:33:22 +0000139 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000140 break;
141 ConsumeToken(); // Eat the comma, move to the next argument
142 }
Chris Lattner34a01ad2007-10-09 17:33:22 +0000143 if (ArgExprsOk && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 ConsumeParen(); // ignore the right paren loc for now
145 CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
Sebastian Redl6008ac32008-11-25 22:21:31 +0000146 ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
Chris Lattner4b009652007-07-25 00:24:17 +0000147 }
148 }
149 } else { // not an identifier
150 // parse a possibly empty comma separated list of expressions
Chris Lattner34a01ad2007-10-09 17:33:22 +0000151 if (Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000152 // __attribute__(( nonnull() ))
153 ConsumeParen(); // ignore the right paren loc for now
154 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
155 0, SourceLocation(), 0, 0, CurrAttr);
156 } else {
157 // __attribute__(( aligned(16) ))
Sebastian Redl6008ac32008-11-25 22:21:31 +0000158 ExprVector ArgExprs(Actions);
Chris Lattner4b009652007-07-25 00:24:17 +0000159 bool ArgExprsOk = true;
160
161 // now parse the list of expressions
162 while (1) {
163 ExprResult ArgExpr = ParseAssignmentExpression();
164 if (ArgExpr.isInvalid) {
165 ArgExprsOk = false;
166 SkipUntil(tok::r_paren);
167 break;
168 } else {
169 ArgExprs.push_back(ArgExpr.Val);
170 }
Chris Lattner34a01ad2007-10-09 17:33:22 +0000171 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000172 break;
173 ConsumeToken(); // Eat the comma, move to the next argument
174 }
175 // Match the ')'.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000176 if (ArgExprsOk && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000177 ConsumeParen(); // ignore the right paren loc for now
Sebastian Redl6008ac32008-11-25 22:21:31 +0000178 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
179 SourceLocation(), ArgExprs.take(), ArgExprs.size(),
Chris Lattner4b009652007-07-25 00:24:17 +0000180 CurrAttr);
181 }
182 }
183 }
184 } else {
185 CurrAttr = new AttributeList(AttrName, AttrNameLoc,
186 0, SourceLocation(), 0, 0, CurrAttr);
187 }
188 }
189 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
190 SkipUntil(tok::r_paren, false);
191 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
192 SkipUntil(tok::r_paren, false);
193 }
194 return CurrAttr;
195}
196
197/// ParseDeclaration - Parse a full 'declaration', which consists of
198/// declaration-specifiers, some number of declarators, and a semicolon.
199/// 'Context' should be a Declarator::TheContext value.
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000200///
201/// declaration: [C99 6.7]
202/// block-declaration ->
203/// simple-declaration
204/// others [FIXME]
205/// [C++] namespace-definition
206/// others... [FIXME]
207///
Chris Lattner4b009652007-07-25 00:24:17 +0000208Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000209 switch (Tok.getKind()) {
210 case tok::kw_namespace:
211 return ParseNamespace(Context);
212 default:
213 return ParseSimpleDeclaration(Context);
214 }
215}
216
217/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
218/// declaration-specifiers init-declarator-list[opt] ';'
219///[C90/C++]init-declarator-list ';' [TODO]
220/// [OMP] threadprivate-directive [TODO]
221Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) {
Chris Lattner4b009652007-07-25 00:24:17 +0000222 // Parse the common declaration-specifiers piece.
223 DeclSpec DS;
224 ParseDeclarationSpecifiers(DS);
225
226 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
227 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner34a01ad2007-10-09 17:33:22 +0000228 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000229 ConsumeToken();
230 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
231 }
232
233 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
234 ParseDeclarator(DeclaratorInfo);
235
236 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
237}
238
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000239
Chris Lattner4b009652007-07-25 00:24:17 +0000240/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
241/// parsing 'declaration-specifiers declarator'. This method is split out this
242/// way to handle the ambiguity between top-level function-definitions and
243/// declarations.
244///
Chris Lattner4b009652007-07-25 00:24:17 +0000245/// init-declarator-list: [C99 6.7]
246/// init-declarator
247/// init-declarator-list ',' init-declarator
248/// init-declarator: [C99 6.7]
249/// declarator
250/// declarator '=' initializer
251/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
252/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000253/// [C++] declarator initializer[opt]
254///
255/// [C++] initializer:
256/// [C++] '=' initializer-clause
257/// [C++] '(' expression-list ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000258///
259Parser::DeclTy *Parser::
260ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
261
262 // Declarators may be grouped together ("int X, *Y, Z();"). Provide info so
263 // that they can be chained properly if the actions want this.
264 Parser::DeclTy *LastDeclInGroup = 0;
265
266 // At this point, we know that it is not a function definition. Parse the
267 // rest of the init-declarator-list.
268 while (1) {
269 // If a simple-asm-expr is present, parse it.
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000270 if (Tok.is(tok::kw_asm)) {
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000271 ExprResult AsmLabel = ParseSimpleAsm();
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000272 if (AsmLabel.isInvalid) {
273 SkipUntil(tok::semi);
274 return 0;
275 }
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000276
277 D.setAsmLabel(AsmLabel.Val);
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000278 }
Chris Lattner4b009652007-07-25 00:24:17 +0000279
280 // If attributes are present, parse them.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000281 if (Tok.is(tok::kw___attribute))
Chris Lattner4b009652007-07-25 00:24:17 +0000282 D.AddAttributes(ParseAttributes());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000283
284 // Inform the current actions module that we just parsed this declarator.
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000285 LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000286
Chris Lattner4b009652007-07-25 00:24:17 +0000287 // Parse declarator '=' initializer.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000288 if (Tok.is(tok::equal)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000289 ConsumeToken();
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000290 ExprResult Init = ParseInitializer();
Chris Lattner4b009652007-07-25 00:24:17 +0000291 if (Init.isInvalid) {
292 SkipUntil(tok::semi);
293 return 0;
294 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000295 Actions.AddInitializerToDecl(LastDeclInGroup, Init.Val);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000296 } else if (Tok.is(tok::l_paren)) {
297 // Parse C++ direct initializer: '(' expression-list ')'
298 SourceLocation LParenLoc = ConsumeParen();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000299 ExprVector Exprs(Actions);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000300 CommaLocsTy CommaLocs;
301
302 bool InvalidExpr = false;
303 if (ParseExpressionList(Exprs, CommaLocs)) {
304 SkipUntil(tok::r_paren);
305 InvalidExpr = true;
306 }
307 // Match the ')'.
308 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
309
310 if (!InvalidExpr) {
311 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
312 "Unexpected number of commas!");
313 Actions.AddCXXDirectInitializerToDecl(LastDeclInGroup, LParenLoc,
Sebastian Redl6008ac32008-11-25 22:21:31 +0000314 Exprs.take(), Exprs.size(),
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000315 &CommaLocs[0], RParenLoc);
316 }
Douglas Gregor81c29152008-10-29 00:13:59 +0000317 } else {
318 Actions.ActOnUninitializedDecl(LastDeclInGroup);
Chris Lattner4b009652007-07-25 00:24:17 +0000319 }
320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // If we don't have a comma, it is either the end of the list (a ';') or an
322 // error, bail out.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000323 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000324 break;
325
326 // Consume the comma.
327 ConsumeToken();
328
329 // Parse the next declarator.
330 D.clear();
Chris Lattner926cf542008-10-20 04:57:38 +0000331
332 // Accept attributes in an init-declarator. In the first declarator in a
333 // declaration, these would be part of the declspec. In subsequent
334 // declarators, they become part of the declarator itself, so that they
335 // don't apply to declarators after *this* one. Examples:
336 // short __attribute__((common)) var; -> declspec
337 // short var __attribute__((common)); -> declarator
338 // short x, __attribute__((common)) var; -> declarator
339 if (Tok.is(tok::kw___attribute))
340 D.AddAttributes(ParseAttributes());
341
Chris Lattner4b009652007-07-25 00:24:17 +0000342 ParseDeclarator(D);
343 }
344
Chris Lattner34a01ad2007-10-09 17:33:22 +0000345 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000346 ConsumeToken();
347 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
348 }
Fariborz Jahanian6e9c2b12008-01-04 23:23:46 +0000349 // If this is an ObjC2 for-each loop, this is a successful declarator
350 // parse. The syntax for these looks like:
351 // 'for' '(' declaration 'in' expr ')' statement
Fariborz Jahaniancadb0702008-01-04 23:04:08 +0000352 if (D.getContext() == Declarator::ForContext && isTokIdentifier_in()) {
Fariborz Jahanian1300bc72008-01-03 17:55:25 +0000353 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
354 }
Chris Lattner4b009652007-07-25 00:24:17 +0000355 Diag(Tok, diag::err_parse_error);
356 // Skip to end of block or statement
Chris Lattnerf491b412007-08-21 18:36:18 +0000357 SkipUntil(tok::r_brace, true, true);
Chris Lattner34a01ad2007-10-09 17:33:22 +0000358 if (Tok.is(tok::semi))
Chris Lattner4b009652007-07-25 00:24:17 +0000359 ConsumeToken();
360 return 0;
361}
362
363/// ParseSpecifierQualifierList
364/// specifier-qualifier-list:
365/// type-specifier specifier-qualifier-list[opt]
366/// type-qualifier specifier-qualifier-list[opt]
367/// [GNU] attributes specifier-qualifier-list[opt]
368///
369void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
370 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
371 /// parse declaration-specifiers and complain about extra stuff.
372 ParseDeclarationSpecifiers(DS);
373
374 // Validate declspec for type-name.
375 unsigned Specs = DS.getParsedSpecifiers();
Steve Naroff5f0466b2008-06-05 00:02:44 +0000376 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers())
Chris Lattner4b009652007-07-25 00:24:17 +0000377 Diag(Tok, diag::err_typename_requires_specqual);
378
379 // Issue diagnostic and remove storage class if present.
380 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
381 if (DS.getStorageClassSpecLoc().isValid())
382 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
383 else
384 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
385 DS.ClearStorageClassSpecs();
386 }
387
388 // Issue diagnostic and remove function specfier if present.
389 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000390 if (DS.isInlineSpecified())
391 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
392 if (DS.isVirtualSpecified())
393 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
394 if (DS.isExplicitSpecified())
395 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattner4b009652007-07-25 00:24:17 +0000396 DS.ClearFunctionSpecs();
397 }
398}
399
400/// ParseDeclarationSpecifiers
401/// declaration-specifiers: [C99 6.7]
402/// storage-class-specifier declaration-specifiers[opt]
403/// type-specifier declaration-specifiers[opt]
Chris Lattner4b009652007-07-25 00:24:17 +0000404/// [C99] function-specifier declaration-specifiers[opt]
405/// [GNU] attributes declaration-specifiers[opt]
406///
407/// storage-class-specifier: [C99 6.7.1]
408/// 'typedef'
409/// 'extern'
410/// 'static'
411/// 'auto'
412/// 'register'
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000413/// [C++] 'mutable'
Chris Lattner4b009652007-07-25 00:24:17 +0000414/// [GNU] '__thread'
Chris Lattner4b009652007-07-25 00:24:17 +0000415/// function-specifier: [C99 6.7.4]
416/// [C99] 'inline'
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000417/// [C++] 'virtual'
418/// [C++] 'explicit'
Chris Lattner4b009652007-07-25 00:24:17 +0000419///
420void Parser::ParseDeclarationSpecifiers(DeclSpec &DS) {
Chris Lattnera4ff4272008-03-13 06:29:04 +0000421 DS.SetRangeStart(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000422 while (1) {
423 int isInvalid = false;
424 const char *PrevSpec = 0;
425 SourceLocation Loc = Tok.getLocation();
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000426
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000427 // Only annotate C++ scope. Allow class-name as an identifier in case
428 // it's a constructor.
Daniel Dunbar1afd88d2008-11-25 23:05:24 +0000429 if (getLang().CPlusPlus)
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000430 TryAnnotateCXXScopeToken();
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000431
Chris Lattner4b009652007-07-25 00:24:17 +0000432 switch (Tok.getKind()) {
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000433 default:
434 // Try to parse a type-specifier; if we found one, continue.
435 if (MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec))
436 continue;
437
Chris Lattnerb99d7492008-07-26 00:20:22 +0000438 DoneWithDeclSpec:
Chris Lattner4b009652007-07-25 00:24:17 +0000439 // If this is not a declaration specifier token, we're done reading decl
440 // specifiers. First verify that DeclSpec's are consistent.
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000441 DS.Finish(Diags, PP.getSourceManager(), getLang());
Chris Lattner4b009652007-07-25 00:24:17 +0000442 return;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000443
444 case tok::annot_cxxscope: {
445 if (DS.hasTypeSpecifier())
446 goto DoneWithDeclSpec;
447
448 // We are looking for a qualified typename.
449 if (NextToken().isNot(tok::identifier))
450 goto DoneWithDeclSpec;
451
452 CXXScopeSpec SS;
453 SS.setScopeRep(Tok.getAnnotationValue());
454 SS.setRange(Tok.getAnnotationRange());
455
456 // If the next token is the name of the class type that the C++ scope
457 // denotes, followed by a '(', then this is a constructor declaration.
458 // We're done with the decl-specifiers.
459 if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(),
460 CurScope, &SS) &&
461 GetLookAheadToken(2).is(tok::l_paren))
462 goto DoneWithDeclSpec;
463
464 TypeTy *TypeRep = Actions.isTypeName(*NextToken().getIdentifierInfo(),
465 CurScope, &SS);
466 if (TypeRep == 0)
467 goto DoneWithDeclSpec;
468
469 ConsumeToken(); // The C++ scope.
470
471 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
472 TypeRep);
473 if (isInvalid)
474 break;
475
476 DS.SetRangeEnd(Tok.getLocation());
477 ConsumeToken(); // The typename.
478
479 continue;
480 }
481
Chris Lattnerfda18db2008-07-26 01:18:38 +0000482 // typedef-name
483 case tok::identifier: {
484 // This identifier can only be a typedef name if we haven't already seen
485 // a type-specifier. Without this check we misparse:
486 // typedef int X; struct Y { short X; }; as 'short int'.
487 if (DS.hasTypeSpecifier())
488 goto DoneWithDeclSpec;
489
490 // It has to be available as a typedef too!
Argiris Kirtzidis46403632008-08-01 10:35:27 +0000491 TypeTy *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope);
Chris Lattnerfda18db2008-07-26 01:18:38 +0000492 if (TypeRep == 0)
493 goto DoneWithDeclSpec;
494
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000495 // C++: If the identifier is actually the name of the class type
496 // being defined and the next token is a '(', then this is a
497 // constructor declaration. We're done with the decl-specifiers
498 // and will treat this token as an identifier.
499 if (getLang().CPlusPlus &&
500 CurScope->isCXXClassScope() &&
501 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
502 NextToken().getKind() == tok::l_paren)
503 goto DoneWithDeclSpec;
504
Chris Lattnerfda18db2008-07-26 01:18:38 +0000505 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
506 TypeRep);
507 if (isInvalid)
508 break;
509
510 DS.SetRangeEnd(Tok.getLocation());
511 ConsumeToken(); // The identifier
512
513 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
514 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
515 // Objective-C interface. If we don't have Objective-C or a '<', this is
516 // just a normal reference to a typedef name.
517 if (!Tok.is(tok::less) || !getLang().ObjC1)
518 continue;
519
520 SourceLocation EndProtoLoc;
Chris Lattnerada63792008-07-26 01:53:50 +0000521 llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
Chris Lattner2bdedd62008-07-26 04:03:38 +0000522 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
Chris Lattnerada63792008-07-26 01:53:50 +0000523 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
Chris Lattnerfda18db2008-07-26 01:18:38 +0000524
525 DS.SetRangeEnd(EndProtoLoc);
526
Steve Narofff7683302008-09-22 10:28:57 +0000527 // Need to support trailing type qualifiers (e.g. "id<p> const").
528 // If a type specifier follows, it will be diagnosed elsewhere.
529 continue;
Chris Lattnerfda18db2008-07-26 01:18:38 +0000530 }
Chris Lattner4b009652007-07-25 00:24:17 +0000531 // GNU attributes support.
532 case tok::kw___attribute:
533 DS.AddAttributes(ParseAttributes());
534 continue;
535
536 // storage-class-specifier
537 case tok::kw_typedef:
538 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
539 break;
540 case tok::kw_extern:
541 if (DS.isThreadSpecified())
Chris Lattnerf006a222008-11-18 07:48:38 +0000542 Diag(Tok, diag::ext_thread_before) << "extern";
Chris Lattner4b009652007-07-25 00:24:17 +0000543 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
544 break;
Steve Narofff258a0f2007-12-18 00:16:02 +0000545 case tok::kw___private_extern__:
Chris Lattner9f7564b2008-04-06 06:57:35 +0000546 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
547 PrevSpec);
Steve Narofff258a0f2007-12-18 00:16:02 +0000548 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000549 case tok::kw_static:
550 if (DS.isThreadSpecified())
Chris Lattnerf006a222008-11-18 07:48:38 +0000551 Diag(Tok, diag::ext_thread_before) << "static";
Chris Lattner4b009652007-07-25 00:24:17 +0000552 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
553 break;
554 case tok::kw_auto:
555 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
556 break;
557 case tok::kw_register:
558 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
559 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000560 case tok::kw_mutable:
561 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec);
562 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000563 case tok::kw___thread:
564 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
565 break;
566
Chris Lattner4b009652007-07-25 00:24:17 +0000567 continue;
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000568
Chris Lattner4b009652007-07-25 00:24:17 +0000569 // function-specifier
570 case tok::kw_inline:
571 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
572 break;
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000573
574 case tok::kw_virtual:
575 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec);
576 break;
577
578 case tok::kw_explicit:
579 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec);
580 break;
Steve Naroff5f0466b2008-06-05 00:02:44 +0000581
Steve Naroff5f0466b2008-06-05 00:02:44 +0000582 case tok::less:
Chris Lattnerfda18db2008-07-26 01:18:38 +0000583 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattnerb99d7492008-07-26 00:20:22 +0000584 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
585 // but we support it.
Chris Lattnerfda18db2008-07-26 01:18:38 +0000586 if (DS.hasTypeSpecifier() || !getLang().ObjC1)
Chris Lattnerb99d7492008-07-26 00:20:22 +0000587 goto DoneWithDeclSpec;
588
589 {
590 SourceLocation EndProtoLoc;
Chris Lattnerada63792008-07-26 01:53:50 +0000591 llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
Chris Lattner2bdedd62008-07-26 04:03:38 +0000592 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
Chris Lattnerada63792008-07-26 01:53:50 +0000593 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
Chris Lattnerfda18db2008-07-26 01:18:38 +0000594 DS.SetRangeEnd(EndProtoLoc);
595
Chris Lattnerf006a222008-11-18 07:48:38 +0000596 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
597 << SourceRange(Loc, EndProtoLoc);
Steve Narofff7683302008-09-22 10:28:57 +0000598 // Need to support trailing type qualifiers (e.g. "id<p> const").
599 // If a type specifier follows, it will be diagnosed elsewhere.
600 continue;
Steve Naroff5f0466b2008-06-05 00:02:44 +0000601 }
Chris Lattner4b009652007-07-25 00:24:17 +0000602 }
603 // If the specifier combination wasn't legal, issue a diagnostic.
604 if (isInvalid) {
605 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattnerf006a222008-11-18 07:48:38 +0000606 // Pick between error or extwarn.
607 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
608 : diag::ext_duplicate_declspec;
609 Diag(Tok, DiagID) << PrevSpec;
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
Chris Lattnera4ff4272008-03-13 06:29:04 +0000611 DS.SetRangeEnd(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000612 ConsumeToken();
613 }
614}
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000615/// MaybeParseTypeSpecifier - Try to parse a single type-specifier. We
616/// primarily follow the C++ grammar with additions for C99 and GNU,
617/// which together subsume the C grammar. Note that the C++
618/// type-specifier also includes the C type-qualifier (for const,
619/// volatile, and C99 restrict). Returns true if a type-specifier was
620/// found (and parsed), false otherwise.
621///
622/// type-specifier: [C++ 7.1.5]
623/// simple-type-specifier
624/// class-specifier
625/// enum-specifier
626/// elaborated-type-specifier [TODO]
627/// cv-qualifier
628///
629/// cv-qualifier: [C++ 7.1.5.1]
630/// 'const'
631/// 'volatile'
632/// [C99] 'restrict'
633///
634/// simple-type-specifier: [ C++ 7.1.5.2]
635/// '::'[opt] nested-name-specifier[opt] type-name [TODO]
636/// '::'[opt] nested-name-specifier 'template' template-id [TODO]
637/// 'char'
638/// 'wchar_t'
639/// 'bool'
640/// 'short'
641/// 'int'
642/// 'long'
643/// 'signed'
644/// 'unsigned'
645/// 'float'
646/// 'double'
647/// 'void'
648/// [C99] '_Bool'
649/// [C99] '_Complex'
650/// [C99] '_Imaginary' // Removed in TC2?
651/// [GNU] '_Decimal32'
652/// [GNU] '_Decimal64'
653/// [GNU] '_Decimal128'
654/// [GNU] typeof-specifier
655/// [OBJC] class-name objc-protocol-refs[opt] [TODO]
656/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
657bool Parser::MaybeParseTypeSpecifier(DeclSpec &DS, int& isInvalid,
658 const char *&PrevSpec) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000659 // Annotate typenames and C++ scope specifiers.
660 TryAnnotateTypeOrScopeToken();
661
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000662 SourceLocation Loc = Tok.getLocation();
663
664 switch (Tok.getKind()) {
665 // simple-type-specifier:
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000666 case tok::annot_qualtypename: {
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000667 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000668 Tok.getAnnotationValue());
669 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
670 ConsumeToken(); // The typename
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000671
672 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
673 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
674 // Objective-C interface. If we don't have Objective-C or a '<', this is
675 // just a normal reference to a typedef name.
676 if (!Tok.is(tok::less) || !getLang().ObjC1)
677 return true;
678
679 SourceLocation EndProtoLoc;
680 llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
681 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
682 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
683
684 DS.SetRangeEnd(EndProtoLoc);
685 return true;
686 }
687
688 case tok::kw_short:
689 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
690 break;
691 case tok::kw_long:
692 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
693 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
694 else
695 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
696 break;
697 case tok::kw_signed:
698 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
699 break;
700 case tok::kw_unsigned:
701 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
702 break;
703 case tok::kw__Complex:
704 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
705 break;
706 case tok::kw__Imaginary:
707 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
708 break;
709 case tok::kw_void:
710 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
711 break;
712 case tok::kw_char:
713 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
714 break;
715 case tok::kw_int:
716 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
717 break;
718 case tok::kw_float:
719 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
720 break;
721 case tok::kw_double:
722 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
723 break;
724 case tok::kw_wchar_t:
725 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
726 break;
727 case tok::kw_bool:
728 case tok::kw__Bool:
729 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
730 break;
731 case tok::kw__Decimal32:
732 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
733 break;
734 case tok::kw__Decimal64:
735 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
736 break;
737 case tok::kw__Decimal128:
738 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
739 break;
740
741 // class-specifier:
742 case tok::kw_class:
743 case tok::kw_struct:
744 case tok::kw_union:
745 ParseClassSpecifier(DS);
746 return true;
747
748 // enum-specifier:
749 case tok::kw_enum:
750 ParseEnumSpecifier(DS);
751 return true;
752
753 // cv-qualifier:
754 case tok::kw_const:
755 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
756 getLang())*2;
757 break;
758 case tok::kw_volatile:
759 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
760 getLang())*2;
761 break;
762 case tok::kw_restrict:
763 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
764 getLang())*2;
765 break;
766
767 // GNU typeof support.
768 case tok::kw_typeof:
769 ParseTypeofSpecifier(DS);
770 return true;
771
772 default:
773 // Not a type-specifier; do nothing.
774 return false;
775 }
776
777 // If the specifier combination wasn't legal, issue a diagnostic.
778 if (isInvalid) {
779 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattnerf006a222008-11-18 07:48:38 +0000780 // Pick between error or extwarn.
781 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
782 : diag::ext_duplicate_declspec;
783 Diag(Tok, DiagID) << PrevSpec;
Douglas Gregor3a6a3072008-11-07 15:42:26 +0000784 }
785 DS.SetRangeEnd(Tok.getLocation());
786 ConsumeToken(); // whatever we parsed above.
787 return true;
788}
Chris Lattner4b009652007-07-25 00:24:17 +0000789
Chris Lattnerced5b4f2007-10-29 04:42:53 +0000790/// ParseStructDeclaration - Parse a struct declaration without the terminating
791/// semicolon.
792///
Chris Lattner4b009652007-07-25 00:24:17 +0000793/// struct-declaration:
Chris Lattnerced5b4f2007-10-29 04:42:53 +0000794/// specifier-qualifier-list struct-declarator-list
Chris Lattner4b009652007-07-25 00:24:17 +0000795/// [GNU] __extension__ struct-declaration
Chris Lattnerced5b4f2007-10-29 04:42:53 +0000796/// [GNU] specifier-qualifier-list
Chris Lattner4b009652007-07-25 00:24:17 +0000797/// struct-declarator-list:
798/// struct-declarator
799/// struct-declarator-list ',' struct-declarator
800/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
801/// struct-declarator:
802/// declarator
803/// [GNU] declarator attributes[opt]
804/// declarator[opt] ':' constant-expression
805/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
806///
Chris Lattner3dd8d392008-04-10 06:46:29 +0000807void Parser::
808ParseStructDeclaration(DeclSpec &DS,
809 llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000810 if (Tok.is(tok::kw___extension__)) {
811 // __extension__ silences extension warnings in the subexpression.
812 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroffa9adf112007-08-20 22:28:22 +0000813 ConsumeToken();
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000814 return ParseStructDeclaration(DS, Fields);
815 }
Steve Naroffa9adf112007-08-20 22:28:22 +0000816
817 // Parse the common specifier-qualifiers-list piece.
Chris Lattner12e8a4c2008-04-10 06:15:14 +0000818 SourceLocation DSStart = Tok.getLocation();
Steve Naroffa9adf112007-08-20 22:28:22 +0000819 ParseSpecifierQualifierList(DS);
Steve Naroffa9adf112007-08-20 22:28:22 +0000820
821 // If there are no declarators, issue a warning.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000822 if (Tok.is(tok::semi)) {
Chris Lattner12e8a4c2008-04-10 06:15:14 +0000823 Diag(DSStart, diag::w_no_declarators);
Steve Naroffa9adf112007-08-20 22:28:22 +0000824 return;
825 }
826
827 // Read struct-declarators until we find the semicolon.
Chris Lattnerf62fb732008-04-10 16:37:40 +0000828 Fields.push_back(FieldDeclarator(DS));
Steve Naroffa9adf112007-08-20 22:28:22 +0000829 while (1) {
Chris Lattner3dd8d392008-04-10 06:46:29 +0000830 FieldDeclarator &DeclaratorInfo = Fields.back();
831
Steve Naroffa9adf112007-08-20 22:28:22 +0000832 /// struct-declarator: declarator
833 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner34a01ad2007-10-09 17:33:22 +0000834 if (Tok.isNot(tok::colon))
Chris Lattner3dd8d392008-04-10 06:46:29 +0000835 ParseDeclarator(DeclaratorInfo.D);
Steve Naroffa9adf112007-08-20 22:28:22 +0000836
Chris Lattner34a01ad2007-10-09 17:33:22 +0000837 if (Tok.is(tok::colon)) {
Steve Naroffa9adf112007-08-20 22:28:22 +0000838 ConsumeToken();
839 ExprResult Res = ParseConstantExpression();
Chris Lattner12e8a4c2008-04-10 06:15:14 +0000840 if (Res.isInvalid)
Steve Naroffa9adf112007-08-20 22:28:22 +0000841 SkipUntil(tok::semi, true, true);
Chris Lattner12e8a4c2008-04-10 06:15:14 +0000842 else
Chris Lattner3dd8d392008-04-10 06:46:29 +0000843 DeclaratorInfo.BitfieldSize = Res.Val;
Steve Naroffa9adf112007-08-20 22:28:22 +0000844 }
845
846 // If attributes exist after the declarator, parse them.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000847 if (Tok.is(tok::kw___attribute))
Chris Lattner3dd8d392008-04-10 06:46:29 +0000848 DeclaratorInfo.D.AddAttributes(ParseAttributes());
Steve Naroffa9adf112007-08-20 22:28:22 +0000849
850 // If we don't have a comma, it is either the end of the list (a ';')
851 // or an error, bail out.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000852 if (Tok.isNot(tok::comma))
Chris Lattnerced5b4f2007-10-29 04:42:53 +0000853 return;
Steve Naroffa9adf112007-08-20 22:28:22 +0000854
855 // Consume the comma.
856 ConsumeToken();
857
858 // Parse the next declarator.
Chris Lattnerf62fb732008-04-10 16:37:40 +0000859 Fields.push_back(FieldDeclarator(DS));
Steve Naroffa9adf112007-08-20 22:28:22 +0000860
861 // Attributes are only allowed on the second declarator.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000862 if (Tok.is(tok::kw___attribute))
Chris Lattner3dd8d392008-04-10 06:46:29 +0000863 Fields.back().D.AddAttributes(ParseAttributes());
Steve Naroffa9adf112007-08-20 22:28:22 +0000864 }
Steve Naroffa9adf112007-08-20 22:28:22 +0000865}
866
867/// ParseStructUnionBody
868/// struct-contents:
869/// struct-declaration-list
870/// [EXT] empty
871/// [GNU] "struct-declaration-list" without terminatoring ';'
872/// struct-declaration-list:
873/// struct-declaration
874/// struct-declaration-list struct-declaration
Chris Lattner1bf58f62008-06-21 19:39:06 +0000875/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroffa9adf112007-08-20 22:28:22 +0000876///
Chris Lattner4b009652007-07-25 00:24:17 +0000877void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
878 unsigned TagType, DeclTy *TagDecl) {
879 SourceLocation LBraceLoc = ConsumeBrace();
880
881 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
882 // C++.
Douglas Gregorec93f442008-04-13 21:30:24 +0000883 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
Chris Lattnerf006a222008-11-18 07:48:38 +0000884 Diag(Tok, diag::ext_empty_struct_union_enum)
885 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
Chris Lattner4b009652007-07-25 00:24:17 +0000886
887 llvm::SmallVector<DeclTy*, 32> FieldDecls;
Chris Lattner3dd8d392008-04-10 06:46:29 +0000888 llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
889
Chris Lattner4b009652007-07-25 00:24:17 +0000890 // While we still have something to read, read the declarations in the struct.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000891 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000892 // Each iteration of this loop reads one struct-declaration.
893
894 // Check for extraneous top-level semicolon.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000895 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000896 Diag(Tok, diag::ext_extra_struct_semi);
897 ConsumeToken();
898 continue;
899 }
Chris Lattner3dd8d392008-04-10 06:46:29 +0000900
901 // Parse all the comma separated declarators.
902 DeclSpec DS;
903 FieldDeclarators.clear();
Chris Lattner1bf58f62008-06-21 19:39:06 +0000904 if (!Tok.is(tok::at)) {
905 ParseStructDeclaration(DS, FieldDeclarators);
906
907 // Convert them all to fields.
908 for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
909 FieldDeclarator &FD = FieldDeclarators[i];
910 // Install the declarator into the current TagDecl.
911 DeclTy *Field = Actions.ActOnField(CurScope,
912 DS.getSourceRange().getBegin(),
913 FD.D, FD.BitfieldSize);
914 FieldDecls.push_back(Field);
915 }
916 } else { // Handle @defs
917 ConsumeToken();
918 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
919 Diag(Tok, diag::err_unexpected_at);
920 SkipUntil(tok::semi, true, true);
921 continue;
922 }
923 ConsumeToken();
924 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
925 if (!Tok.is(tok::identifier)) {
926 Diag(Tok, diag::err_expected_ident);
927 SkipUntil(tok::semi, true, true);
928 continue;
929 }
930 llvm::SmallVector<DeclTy*, 16> Fields;
931 Actions.ActOnDefs(CurScope, Tok.getLocation(), Tok.getIdentifierInfo(),
932 Fields);
933 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
934 ConsumeToken();
935 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
936 }
Chris Lattner4b009652007-07-25 00:24:17 +0000937
Chris Lattner34a01ad2007-10-09 17:33:22 +0000938 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000939 ConsumeToken();
Chris Lattner34a01ad2007-10-09 17:33:22 +0000940 } else if (Tok.is(tok::r_brace)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000941 Diag(Tok, diag::ext_expected_semi_decl_list);
Chris Lattner4b009652007-07-25 00:24:17 +0000942 break;
943 } else {
944 Diag(Tok, diag::err_expected_semi_decl_list);
945 // Skip to end of block or statement
946 SkipUntil(tok::r_brace, true, true);
947 }
948 }
949
Steve Naroff1a7fa7b2007-10-29 21:38:07 +0000950 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000951
Chris Lattner4b009652007-07-25 00:24:17 +0000952 AttributeList *AttrList = 0;
953 // If attributes exist after struct contents, parse them.
Chris Lattner34a01ad2007-10-09 17:33:22 +0000954 if (Tok.is(tok::kw___attribute))
Daniel Dunbar3b908072008-10-03 16:42:10 +0000955 AttrList = ParseAttributes();
Daniel Dunbarf3944442008-10-03 02:03:53 +0000956
957 Actions.ActOnFields(CurScope,
958 RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
959 LBraceLoc, RBraceLoc,
960 AttrList);
Chris Lattner4b009652007-07-25 00:24:17 +0000961}
962
963
964/// ParseEnumSpecifier
965/// enum-specifier: [C99 6.7.2.2]
966/// 'enum' identifier[opt] '{' enumerator-list '}'
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000967///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattner4b009652007-07-25 00:24:17 +0000968/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
969/// '}' attributes[opt]
970/// 'enum' identifier
971/// [GNU] 'enum' attributes[opt] identifier
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000972///
973/// [C++] elaborated-type-specifier:
974/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
975///
Chris Lattner4b009652007-07-25 00:24:17 +0000976void Parser::ParseEnumSpecifier(DeclSpec &DS) {
Chris Lattner34a01ad2007-10-09 17:33:22 +0000977 assert(Tok.is(tok::kw_enum) && "Not an enum specifier");
Chris Lattner4b009652007-07-25 00:24:17 +0000978 SourceLocation StartLoc = ConsumeToken();
979
980 // Parse the tag portion of this.
Argiris Kirtzidis2298f012008-09-11 00:21:41 +0000981
982 AttributeList *Attr = 0;
983 // If attributes exist after tag, parse them.
984 if (Tok.is(tok::kw___attribute))
985 Attr = ParseAttributes();
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000986
987 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000988 if (getLang().CPlusPlus && MaybeParseCXXScopeSpecifier(SS)) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000989 if (Tok.isNot(tok::identifier)) {
990 Diag(Tok, diag::err_expected_ident);
991 if (Tok.isNot(tok::l_brace)) {
992 // Has no name and is not a definition.
993 // Skip the rest of this declarator, up until the comma or semicolon.
994 SkipUntil(tok::comma, true);
995 return;
996 }
997 }
998 }
Argiris Kirtzidis2298f012008-09-11 00:21:41 +0000999
1000 // Must have either 'enum name' or 'enum {...}'.
1001 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1002 Diag(Tok, diag::err_expected_ident_lbrace);
1003
1004 // Skip the rest of this declarator, up until the comma or semicolon.
1005 SkipUntil(tok::comma, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001006 return;
Argiris Kirtzidis2298f012008-09-11 00:21:41 +00001007 }
1008
1009 // If an identifier is present, consume and remember it.
1010 IdentifierInfo *Name = 0;
1011 SourceLocation NameLoc;
1012 if (Tok.is(tok::identifier)) {
1013 Name = Tok.getIdentifierInfo();
1014 NameLoc = ConsumeToken();
1015 }
1016
1017 // There are three options here. If we have 'enum foo;', then this is a
1018 // forward declaration. If we have 'enum foo {...' then this is a
1019 // definition. Otherwise we have something like 'enum foo xyz', a reference.
1020 //
1021 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1022 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
1023 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
1024 //
1025 Action::TagKind TK;
1026 if (Tok.is(tok::l_brace))
1027 TK = Action::TK_Definition;
1028 else if (Tok.is(tok::semi))
1029 TK = Action::TK_Declaration;
1030 else
1031 TK = Action::TK_Reference;
1032 DeclTy *TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK, StartLoc,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001033 SS, Name, NameLoc, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001034
Chris Lattner34a01ad2007-10-09 17:33:22 +00001035 if (Tok.is(tok::l_brace))
Chris Lattner4b009652007-07-25 00:24:17 +00001036 ParseEnumBody(StartLoc, TagDecl);
1037
1038 // TODO: semantic analysis on the declspec for enums.
1039 const char *PrevSpec = 0;
1040 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
Chris Lattnerf006a222008-11-18 07:48:38 +00001041 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Chris Lattner4b009652007-07-25 00:24:17 +00001042}
1043
1044/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1045/// enumerator-list:
1046/// enumerator
1047/// enumerator-list ',' enumerator
1048/// enumerator:
1049/// enumeration-constant
1050/// enumeration-constant '=' constant-expression
1051/// enumeration-constant:
1052/// identifier
1053///
1054void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
1055 SourceLocation LBraceLoc = ConsumeBrace();
1056
Chris Lattnerc9a92452007-08-27 17:24:30 +00001057 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
Chris Lattner34a01ad2007-10-09 17:33:22 +00001058 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
Chris Lattnerf006a222008-11-18 07:48:38 +00001059 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
Chris Lattner4b009652007-07-25 00:24:17 +00001060
1061 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
1062
1063 DeclTy *LastEnumConstDecl = 0;
1064
1065 // Parse the enumerator-list.
Chris Lattner34a01ad2007-10-09 17:33:22 +00001066 while (Tok.is(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001067 IdentifierInfo *Ident = Tok.getIdentifierInfo();
1068 SourceLocation IdentLoc = ConsumeToken();
1069
1070 SourceLocation EqualLoc;
1071 ExprTy *AssignedVal = 0;
Chris Lattner34a01ad2007-10-09 17:33:22 +00001072 if (Tok.is(tok::equal)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001073 EqualLoc = ConsumeToken();
1074 ExprResult Res = ParseConstantExpression();
1075 if (Res.isInvalid)
1076 SkipUntil(tok::comma, tok::r_brace, true, true);
1077 else
1078 AssignedVal = Res.Val;
1079 }
1080
1081 // Install the enumerator constant into EnumDecl.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001082 DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001083 LastEnumConstDecl,
1084 IdentLoc, Ident,
1085 EqualLoc, AssignedVal);
1086 EnumConstantDecls.push_back(EnumConstDecl);
1087 LastEnumConstDecl = EnumConstDecl;
1088
Chris Lattner34a01ad2007-10-09 17:33:22 +00001089 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +00001090 break;
1091 SourceLocation CommaLoc = ConsumeToken();
1092
Chris Lattner34a01ad2007-10-09 17:33:22 +00001093 if (Tok.isNot(tok::identifier) && !getLang().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001094 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
1095 }
1096
1097 // Eat the }.
1098 MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1099
Steve Naroff0acc9c92007-09-15 18:49:24 +00001100 Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
Chris Lattner4b009652007-07-25 00:24:17 +00001101 EnumConstantDecls.size());
1102
1103 DeclTy *AttrList = 0;
1104 // If attributes exist after the identifier list, parse them.
Chris Lattner34a01ad2007-10-09 17:33:22 +00001105 if (Tok.is(tok::kw___attribute))
Chris Lattner4b009652007-07-25 00:24:17 +00001106 AttrList = ParseAttributes(); // FIXME: where do they do?
1107}
1108
1109/// isTypeSpecifierQualifier - Return true if the current token could be the
Steve Naroff6f9f9552008-02-11 23:15:56 +00001110/// start of a type-qualifier-list.
1111bool Parser::isTypeQualifier() const {
1112 switch (Tok.getKind()) {
1113 default: return false;
1114 // type-qualifier
1115 case tok::kw_const:
1116 case tok::kw_volatile:
1117 case tok::kw_restrict:
1118 return true;
1119 }
1120}
1121
1122/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattner4b009652007-07-25 00:24:17 +00001123/// start of a specifier-qualifier-list.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001124bool Parser::isTypeSpecifierQualifier() {
1125 // Annotate typenames and C++ scope specifiers.
1126 TryAnnotateTypeOrScopeToken();
1127
Chris Lattner4b009652007-07-25 00:24:17 +00001128 switch (Tok.getKind()) {
1129 default: return false;
1130 // GNU attributes support.
1131 case tok::kw___attribute:
Steve Naroff7cbb1462007-07-31 12:34:36 +00001132 // GNU typeof support.
1133 case tok::kw_typeof:
1134
Chris Lattner4b009652007-07-25 00:24:17 +00001135 // type-specifiers
1136 case tok::kw_short:
1137 case tok::kw_long:
1138 case tok::kw_signed:
1139 case tok::kw_unsigned:
1140 case tok::kw__Complex:
1141 case tok::kw__Imaginary:
1142 case tok::kw_void:
1143 case tok::kw_char:
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001144 case tok::kw_wchar_t:
Chris Lattner4b009652007-07-25 00:24:17 +00001145 case tok::kw_int:
1146 case tok::kw_float:
1147 case tok::kw_double:
Chris Lattner2baef2e2007-11-15 05:25:19 +00001148 case tok::kw_bool:
Chris Lattner4b009652007-07-25 00:24:17 +00001149 case tok::kw__Bool:
1150 case tok::kw__Decimal32:
1151 case tok::kw__Decimal64:
1152 case tok::kw__Decimal128:
1153
Chris Lattner2e78db32008-04-13 18:59:07 +00001154 // struct-or-union-specifier (C99) or class-specifier (C++)
1155 case tok::kw_class:
Chris Lattner4b009652007-07-25 00:24:17 +00001156 case tok::kw_struct:
1157 case tok::kw_union:
1158 // enum-specifier
1159 case tok::kw_enum:
1160
1161 // type-qualifier
1162 case tok::kw_const:
1163 case tok::kw_volatile:
1164 case tok::kw_restrict:
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001165
1166 // typedef-name
1167 case tok::annot_qualtypename:
Chris Lattner4b009652007-07-25 00:24:17 +00001168 return true;
Chris Lattner9aefe722008-10-20 00:25:30 +00001169
1170 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1171 case tok::less:
1172 return getLang().ObjC1;
Chris Lattner4b009652007-07-25 00:24:17 +00001173 }
1174}
1175
1176/// isDeclarationSpecifier() - Return true if the current token is part of a
1177/// declaration specifier.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001178bool Parser::isDeclarationSpecifier() {
1179 // Annotate typenames and C++ scope specifiers.
1180 TryAnnotateTypeOrScopeToken();
1181
Chris Lattner4b009652007-07-25 00:24:17 +00001182 switch (Tok.getKind()) {
1183 default: return false;
1184 // storage-class-specifier
1185 case tok::kw_typedef:
1186 case tok::kw_extern:
Steve Narofff258a0f2007-12-18 00:16:02 +00001187 case tok::kw___private_extern__:
Chris Lattner4b009652007-07-25 00:24:17 +00001188 case tok::kw_static:
1189 case tok::kw_auto:
1190 case tok::kw_register:
1191 case tok::kw___thread:
1192
1193 // type-specifiers
1194 case tok::kw_short:
1195 case tok::kw_long:
1196 case tok::kw_signed:
1197 case tok::kw_unsigned:
1198 case tok::kw__Complex:
1199 case tok::kw__Imaginary:
1200 case tok::kw_void:
1201 case tok::kw_char:
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001202 case tok::kw_wchar_t:
Chris Lattner4b009652007-07-25 00:24:17 +00001203 case tok::kw_int:
1204 case tok::kw_float:
1205 case tok::kw_double:
Chris Lattner2baef2e2007-11-15 05:25:19 +00001206 case tok::kw_bool:
Chris Lattner4b009652007-07-25 00:24:17 +00001207 case tok::kw__Bool:
1208 case tok::kw__Decimal32:
1209 case tok::kw__Decimal64:
1210 case tok::kw__Decimal128:
1211
Chris Lattner2e78db32008-04-13 18:59:07 +00001212 // struct-or-union-specifier (C99) or class-specifier (C++)
1213 case tok::kw_class:
Chris Lattner4b009652007-07-25 00:24:17 +00001214 case tok::kw_struct:
1215 case tok::kw_union:
1216 // enum-specifier
1217 case tok::kw_enum:
1218
1219 // type-qualifier
1220 case tok::kw_const:
1221 case tok::kw_volatile:
1222 case tok::kw_restrict:
Steve Naroff7cbb1462007-07-31 12:34:36 +00001223
Chris Lattner4b009652007-07-25 00:24:17 +00001224 // function-specifier
1225 case tok::kw_inline:
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001226 case tok::kw_virtual:
1227 case tok::kw_explicit:
Chris Lattnere35d2582007-08-09 16:40:21 +00001228
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001229 // typedef-name
1230 case tok::annot_qualtypename:
1231
Chris Lattnerb707a7a2007-08-09 17:01:07 +00001232 // GNU typeof support.
1233 case tok::kw_typeof:
1234
1235 // GNU attributes.
Chris Lattnere35d2582007-08-09 16:40:21 +00001236 case tok::kw___attribute:
Chris Lattner4b009652007-07-25 00:24:17 +00001237 return true;
Chris Lattner1b2251c2008-07-26 03:38:44 +00001238
1239 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1240 case tok::less:
1241 return getLang().ObjC1;
Chris Lattner4b009652007-07-25 00:24:17 +00001242 }
1243}
1244
1245
1246/// ParseTypeQualifierListOpt
1247/// type-qualifier-list: [C99 6.7.5]
1248/// type-qualifier
1249/// [GNU] attributes
1250/// type-qualifier-list type-qualifier
1251/// [GNU] type-qualifier-list attributes
1252///
1253void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
1254 while (1) {
1255 int isInvalid = false;
1256 const char *PrevSpec = 0;
1257 SourceLocation Loc = Tok.getLocation();
1258
1259 switch (Tok.getKind()) {
1260 default:
1261 // If this is not a type-qualifier token, we're done reading type
1262 // qualifiers. First verify that DeclSpec's are consistent.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001263 DS.Finish(Diags, PP.getSourceManager(), getLang());
Chris Lattner4b009652007-07-25 00:24:17 +00001264 return;
1265 case tok::kw_const:
1266 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
1267 getLang())*2;
1268 break;
1269 case tok::kw_volatile:
1270 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1271 getLang())*2;
1272 break;
1273 case tok::kw_restrict:
1274 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1275 getLang())*2;
1276 break;
1277 case tok::kw___attribute:
1278 DS.AddAttributes(ParseAttributes());
1279 continue; // do *not* consume the next token!
1280 }
1281
1282 // If the specifier combination wasn't legal, issue a diagnostic.
1283 if (isInvalid) {
1284 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattnerf006a222008-11-18 07:48:38 +00001285 // Pick between error or extwarn.
1286 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1287 : diag::ext_duplicate_declspec;
1288 Diag(Tok, DiagID) << PrevSpec;
Chris Lattner4b009652007-07-25 00:24:17 +00001289 }
1290 ConsumeToken();
1291 }
1292}
1293
1294
1295/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1296///
1297void Parser::ParseDeclarator(Declarator &D) {
1298 /// This implements the 'declarator' production in the C grammar, then checks
1299 /// for well-formedness and issues diagnostics.
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001300 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +00001301}
1302
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001303/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1304/// is parsed by the function passed to it. Pass null, and the direct-declarator
1305/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001306/// ptr-operator production.
1307///
Chris Lattner4b009652007-07-25 00:24:17 +00001308/// declarator: [C99 6.7.5]
1309/// pointer[opt] direct-declarator
1310/// [C++] '&' declarator [C++ 8p4, dcl.decl]
1311/// [GNU] '&' restrict[opt] attributes[opt] declarator
1312///
1313/// pointer: [C99 6.7.5]
1314/// '*' type-qualifier-list[opt]
1315/// '*' type-qualifier-list[opt] pointer
1316///
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001317/// ptr-operator:
1318/// '*' cv-qualifier-seq[opt]
1319/// '&'
1320/// [GNU] '&' restrict[opt] attributes[opt]
1321/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] [TODO]
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001322void Parser::ParseDeclaratorInternal(Declarator &D,
1323 DirectDeclParseFunction DirectDeclParser) {
Chris Lattner4b009652007-07-25 00:24:17 +00001324 tok::TokenKind Kind = Tok.getKind();
1325
Steve Naroff7aa54752008-08-27 16:04:49 +00001326 // Not a pointer, C++ reference, or block.
1327 if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus) &&
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001328 (Kind != tok::caret || !getLang().Blocks)) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001329 if (DirectDeclParser)
1330 (this->*DirectDeclParser)(D);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001331 return;
1332 }
Chris Lattner4b009652007-07-25 00:24:17 +00001333
Steve Naroffdc22f212008-08-28 10:07:06 +00001334 // Otherwise, '*' -> pointer, '^' -> block, '&' -> reference.
Chris Lattner4b009652007-07-25 00:24:17 +00001335 SourceLocation Loc = ConsumeToken(); // Eat the * or &.
1336
Steve Naroffdc22f212008-08-28 10:07:06 +00001337 if (Kind == tok::star || (Kind == tok::caret && getLang().Blocks)) {
Chris Lattner69f01932008-02-21 01:32:26 +00001338 // Is a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +00001339 DeclSpec DS;
1340
1341 ParseTypeQualifierListOpt(DS);
1342
1343 // Recursively parse the declarator.
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001344 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroff7aa54752008-08-27 16:04:49 +00001345 if (Kind == tok::star)
1346 // Remember that we parsed a pointer type, and remember the type-quals.
1347 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1348 DS.TakeAttributes()));
1349 else
1350 // Remember that we parsed a Block type, and remember the type-quals.
1351 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
1352 Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00001353 } else {
1354 // Is a reference
1355 DeclSpec DS;
1356
1357 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1358 // cv-qualifiers are introduced through the use of a typedef or of a
1359 // template type argument, in which case the cv-qualifiers are ignored.
1360 //
1361 // [GNU] Retricted references are allowed.
1362 // [GNU] Attributes on references are allowed.
1363 ParseTypeQualifierListOpt(DS);
1364
1365 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1366 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1367 Diag(DS.getConstSpecLoc(),
Chris Lattnerf006a222008-11-18 07:48:38 +00001368 diag::err_invalid_reference_qualifier_application) << "const";
Chris Lattner4b009652007-07-25 00:24:17 +00001369 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1370 Diag(DS.getVolatileSpecLoc(),
Chris Lattnerf006a222008-11-18 07:48:38 +00001371 diag::err_invalid_reference_qualifier_application) << "volatile";
Chris Lattner4b009652007-07-25 00:24:17 +00001372 }
1373
1374 // Recursively parse the declarator.
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001375 ParseDeclaratorInternal(D, DirectDeclParser);
Chris Lattner4b009652007-07-25 00:24:17 +00001376
Douglas Gregorb7b28a22008-11-03 15:51:28 +00001377 if (D.getNumTypeObjects() > 0) {
1378 // C++ [dcl.ref]p4: There shall be no references to references.
1379 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
1380 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattner8f7db152008-11-19 07:37:42 +00001381 if (const IdentifierInfo *II = D.getIdentifier())
1382 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1383 << II;
1384 else
1385 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1386 << "type name";
Douglas Gregorb7b28a22008-11-03 15:51:28 +00001387
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001388 // Once we've complained about the reference-to-reference, we
Douglas Gregorb7b28a22008-11-03 15:51:28 +00001389 // can go ahead and build the (technically ill-formed)
1390 // declarator: reference collapsing will take care of it.
1391 }
1392 }
1393
Chris Lattner4b009652007-07-25 00:24:17 +00001394 // Remember that we parsed a reference type. It doesn't have type-quals.
Chris Lattner69f01932008-02-21 01:32:26 +00001395 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1396 DS.TakeAttributes()));
Chris Lattner4b009652007-07-25 00:24:17 +00001397 }
1398}
1399
1400/// ParseDirectDeclarator
1401/// direct-declarator: [C99 6.7.5]
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001402/// [C99] identifier
Chris Lattner4b009652007-07-25 00:24:17 +00001403/// '(' declarator ')'
1404/// [GNU] '(' attributes declarator ')'
1405/// [C90] direct-declarator '[' constant-expression[opt] ']'
1406/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1407/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1408/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1409/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1410/// direct-declarator '(' parameter-type-list ')'
1411/// direct-declarator '(' identifier-list[opt] ')'
1412/// [GNU] direct-declarator '(' parameter-forward-declarations
1413/// parameter-type-list[opt] ')'
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001414/// [C++] direct-declarator '(' parameter-declaration-clause ')'
1415/// cv-qualifier-seq[opt] exception-specification[opt]
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001416/// [C++] declarator-id
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001417///
1418/// declarator-id: [C++ 8]
1419/// id-expression
1420/// '::'[opt] nested-name-specifier[opt] type-name
1421///
1422/// id-expression: [C++ 5.1]
1423/// unqualified-id
1424/// qualified-id [TODO]
1425///
1426/// unqualified-id: [C++ 5.1]
1427/// identifier
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001428/// operator-function-id
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001429/// conversion-function-id [TODO]
1430/// '~' class-name
1431/// template-id [TODO]
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001432///
Chris Lattner4b009652007-07-25 00:24:17 +00001433void Parser::ParseDirectDeclarator(Declarator &D) {
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001434 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001435
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001436 if (getLang().CPlusPlus) {
1437 if (D.mayHaveIdentifier()) {
1438 bool afterCXXScope = MaybeParseCXXScopeSpecifier(D.getCXXScopeSpec());
1439 if (afterCXXScope) {
1440 // Change the declaration context for name lookup, until this function
1441 // is exited (and the declarator has been parsed).
1442 DeclScopeObj.EnterDeclaratorScope();
1443 }
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001444
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001445 if (Tok.is(tok::identifier)) {
1446 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1447 // Determine whether this identifier is a C++ constructor name or
1448 // a normal identifier.
1449 if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope)) {
1450 D.setConstructor(Actions.isTypeName(*Tok.getIdentifierInfo(),
1451 CurScope),
1452 Tok.getLocation());
1453 } else
1454 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1455 ConsumeToken();
1456 goto PastIdentifier;
1457 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001458
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001459 if (Tok.is(tok::tilde)) {
1460 // This should be a C++ destructor.
1461 SourceLocation TildeLoc = ConsumeToken();
1462 if (Tok.is(tok::identifier)) {
1463 if (TypeTy *Type = ParseClassName())
1464 D.setDestructor(Type, TildeLoc);
1465 else
1466 D.SetIdentifier(0, TildeLoc);
1467 } else {
1468 Diag(Tok, diag::err_expected_class_name);
1469 D.SetIdentifier(0, TildeLoc);
1470 }
1471 goto PastIdentifier;
1472 }
1473
1474 // If we reached this point, token is not identifier and not '~'.
1475
1476 if (afterCXXScope) {
1477 Diag(Tok, diag::err_expected_unqualified_id);
1478 D.SetIdentifier(0, Tok.getLocation());
1479 D.setInvalidType(true);
1480 goto PastIdentifier;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001481 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001482 }
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001483
1484 if (Tok.is(tok::kw_operator)) {
1485 SourceLocation OperatorLoc = Tok.getLocation();
1486
1487 // First try the name of an overloaded operator
1488 if (OverloadedOperatorKind Op = TryParseOperatorFunctionId()) {
1489 D.setOverloadedOperator(Op, OperatorLoc);
1490 } else {
1491 // This must be a conversion function (C++ [class.conv.fct]).
1492 if (TypeTy *ConvType = ParseConversionFunctionId())
1493 D.setConversionFunction(ConvType, OperatorLoc);
1494 else
1495 D.SetIdentifier(0, Tok.getLocation());
1496 }
1497 goto PastIdentifier;
1498 }
1499 }
1500
1501 // If we reached this point, we are either in C/ObjC or the token didn't
1502 // satisfy any of the C++-specific checks.
1503
1504 if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1505 assert(!getLang().CPlusPlus &&
1506 "There's a C++-specific check for tok::identifier above");
1507 assert(Tok.getIdentifierInfo() && "Not an identifier?");
1508 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1509 ConsumeToken();
1510 } else if (Tok.is(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001511 // direct-declarator: '(' declarator ')'
1512 // direct-declarator: '(' attributes declarator ')'
1513 // Example: 'char (*X)' or 'int (*XX)(void)'
1514 ParseParenDeclarator(D);
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001515 } else if (D.mayOmitIdentifier()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001516 // This could be something simple like "int" (in which case the declarator
1517 // portion is empty), if an abstract-declarator is allowed.
1518 D.SetIdentifier(0, Tok.getLocation());
1519 } else {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00001520 if (getLang().CPlusPlus)
1521 Diag(Tok, diag::err_expected_unqualified_id);
1522 else
Chris Lattnerf006a222008-11-18 07:48:38 +00001523 Diag(Tok, diag::err_expected_ident_lparen);
Chris Lattner4b009652007-07-25 00:24:17 +00001524 D.SetIdentifier(0, Tok.getLocation());
Chris Lattnercd61d592008-11-11 06:13:16 +00001525 D.setInvalidType(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001526 }
1527
Argiris Kirtzidisebdc8ea2008-11-26 22:40:03 +00001528 PastIdentifier:
Chris Lattner4b009652007-07-25 00:24:17 +00001529 assert(D.isPastIdentifier() &&
1530 "Haven't past the location of the identifier yet?");
1531
1532 while (1) {
Chris Lattner34a01ad2007-10-09 17:33:22 +00001533 if (Tok.is(tok::l_paren)) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001534 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
1535 // In such a case, check if we actually have a function declarator; if it
1536 // is not, the declarator has been fully parsed.
Chris Lattner1f185292008-10-20 02:05:46 +00001537 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
1538 // When not in file scope, warn for ambiguous function declarators, just
1539 // in case the author intended it as a variable definition.
1540 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
1541 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
1542 break;
1543 }
Chris Lattnera0d056d2008-04-06 05:45:57 +00001544 ParseFunctionDeclarator(ConsumeParen(), D);
Chris Lattner34a01ad2007-10-09 17:33:22 +00001545 } else if (Tok.is(tok::l_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001546 ParseBracketDeclarator(D);
1547 } else {
1548 break;
1549 }
1550 }
1551}
1552
Chris Lattnera0d056d2008-04-06 05:45:57 +00001553/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
1554/// only called before the identifier, so these are most likely just grouping
1555/// parens for precedence. If we find that these are actually function
1556/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1557///
1558/// direct-declarator:
1559/// '(' declarator ')'
1560/// [GNU] '(' attributes declarator ')'
Chris Lattner1f185292008-10-20 02:05:46 +00001561/// direct-declarator '(' parameter-type-list ')'
1562/// direct-declarator '(' identifier-list[opt] ')'
1563/// [GNU] direct-declarator '(' parameter-forward-declarations
1564/// parameter-type-list[opt] ')'
Chris Lattnera0d056d2008-04-06 05:45:57 +00001565///
1566void Parser::ParseParenDeclarator(Declarator &D) {
1567 SourceLocation StartLoc = ConsumeParen();
1568 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1569
Chris Lattner1f185292008-10-20 02:05:46 +00001570 // Eat any attributes before we look at whether this is a grouping or function
1571 // declarator paren. If this is a grouping paren, the attribute applies to
1572 // the type being built up, for example:
1573 // int (__attribute__(()) *x)(long y)
1574 // If this ends up not being a grouping paren, the attribute applies to the
1575 // first argument, for example:
1576 // int (__attribute__(()) int x)
1577 // In either case, we need to eat any attributes to be able to determine what
1578 // sort of paren this is.
1579 //
1580 AttributeList *AttrList = 0;
1581 bool RequiresArg = false;
1582 if (Tok.is(tok::kw___attribute)) {
1583 AttrList = ParseAttributes();
1584
1585 // We require that the argument list (if this is a non-grouping paren) be
1586 // present even if the attribute list was empty.
1587 RequiresArg = true;
1588 }
1589
Chris Lattnera0d056d2008-04-06 05:45:57 +00001590 // If we haven't past the identifier yet (or where the identifier would be
1591 // stored, if this is an abstract declarator), then this is probably just
1592 // grouping parens. However, if this could be an abstract-declarator, then
1593 // this could also be the start of function arguments (consider 'void()').
1594 bool isGrouping;
1595
1596 if (!D.mayOmitIdentifier()) {
1597 // If this can't be an abstract-declarator, this *must* be a grouping
1598 // paren, because we haven't seen the identifier yet.
1599 isGrouping = true;
1600 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Argiris Kirtzidis1c64fdc2008-10-06 00:07:55 +00001601 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
Chris Lattnera0d056d2008-04-06 05:45:57 +00001602 isDeclarationSpecifier()) { // 'int(int)' is a function.
1603 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1604 // considered to be a type, not a K&R identifier-list.
1605 isGrouping = false;
1606 } else {
1607 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1608 isGrouping = true;
1609 }
1610
1611 // If this is a grouping paren, handle:
1612 // direct-declarator: '(' declarator ')'
1613 // direct-declarator: '(' attributes declarator ')'
1614 if (isGrouping) {
Argiris Kirtzidis0941ff42008-10-07 10:21:57 +00001615 bool hadGroupingParens = D.hasGroupingParens();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001616 D.setGroupingParens(true);
Chris Lattner1f185292008-10-20 02:05:46 +00001617 if (AttrList)
1618 D.AddAttributes(AttrList);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001619
Sebastian Redl19fec9d2008-11-21 19:14:01 +00001620 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnera0d056d2008-04-06 05:45:57 +00001621 // Match the ')'.
1622 MatchRHSPunctuation(tok::r_paren, StartLoc);
Argiris Kirtzidis0941ff42008-10-07 10:21:57 +00001623
1624 D.setGroupingParens(hadGroupingParens);
Chris Lattnera0d056d2008-04-06 05:45:57 +00001625 return;
1626 }
1627
1628 // Okay, if this wasn't a grouping paren, it must be the start of a function
1629 // argument list. Recognize that this declarator will never have an
Chris Lattner1f185292008-10-20 02:05:46 +00001630 // identifier (and remember where it would have been), then call into
1631 // ParseFunctionDeclarator to handle of argument list.
Chris Lattnera0d056d2008-04-06 05:45:57 +00001632 D.SetIdentifier(0, Tok.getLocation());
1633
Chris Lattner1f185292008-10-20 02:05:46 +00001634 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
Chris Lattnera0d056d2008-04-06 05:45:57 +00001635}
1636
1637/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1638/// declarator D up to a paren, which indicates that we are parsing function
1639/// arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001640///
Chris Lattner1f185292008-10-20 02:05:46 +00001641/// If AttrList is non-null, then the caller parsed those arguments immediately
1642/// after the open paren - they should be considered to be the first argument of
1643/// a parameter. If RequiresArg is true, then the first argument of the
1644/// function is required to be present and required to not be an identifier
1645/// list.
1646///
Chris Lattner4b009652007-07-25 00:24:17 +00001647/// This method also handles this portion of the grammar:
1648/// parameter-type-list: [C99 6.7.5]
1649/// parameter-list
1650/// parameter-list ',' '...'
1651///
1652/// parameter-list: [C99 6.7.5]
1653/// parameter-declaration
1654/// parameter-list ',' parameter-declaration
1655///
1656/// parameter-declaration: [C99 6.7.5]
1657/// declaration-specifiers declarator
Chris Lattner3e254fb2008-04-08 04:40:51 +00001658/// [C++] declaration-specifiers declarator '=' assignment-expression
Chris Lattner4b009652007-07-25 00:24:17 +00001659/// [GNU] declaration-specifiers declarator attributes
1660/// declaration-specifiers abstract-declarator[opt]
Chris Lattner97316c02008-04-10 02:22:51 +00001661/// [C++] declaration-specifiers abstract-declarator[opt]
1662/// '=' assignment-expression
Chris Lattner4b009652007-07-25 00:24:17 +00001663/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
1664///
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001665/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
1666/// and "exception-specification[opt]"(TODO).
1667///
Chris Lattner1f185292008-10-20 02:05:46 +00001668void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
1669 AttributeList *AttrList,
1670 bool RequiresArg) {
Chris Lattnera0d056d2008-04-06 05:45:57 +00001671 // lparen is already consumed!
1672 assert(D.isPastIdentifier() && "Should not call before identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +00001673
Chris Lattner1f185292008-10-20 02:05:46 +00001674 // This parameter list may be empty.
Chris Lattner34a01ad2007-10-09 17:33:22 +00001675 if (Tok.is(tok::r_paren)) {
Chris Lattner1f185292008-10-20 02:05:46 +00001676 if (RequiresArg) {
Chris Lattnerf006a222008-11-18 07:48:38 +00001677 Diag(Tok, diag::err_argument_required_after_attribute);
Chris Lattner1f185292008-10-20 02:05:46 +00001678 delete AttrList;
1679 }
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001680
1681 ConsumeParen(); // Eat the closing ')'.
1682
1683 // cv-qualifier-seq[opt].
1684 DeclSpec DS;
1685 if (getLang().CPlusPlus) {
1686 ParseTypeQualifierListOpt(DS);
Douglas Gregor90a2c972008-11-25 03:22:00 +00001687
1688 // Parse exception-specification[opt].
1689 if (Tok.is(tok::kw_throw))
1690 ParseExceptionSpecification();
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001691 }
1692
Chris Lattner9f7564b2008-04-06 06:57:35 +00001693 // Remember that we parsed a function type, and remember the attributes.
Chris Lattner4b009652007-07-25 00:24:17 +00001694 // int() -> no prototype, no '...'.
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001695 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
Chris Lattner9f7564b2008-04-06 06:57:35 +00001696 /*variadic*/ false,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001697 /*arglist*/ 0, 0,
1698 DS.getTypeQualifiers(),
1699 LParenLoc));
Chris Lattner9f7564b2008-04-06 06:57:35 +00001700 return;
Chris Lattner1f185292008-10-20 02:05:46 +00001701 }
1702
1703 // Alternatively, this parameter list may be an identifier list form for a
1704 // K&R-style function: void foo(a,b,c)
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001705 if (!getLang().CPlusPlus && Tok.is(tok::identifier) &&
Chris Lattner1f185292008-10-20 02:05:46 +00001706 // K&R identifier lists can't have typedefs as identifiers, per
1707 // C99 6.7.5.3p11.
1708 !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1709 if (RequiresArg) {
Chris Lattnerf006a222008-11-18 07:48:38 +00001710 Diag(Tok, diag::err_argument_required_after_attribute);
Chris Lattner1f185292008-10-20 02:05:46 +00001711 delete AttrList;
1712 }
1713
Chris Lattner4b009652007-07-25 00:24:17 +00001714 // Identifier list. Note that '(' identifier-list ')' is only allowed for
1715 // normal declarators, not for abstract-declarators.
Chris Lattner35d9c912008-04-06 06:34:08 +00001716 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
Chris Lattner9f7564b2008-04-06 06:57:35 +00001717 }
1718
1719 // Finally, a normal, non-empty parameter type list.
1720
1721 // Build up an array of information about the parsed arguments.
1722 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001723
1724 // Enter function-declaration scope, limiting any declarators to the
1725 // function prototype scope, including parameter declarators.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001726 EnterScope(Scope::FnScope|Scope::DeclScope);
Chris Lattner9f7564b2008-04-06 06:57:35 +00001727
1728 bool IsVariadic = false;
1729 while (1) {
1730 if (Tok.is(tok::ellipsis)) {
1731 IsVariadic = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001732
Chris Lattner9f7564b2008-04-06 06:57:35 +00001733 // Check to see if this is "void(...)" which is not allowed.
Argiris Kirtzidis1c64fdc2008-10-06 00:07:55 +00001734 if (!getLang().CPlusPlus && ParamInfo.empty()) {
Chris Lattner9f7564b2008-04-06 06:57:35 +00001735 // Otherwise, parse parameter type list. If it starts with an
1736 // ellipsis, diagnose the malformed function.
1737 Diag(Tok, diag::err_ellipsis_first_arg);
1738 IsVariadic = false; // Treat this like 'void()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001739 }
Chris Lattnere5db29f2008-01-31 06:10:07 +00001740
Chris Lattner9f7564b2008-04-06 06:57:35 +00001741 ConsumeToken(); // Consume the ellipsis.
1742 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001743 }
1744
Chris Lattner9f7564b2008-04-06 06:57:35 +00001745 SourceLocation DSStart = Tok.getLocation();
Chris Lattner4b009652007-07-25 00:24:17 +00001746
Chris Lattner9f7564b2008-04-06 06:57:35 +00001747 // Parse the declaration-specifiers.
1748 DeclSpec DS;
Chris Lattner1f185292008-10-20 02:05:46 +00001749
1750 // If the caller parsed attributes for the first argument, add them now.
1751 if (AttrList) {
1752 DS.AddAttributes(AttrList);
1753 AttrList = 0; // Only apply the attributes to the first parameter.
1754 }
Chris Lattner9f7564b2008-04-06 06:57:35 +00001755 ParseDeclarationSpecifiers(DS);
1756
1757 // Parse the declarator. This is "PrototypeContext", because we must
1758 // accept either 'declarator' or 'abstract-declarator' here.
1759 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1760 ParseDeclarator(ParmDecl);
1761
1762 // Parse GNU attributes, if present.
1763 if (Tok.is(tok::kw___attribute))
1764 ParmDecl.AddAttributes(ParseAttributes());
1765
Chris Lattner9f7564b2008-04-06 06:57:35 +00001766 // Remember this parsed parameter in ParamInfo.
1767 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1768
Chris Lattner9f7564b2008-04-06 06:57:35 +00001769 // If no parameter was specified, verify that *something* was specified,
1770 // otherwise we have a missing type and identifier.
1771 if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1772 ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1773 // Completely missing, emit error.
1774 Diag(DSStart, diag::err_missing_param);
1775 } else {
1776 // Otherwise, we have something. Add it and let semantic analysis try
1777 // to grok it and add the result to the ParamInfo we are building.
1778
1779 // Inform the actions module about the parameter declarator, so it gets
1780 // added to the current scope.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001781 DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1782
1783 // Parse the default argument, if any. We parse the default
1784 // arguments in all dialects; the semantic analysis in
1785 // ActOnParamDefaultArgument will reject the default argument in
1786 // C.
1787 if (Tok.is(tok::equal)) {
1788 SourceLocation EqualLoc = Tok.getLocation();
1789
1790 // Consume the '='.
1791 ConsumeToken();
1792
1793 // Parse the default argument
Chris Lattner3e254fb2008-04-08 04:40:51 +00001794 ExprResult DefArgResult = ParseAssignmentExpression();
1795 if (DefArgResult.isInvalid) {
1796 SkipUntil(tok::comma, tok::r_paren, true, true);
1797 } else {
1798 // Inform the actions module about the default argument
1799 Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.Val);
1800 }
1801 }
Chris Lattner9f7564b2008-04-06 06:57:35 +00001802
1803 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001804 ParmDecl.getIdentifierLoc(), Param));
Chris Lattner9f7564b2008-04-06 06:57:35 +00001805 }
1806
1807 // If the next token is a comma, consume it and keep reading arguments.
1808 if (Tok.isNot(tok::comma)) break;
1809
1810 // Consume the comma.
1811 ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +00001812 }
1813
Chris Lattner9f7564b2008-04-06 06:57:35 +00001814 // Leave prototype scope.
1815 ExitScope();
1816
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001817 // If we have the closing ')', eat it.
1818 MatchRHSPunctuation(tok::r_paren, LParenLoc);
1819
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001820 DeclSpec DS;
1821 if (getLang().CPlusPlus) {
Douglas Gregor90a2c972008-11-25 03:22:00 +00001822 // Parse cv-qualifier-seq[opt].
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001823 ParseTypeQualifierListOpt(DS);
Douglas Gregor90a2c972008-11-25 03:22:00 +00001824
1825 // Parse exception-specification[opt].
1826 if (Tok.is(tok::kw_throw))
1827 ParseExceptionSpecification();
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001828 }
1829
Chris Lattner4b009652007-07-25 00:24:17 +00001830 // Remember that we parsed a function type, and remember the attributes.
Chris Lattner9f7564b2008-04-06 06:57:35 +00001831 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
1832 &ParamInfo[0], ParamInfo.size(),
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001833 DS.getTypeQualifiers(),
Chris Lattner9f7564b2008-04-06 06:57:35 +00001834 LParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001835}
1836
Chris Lattner35d9c912008-04-06 06:34:08 +00001837/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
1838/// we found a K&R-style identifier list instead of a type argument list. The
1839/// current token is known to be the first identifier in the list.
1840///
1841/// identifier-list: [C99 6.7.5]
1842/// identifier
1843/// identifier-list ',' identifier
1844///
1845void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
1846 Declarator &D) {
1847 // Build up an array of information about the parsed arguments.
1848 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1849 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1850
1851 // If there was no identifier specified for the declarator, either we are in
1852 // an abstract-declarator, or we are in a parameter declarator which was found
1853 // to be abstract. In abstract-declarators, identifier lists are not valid:
1854 // diagnose this.
1855 if (!D.getIdentifier())
1856 Diag(Tok, diag::ext_ident_list_in_param);
1857
1858 // Tok is known to be the first identifier in the list. Remember this
1859 // identifier in ParamInfo.
Chris Lattnerc337fa22008-04-06 06:50:56 +00001860 ParamsSoFar.insert(Tok.getIdentifierInfo());
Chris Lattner35d9c912008-04-06 06:34:08 +00001861 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1862 Tok.getLocation(), 0));
1863
Chris Lattner113a56b2008-04-06 06:39:19 +00001864 ConsumeToken(); // eat the first identifier.
Chris Lattner35d9c912008-04-06 06:34:08 +00001865
1866 while (Tok.is(tok::comma)) {
1867 // Eat the comma.
1868 ConsumeToken();
1869
Chris Lattner113a56b2008-04-06 06:39:19 +00001870 // If this isn't an identifier, report the error and skip until ')'.
Chris Lattner35d9c912008-04-06 06:34:08 +00001871 if (Tok.isNot(tok::identifier)) {
1872 Diag(Tok, diag::err_expected_ident);
Chris Lattner113a56b2008-04-06 06:39:19 +00001873 SkipUntil(tok::r_paren);
1874 return;
Chris Lattner35d9c912008-04-06 06:34:08 +00001875 }
Chris Lattneracb67d92008-04-06 06:47:48 +00001876
Chris Lattner35d9c912008-04-06 06:34:08 +00001877 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
Chris Lattneracb67d92008-04-06 06:47:48 +00001878
1879 // Reject 'typedef int y; int test(x, y)', but continue parsing.
1880 if (Actions.isTypeName(*ParmII, CurScope))
Chris Lattner8f7db152008-11-19 07:37:42 +00001881 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
Chris Lattner35d9c912008-04-06 06:34:08 +00001882
1883 // Verify that the argument identifier has not already been mentioned.
1884 if (!ParamsSoFar.insert(ParmII)) {
Chris Lattner8f7db152008-11-19 07:37:42 +00001885 Diag(Tok, diag::err_param_redefinition) << ParmII;
Chris Lattner113a56b2008-04-06 06:39:19 +00001886 } else {
1887 // Remember this identifier in ParamInfo.
Chris Lattner35d9c912008-04-06 06:34:08 +00001888 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1889 Tok.getLocation(), 0));
Chris Lattner113a56b2008-04-06 06:39:19 +00001890 }
Chris Lattner35d9c912008-04-06 06:34:08 +00001891
1892 // Eat the identifier.
1893 ConsumeToken();
1894 }
1895
Chris Lattner113a56b2008-04-06 06:39:19 +00001896 // Remember that we parsed a function type, and remember the attributes. This
1897 // function type is always a K&R style function type, which is not varargs and
1898 // has no prototype.
1899 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
1900 &ParamInfo[0], ParamInfo.size(),
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001901 /*TypeQuals*/0, LParenLoc));
Chris Lattner35d9c912008-04-06 06:34:08 +00001902
1903 // If we have the closing ')', eat it and we're done.
Chris Lattner113a56b2008-04-06 06:39:19 +00001904 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Chris Lattner35d9c912008-04-06 06:34:08 +00001905}
Chris Lattnera0d056d2008-04-06 05:45:57 +00001906
Chris Lattner4b009652007-07-25 00:24:17 +00001907/// [C90] direct-declarator '[' constant-expression[opt] ']'
1908/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1909/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1910/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1911/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
1912void Parser::ParseBracketDeclarator(Declarator &D) {
1913 SourceLocation StartLoc = ConsumeBracket();
1914
1915 // If valid, this location is the position where we read the 'static' keyword.
1916 SourceLocation StaticLoc;
Chris Lattner34a01ad2007-10-09 17:33:22 +00001917 if (Tok.is(tok::kw_static))
Chris Lattner4b009652007-07-25 00:24:17 +00001918 StaticLoc = ConsumeToken();
1919
1920 // If there is a type-qualifier-list, read it now.
1921 DeclSpec DS;
1922 ParseTypeQualifierListOpt(DS);
1923
1924 // If we haven't already read 'static', check to see if there is one after the
1925 // type-qualifier-list.
Chris Lattner34a01ad2007-10-09 17:33:22 +00001926 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
Chris Lattner4b009652007-07-25 00:24:17 +00001927 StaticLoc = ConsumeToken();
1928
1929 // Handle "direct-declarator [ type-qual-list[opt] * ]".
1930 bool isStar = false;
1931 ExprResult NumElements(false);
Chris Lattner44f6d9d2008-04-06 05:26:30 +00001932
1933 // Handle the case where we have '[*]' as the array size. However, a leading
1934 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
1935 // the the token after the star is a ']'. Since stars in arrays are
1936 // infrequent, use of lookahead is not costly here.
1937 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattner1bb39512008-04-06 05:27:21 +00001938 ConsumeToken(); // Eat the '*'.
Chris Lattner4b009652007-07-25 00:24:17 +00001939
Chris Lattner44f6d9d2008-04-06 05:26:30 +00001940 if (StaticLoc.isValid())
1941 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1942 StaticLoc = SourceLocation(); // Drop the static.
1943 isStar = true;
Chris Lattner34a01ad2007-10-09 17:33:22 +00001944 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001945 // Parse the assignment-expression now.
1946 NumElements = ParseAssignmentExpression();
1947 }
1948
1949 // If there was an error parsing the assignment-expression, recover.
1950 if (NumElements.isInvalid) {
1951 // If the expression was invalid, skip it.
1952 SkipUntil(tok::r_square);
1953 return;
1954 }
1955
1956 MatchRHSPunctuation(tok::r_square, StartLoc);
1957
1958 // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1959 // it was not a constant expression.
1960 if (!getLang().C99) {
1961 // TODO: check C90 array constant exprness.
1962 if (isStar || StaticLoc.isValid() ||
1963 0/*TODO: NumElts is not a C90 constantexpr */)
1964 Diag(StartLoc, diag::ext_c99_array_usage);
1965 }
1966
1967 // Remember that we parsed a pointer type, and remember the type-quals.
1968 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1969 StaticLoc.isValid(), isStar,
1970 NumElements.Val, StartLoc));
1971}
1972
Argiris Kirtzidisc2a384d2008-09-05 11:26:19 +00001973/// [GNU] typeof-specifier:
1974/// typeof ( expressions )
1975/// typeof ( type-name )
1976/// [GNU/C++] typeof unary-expression
Steve Naroff7cbb1462007-07-31 12:34:36 +00001977///
1978void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner34a01ad2007-10-09 17:33:22 +00001979 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Steve Naroff14bbce82007-08-02 02:53:48 +00001980 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
Steve Naroff7cbb1462007-07-31 12:34:36 +00001981 SourceLocation StartLoc = ConsumeToken();
1982
Chris Lattner34a01ad2007-10-09 17:33:22 +00001983 if (Tok.isNot(tok::l_paren)) {
Argiris Kirtzidisc2a384d2008-09-05 11:26:19 +00001984 if (!getLang().CPlusPlus) {
Chris Lattnerb1753422008-11-23 21:45:46 +00001985 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
Argiris Kirtzidisc2a384d2008-09-05 11:26:19 +00001986 return;
1987 }
1988
1989 ExprResult Result = ParseCastExpression(true/*isUnaryExpression*/);
1990 if (Result.isInvalid)
1991 return;
1992
1993 const char *PrevSpec = 0;
1994 // Check for duplicate type specifiers.
1995 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
1996 Result.Val))
Chris Lattnerf006a222008-11-18 07:48:38 +00001997 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Argiris Kirtzidisc2a384d2008-09-05 11:26:19 +00001998
1999 // FIXME: Not accurate, the range gets one token more than it should.
2000 DS.SetRangeEnd(Tok.getLocation());
Steve Naroff14bbce82007-08-02 02:53:48 +00002001 return;
Steve Naroff7cbb1462007-07-31 12:34:36 +00002002 }
Argiris Kirtzidisc2a384d2008-09-05 11:26:19 +00002003
Steve Naroff7cbb1462007-07-31 12:34:36 +00002004 SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
2005
Argiris Kirtzidis3276cbc2008-10-05 19:56:22 +00002006 if (isTypeIdInParens()) {
Steve Naroff7cbb1462007-07-31 12:34:36 +00002007 TypeTy *Ty = ParseTypeName();
2008
Steve Naroff4c255ab2007-07-31 23:56:32 +00002009 assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
2010
Chris Lattner34a01ad2007-10-09 17:33:22 +00002011 if (Tok.isNot(tok::r_paren)) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00002012 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00002013 return;
2014 }
2015 RParenLoc = ConsumeParen();
2016 const char *PrevSpec = 0;
2017 // Check for duplicate type specifiers (e.g. "int typeof(int)").
2018 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
Chris Lattnerf006a222008-11-18 07:48:38 +00002019 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Steve Naroff7cbb1462007-07-31 12:34:36 +00002020 } else { // we have an expression.
2021 ExprResult Result = ParseExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +00002022 ExprGuard ResultGuard(Actions, Result);
Steve Naroff4c255ab2007-07-31 23:56:32 +00002023
Chris Lattner34a01ad2007-10-09 17:33:22 +00002024 if (Result.isInvalid || Tok.isNot(tok::r_paren)) {
Steve Naroff4c255ab2007-07-31 23:56:32 +00002025 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Steve Naroff14bbce82007-08-02 02:53:48 +00002026 return;
2027 }
2028 RParenLoc = ConsumeParen();
2029 const char *PrevSpec = 0;
2030 // Check for duplicate type specifiers (e.g. "int typeof(int)").
2031 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Sebastian Redl6008ac32008-11-25 22:21:31 +00002032 ResultGuard.take()))
Chris Lattnerf006a222008-11-18 07:48:38 +00002033 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Steve Naroff7cbb1462007-07-31 12:34:36 +00002034 }
Argiris Kirtzidis4d923942008-08-16 10:21:33 +00002035 DS.SetRangeEnd(RParenLoc);
Steve Naroff7cbb1462007-07-31 12:34:36 +00002036}
2037
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00002038