blob: 9eab4fda151e7273f4ab8e14e35d803f6d3b2fdd [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Parser.cpp - C Language Family Parser ----------------------------===//
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 Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/DeclSpec.h"
16#include "clang/Parse/Scope.h"
17using namespace clang;
18
19Parser::Parser(Preprocessor &pp, Action &actions)
20 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()) {
21 Tok.setKind(tok::eof);
22 CurScope = 0;
23 NumCachedScopes = 0;
24 ParenCount = BracketCount = BraceCount = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000025 ObjCImpDecl = 0;
Argiris Kirtzidis9d784332008-06-24 22:12:16 +000026 // Instantiate a LexedMethodsForTopClass for all the non-nested classes.
27 PushTopClassStack();
Chris Lattner4b009652007-07-25 00:24:17 +000028}
29
30/// Out-of-line virtual destructor to provide home for Action class.
31Action::~Action() {}
32
33
34void Parser::Diag(SourceLocation Loc, unsigned DiagID,
35 const std::string &Msg) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000036 Diags.Report(FullSourceLoc(Loc,PP.getSourceManager()), DiagID, &Msg, 1);
Chris Lattner4b009652007-07-25 00:24:17 +000037}
38
Chris Lattnerda8aad92008-07-26 00:16:04 +000039void Parser::Diag(SourceLocation Loc, unsigned DiagID, const SourceRange &R) {
40 Diags.Report(FullSourceLoc(Loc,PP.getSourceManager()), DiagID, 0, 0,
41 &R, 1);
42}
43
44
Chris Lattner4b009652007-07-25 00:24:17 +000045/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
46/// this helper function matches and consumes the specified RHS token if
47/// present. If not present, it emits the specified diagnostic indicating
48/// that the parser failed to match the RHS of the token at LHSLoc. LHSName
49/// should be the name of the unmatched LHS token.
50SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
51 SourceLocation LHSLoc) {
Mike Stumpeda58eb2008-06-19 19:28:49 +000052
Chris Lattner17a5fb62007-10-09 17:23:58 +000053 if (Tok.is(RHSTok))
Chris Lattner4b009652007-07-25 00:24:17 +000054 return ConsumeAnyToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +000055
Chris Lattner4b009652007-07-25 00:24:17 +000056 SourceLocation R = Tok.getLocation();
57 const char *LHSName = "unknown";
58 diag::kind DID = diag::err_parse_error;
59 switch (RHSTok) {
60 default: break;
61 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
62 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
63 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
64 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
65 }
66 Diag(Tok, DID);
67 Diag(LHSLoc, diag::err_matching, LHSName);
68 SkipUntil(RHSTok);
69 return R;
70}
71
72/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
73/// input. If so, it is consumed and false is returned.
74///
75/// If the input is malformed, this emits the specified diagnostic. Next, if
76/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
77/// returned.
78bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
79 const char *Msg, tok::TokenKind SkipToTok) {
Chris Lattner17a5fb62007-10-09 17:23:58 +000080 if (Tok.is(ExpectedTok)) {
Chris Lattner4b009652007-07-25 00:24:17 +000081 ConsumeAnyToken();
82 return false;
83 }
Mike Stumpeda58eb2008-06-19 19:28:49 +000084
Chris Lattner4b009652007-07-25 00:24:17 +000085 Diag(Tok, DiagID, Msg);
86 if (SkipToTok != tok::unknown)
87 SkipUntil(SkipToTok);
88 return true;
89}
90
91//===----------------------------------------------------------------------===//
92// Error recovery.
93//===----------------------------------------------------------------------===//
94
95/// SkipUntil - Read tokens until we get to the specified token, then consume
96/// it (unless DontConsume is true). Because we cannot guarantee that the
97/// token will ever occur, this skips to the next token, or to some likely
98/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
99/// character.
Mike Stumpeda58eb2008-06-19 19:28:49 +0000100///
Chris Lattner4b009652007-07-25 00:24:17 +0000101/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stumpeda58eb2008-06-19 19:28:49 +0000102/// returns false.
Chris Lattner4b009652007-07-25 00:24:17 +0000103bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
104 bool StopAtSemi, bool DontConsume) {
105 // We always want this function to skip at least one token if the first token
106 // isn't T and if not at EOF.
107 bool isFirstTokenSkipped = true;
108 while (1) {
109 // If we found one of the tokens, stop and return true.
110 for (unsigned i = 0; i != NumToks; ++i) {
Chris Lattner17a5fb62007-10-09 17:23:58 +0000111 if (Tok.is(Toks[i])) {
Chris Lattner4b009652007-07-25 00:24:17 +0000112 if (DontConsume) {
113 // Noop, don't consume the token.
114 } else {
115 ConsumeAnyToken();
116 }
117 return true;
118 }
119 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000120
Chris Lattner4b009652007-07-25 00:24:17 +0000121 switch (Tok.getKind()) {
122 case tok::eof:
123 // Ran out of tokens.
124 return false;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000125
Chris Lattner4b009652007-07-25 00:24:17 +0000126 case tok::l_paren:
127 // Recursively skip properly-nested parens.
128 ConsumeParen();
129 SkipUntil(tok::r_paren, false);
130 break;
131 case tok::l_square:
132 // Recursively skip properly-nested square brackets.
133 ConsumeBracket();
134 SkipUntil(tok::r_square, false);
135 break;
136 case tok::l_brace:
137 // Recursively skip properly-nested braces.
138 ConsumeBrace();
139 SkipUntil(tok::r_brace, false);
140 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000141
Chris Lattner4b009652007-07-25 00:24:17 +0000142 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
143 // Since the user wasn't looking for this token (if they were, it would
144 // already be handled), this isn't balanced. If there is a LHS token at a
145 // higher level, we will assume that this matches the unbalanced token
146 // and return it. Otherwise, this is a spurious RHS token, which we skip.
147 case tok::r_paren:
148 if (ParenCount && !isFirstTokenSkipped)
149 return false; // Matches something.
150 ConsumeParen();
151 break;
152 case tok::r_square:
153 if (BracketCount && !isFirstTokenSkipped)
154 return false; // Matches something.
155 ConsumeBracket();
156 break;
157 case tok::r_brace:
158 if (BraceCount && !isFirstTokenSkipped)
159 return false; // Matches something.
160 ConsumeBrace();
161 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000162
Chris Lattner4b009652007-07-25 00:24:17 +0000163 case tok::string_literal:
164 case tok::wide_string_literal:
165 ConsumeStringToken();
166 break;
167 case tok::semi:
168 if (StopAtSemi)
169 return false;
170 // FALL THROUGH.
171 default:
172 // Skip this token.
173 ConsumeToken();
174 break;
175 }
176 isFirstTokenSkipped = false;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000177 }
Chris Lattner4b009652007-07-25 00:24:17 +0000178}
179
180//===----------------------------------------------------------------------===//
181// Scope manipulation
182//===----------------------------------------------------------------------===//
183
184/// EnterScope - Start a new scope.
185void Parser::EnterScope(unsigned ScopeFlags) {
186 if (NumCachedScopes) {
187 Scope *N = ScopeCache[--NumCachedScopes];
188 N->Init(CurScope, ScopeFlags);
189 CurScope = N;
190 } else {
191 CurScope = new Scope(CurScope, ScopeFlags);
192 }
193}
194
195/// ExitScope - Pop a scope off the scope stack.
196void Parser::ExitScope() {
197 assert(CurScope && "Scope imbalance!");
198
Chris Lattner62231492007-10-09 20:37:18 +0000199 // Inform the actions module that this scope is going away if there are any
200 // decls in it.
201 if (!CurScope->decl_empty())
Steve Naroff9637a9b2007-10-09 22:01:59 +0000202 Actions.ActOnPopScope(Tok.getLocation(), CurScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000203
Chris Lattner4b009652007-07-25 00:24:17 +0000204 Scope *OldScope = CurScope;
205 CurScope = OldScope->getParent();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000206
Chris Lattner4b009652007-07-25 00:24:17 +0000207 if (NumCachedScopes == ScopeCacheSize)
208 delete OldScope;
209 else
210 ScopeCache[NumCachedScopes++] = OldScope;
211}
212
213
214
215
216//===----------------------------------------------------------------------===//
217// C99 6.9: External Definitions.
218//===----------------------------------------------------------------------===//
219
220Parser::~Parser() {
221 // If we still have scopes active, delete the scope tree.
222 delete CurScope;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000223
Chris Lattner4b009652007-07-25 00:24:17 +0000224 // Free the scope cache.
225 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
226 delete ScopeCache[i];
227}
228
229/// Initialize - Warm up the parser.
230///
231void Parser::Initialize() {
232 // Prime the lexer look-ahead.
233 ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000234
Chris Lattnera7549902007-08-26 06:24:45 +0000235 // Create the translation unit scope. Install it as the current scope.
Chris Lattner4b009652007-07-25 00:24:17 +0000236 assert(CurScope == 0 && "A scope is already active?");
Chris Lattnera7549902007-08-26 06:24:45 +0000237 EnterScope(Scope::DeclScope);
Steve Naroff9637a9b2007-10-09 22:01:59 +0000238 Actions.ActOnTranslationUnitScope(Tok.getLocation(), CurScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000239
Chris Lattner17a5fb62007-10-09 17:23:58 +0000240 if (Tok.is(tok::eof) &&
Chris Lattner7bdc85d2007-08-25 05:47:03 +0000241 !getLang().CPlusPlus) // Empty source file is an extension in C
Chris Lattner4b009652007-07-25 00:24:17 +0000242 Diag(Tok, diag::ext_empty_source_file);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000243
Chris Lattner32352462007-08-29 22:54:08 +0000244 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremenek42730c52008-01-07 19:49:32 +0000245 // Referenced in Parser::ParseObjCTypeQualifierList.
Chris Lattner32352462007-08-29 22:54:08 +0000246 if (getLang().ObjC1) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000247 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
248 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
249 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
250 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
251 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
252 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner32352462007-08-29 22:54:08 +0000253 }
Fariborz Jahanian6668b8c2007-08-31 16:11:31 +0000254 if (getLang().ObjC2) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000255 ObjCPropertyAttrs[objc_readonly] = &PP.getIdentifierTable().get("readonly");
256 ObjCPropertyAttrs[objc_getter] = &PP.getIdentifierTable().get("getter");
257 ObjCPropertyAttrs[objc_setter] = &PP.getIdentifierTable().get("setter");
258 ObjCPropertyAttrs[objc_assign] = &PP.getIdentifierTable().get("assign");
Mike Stumpeda58eb2008-06-19 19:28:49 +0000259 ObjCPropertyAttrs[objc_readwrite] =
Fariborz Jahanian6668b8c2007-08-31 16:11:31 +0000260 &PP.getIdentifierTable().get("readwrite");
Ted Kremenek42730c52008-01-07 19:49:32 +0000261 ObjCPropertyAttrs[objc_retain] = &PP.getIdentifierTable().get("retain");
262 ObjCPropertyAttrs[objc_copy] = &PP.getIdentifierTable().get("copy");
Mike Stumpeda58eb2008-06-19 19:28:49 +0000263 ObjCPropertyAttrs[objc_nonatomic] =
Fariborz Jahanian6668b8c2007-08-31 16:11:31 +0000264 &PP.getIdentifierTable().get("nonatomic");
Fariborz Jahanian9e920f32008-01-02 22:54:34 +0000265 ObjCForCollectionInKW = &PP.getIdentifierTable().get("in");
Fariborz Jahanian6668b8c2007-08-31 16:11:31 +0000266 }
Chris Lattner4b009652007-07-25 00:24:17 +0000267}
268
269/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
270/// action tells us to. This returns true if the EOF was encountered.
Steve Naroffca44ffd2007-11-29 23:05:20 +0000271bool Parser::ParseTopLevelDecl(DeclTy*& Result) {
272 Result = 0;
Chris Lattner17a5fb62007-10-09 17:23:58 +0000273 if (Tok.is(tok::eof)) return true;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000274
Steve Naroffca44ffd2007-11-29 23:05:20 +0000275 Result = ParseExternalDeclaration();
Chris Lattner4b009652007-07-25 00:24:17 +0000276 return false;
277}
278
279/// Finalize - Shut down the parser.
280///
281void Parser::Finalize() {
282 ExitScope();
283 assert(CurScope == 0 && "Scope imbalance!");
284}
285
286/// ParseTranslationUnit:
287/// translation-unit: [C99 6.9]
Mike Stumpeda58eb2008-06-19 19:28:49 +0000288/// external-declaration
289/// translation-unit external-declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000290void Parser::ParseTranslationUnit() {
291 Initialize();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000292
Steve Naroffca44ffd2007-11-29 23:05:20 +0000293 DeclTy *Res;
294 while (!ParseTopLevelDecl(Res))
Chris Lattner4b009652007-07-25 00:24:17 +0000295 /*parse them all*/;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000296
Chris Lattner4b009652007-07-25 00:24:17 +0000297 Finalize();
298}
299
300/// ParseExternalDeclaration:
301/// external-declaration: [C99 6.9]
Chris Lattner06f4e752007-08-10 20:57:02 +0000302/// function-definition
303/// declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// [EXT] ';'
305/// [GNU] asm-definition
Chris Lattner06f4e752007-08-10 20:57:02 +0000306/// [GNU] __extension__ external-declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000307/// [OBJC] objc-class-definition
308/// [OBJC] objc-class-declaration
309/// [OBJC] objc-alias-declaration
310/// [OBJC] objc-protocol-definition
311/// [OBJC] objc-method-definition
312/// [OBJC] @end
313///
314/// [GNU] asm-definition:
315/// simple-asm-expr ';'
316///
317Parser::DeclTy *Parser::ParseExternalDeclaration() {
318 switch (Tok.getKind()) {
319 case tok::semi:
320 Diag(Tok, diag::ext_top_level_semi);
321 ConsumeToken();
322 // TODO: Invoke action for top-level semicolon.
323 return 0;
Chris Lattner06f4e752007-08-10 20:57:02 +0000324 case tok::kw___extension__: {
325 ConsumeToken();
326 // FIXME: Disable extension warnings.
327 DeclTy *RV = ParseExternalDeclaration();
328 // FIXME: Restore extension warnings.
329 return RV;
330 }
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000331 case tok::kw_asm: {
332 ExprResult Result = ParseSimpleAsm();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000333
Anders Carlssonf41100b2008-02-08 00:23:11 +0000334 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
335 "top-level asm block");
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000336
337 if (!Result.isInvalid)
338 return Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), Result.Val);
Chris Lattnerb36c3652008-05-27 23:32:43 +0000339 return 0;
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000340 }
Chris Lattner4b009652007-07-25 00:24:17 +0000341 case tok::at:
342 // @ is not a legal token unless objc is enabled, no need to check.
Steve Narofffaed3bf2007-09-10 20:51:04 +0000343 return ParseObjCAtDirectives();
Chris Lattner4b009652007-07-25 00:24:17 +0000344 case tok::minus:
Chris Lattner4b009652007-07-25 00:24:17 +0000345 case tok::plus:
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +0000346 if (getLang().ObjC1)
Steve Naroff18c83382007-11-13 23:01:27 +0000347 return ParseObjCMethodDefinition();
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +0000348 else {
Chris Lattner4b009652007-07-25 00:24:17 +0000349 Diag(Tok, diag::err_expected_external_declaration);
350 ConsumeToken();
351 }
352 return 0;
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000353 case tok::kw_namespace:
Chris Lattner4b009652007-07-25 00:24:17 +0000354 case tok::kw_typedef:
Chris Lattner9c135722007-08-25 18:15:16 +0000355 // A function definition cannot start with a these keywords.
Chris Lattner4b009652007-07-25 00:24:17 +0000356 return ParseDeclaration(Declarator::FileContext);
357 default:
358 // We can't tell whether this is a function-definition or declaration yet.
359 return ParseDeclarationOrFunctionDefinition();
360 }
361}
362
363/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
364/// a declaration. We can't tell which we have until we read up to the
365/// compound-statement in function-definition.
366///
367/// function-definition: [C99 6.9.1]
Chris Lattnera15e9d22008-04-05 05:52:15 +0000368/// decl-specs declarator declaration-list[opt] compound-statement
369/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpeda58eb2008-06-19 19:28:49 +0000370/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattnera15e9d22008-04-05 05:52:15 +0000371///
Chris Lattner4b009652007-07-25 00:24:17 +0000372/// declaration: [C99 6.7]
Chris Lattneraac973e2007-08-22 06:06:56 +0000373/// declaration-specifiers init-declarator-list[opt] ';'
374/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Chris Lattner4b009652007-07-25 00:24:17 +0000375/// [OMP] threadprivate-directive [TODO]
376///
377Parser::DeclTy *Parser::ParseDeclarationOrFunctionDefinition() {
378 // Parse the common declaration-specifiers piece.
379 DeclSpec DS;
380 ParseDeclarationSpecifiers(DS);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000381
Chris Lattner4b009652007-07-25 00:24:17 +0000382 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
383 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner17a5fb62007-10-09 17:23:58 +0000384 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000385 ConsumeToken();
386 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
387 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000388
Steve Naroffa7f62782007-08-23 19:56:30 +0000389 // ObjC2 allows prefix attributes on class interfaces.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000390 if (getLang().ObjC2 && Tok.is(tok::at)) {
Steve Narofffb367882007-08-20 21:31:48 +0000391 SourceLocation AtLoc = ConsumeToken(); // the "@"
Chris Lattner847f5c12007-12-27 19:57:00 +0000392 if (!Tok.isObjCAtKeyword(tok::objc_interface)) {
393 Diag(Tok, diag::err_objc_expected_property_attr);//FIXME:better diagnostic
394 SkipUntil(tok::semi); // FIXME: better skip?
395 return 0;
396 }
Fariborz Jahanianf9c0a0d2008-01-02 19:17:38 +0000397 const char *PrevSpec = 0;
398 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec))
399 Diag(AtLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000400 return ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
Steve Narofffb367882007-08-20 21:31:48 +0000401 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000402
Chris Lattner806a5f52008-01-12 07:05:38 +0000403 // If the declspec consisted only of 'extern' and we have a string
404 // literal following it, this must be a C++ linkage specifier like
405 // 'extern "C"'.
Chris Lattner1b5c9f72008-01-12 07:08:43 +0000406 if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
Chris Lattner806a5f52008-01-12 07:05:38 +0000407 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
408 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier)
409 return ParseLinkage(Declarator::FileContext);
410
Chris Lattner4b009652007-07-25 00:24:17 +0000411 // Parse the first declarator.
412 Declarator DeclaratorInfo(DS, Declarator::FileContext);
413 ParseDeclarator(DeclaratorInfo);
414 // Error parsing the declarator?
415 if (DeclaratorInfo.getIdentifier() == 0) {
416 // If so, skip until the semi-colon or a }.
417 SkipUntil(tok::r_brace, true);
Chris Lattner17a5fb62007-10-09 17:23:58 +0000418 if (Tok.is(tok::semi))
Chris Lattner4b009652007-07-25 00:24:17 +0000419 ConsumeToken();
420 return 0;
421 }
422
423 // If the declarator is the start of a function definition, handle it.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000424 if (Tok.is(tok::equal) || // int X()= -> not a function def
425 Tok.is(tok::comma) || // int X(), -> not a function def
426 Tok.is(tok::semi) || // int X(); -> not a function def
427 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
428 Tok.is(tok::kw___attribute)) { // int X() __attr__ -> not a function def
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // FALL THROUGH.
430 } else if (DeclaratorInfo.isFunctionDeclarator() &&
Argiris Kirtzidisd1346a52008-06-21 10:00:56 +0000431 (Tok.is(tok::l_brace) || // int X() {}
432 ( !getLang().CPlusPlus &&
433 isDeclarationSpecifier() ))) { // int X(f) int f; {}
Steve Naroff83298852008-02-14 02:58:32 +0000434 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
435 Diag(Tok, diag::err_function_declared_typedef);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000436
Steve Naroff83298852008-02-14 02:58:32 +0000437 if (Tok.is(tok::l_brace)) {
438 // This recovery skips the entire function body. It would be nice
Mike Stumpeda58eb2008-06-19 19:28:49 +0000439 // to simply call ParseFunctionDefintion() below, however Sema
Steve Naroff83298852008-02-14 02:58:32 +0000440 // assumes the declarator represents a function, not a typedef.
441 ConsumeBrace();
442 SkipUntil(tok::r_brace, true);
443 } else {
444 SkipUntil(tok::semi);
445 }
446 return 0;
447 }
Chris Lattner4b009652007-07-25 00:24:17 +0000448 return ParseFunctionDefinition(DeclaratorInfo);
449 } else {
450 if (DeclaratorInfo.isFunctionDeclarator())
451 Diag(Tok, diag::err_expected_fn_body);
452 else
453 Diag(Tok, diag::err_expected_after_declarator);
454 SkipUntil(tok::semi);
455 return 0;
456 }
457
458 // Parse the init-declarator-list for a normal declaration.
459 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
460}
461
462/// ParseFunctionDefinition - We parsed and verified that the specified
463/// Declarator is well formed. If this is a K&R-style function, read the
464/// parameters declaration-list, then start the compound-statement.
465///
Chris Lattnera15e9d22008-04-05 05:52:15 +0000466/// function-definition: [C99 6.9.1]
467/// decl-specs declarator declaration-list[opt] compound-statement
468/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpeda58eb2008-06-19 19:28:49 +0000469/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattner4b009652007-07-25 00:24:17 +0000470///
471Parser::DeclTy *Parser::ParseFunctionDefinition(Declarator &D) {
472 const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
473 assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
474 "This isn't a function declarator!");
475 const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000476
Chris Lattnera15e9d22008-04-05 05:52:15 +0000477 // If this is C90 and the declspecs were completely missing, fudge in an
478 // implicit int. We do this here because this is the only place where
479 // declaration-specifiers are completely optional in the grammar.
Chris Lattner6ab935b2008-04-05 06:32:51 +0000480 if (getLang().ImplicitInt && D.getDeclSpec().getParsedSpecifiers() == 0) {
Chris Lattnera15e9d22008-04-05 05:52:15 +0000481 const char *PrevSpec;
Chris Lattner5e77ade2008-06-26 06:49:43 +0000482 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, D.getIdentifierLoc(),
Chris Lattnera15e9d22008-04-05 05:52:15 +0000483 PrevSpec);
484 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000485
Chris Lattner4b009652007-07-25 00:24:17 +0000486 // If this declaration was formed with a K&R-style identifier list for the
487 // arguments, parse declarations for all of the args next.
488 // int foo(a,b) int a; float b; {}
489 if (!FTI.hasPrototype && FTI.NumArgs != 0)
490 ParseKNRParamDeclarations(D);
491
Chris Lattner4b009652007-07-25 00:24:17 +0000492 // We should have an opening brace now.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000493 if (Tok.isNot(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000494 Diag(Tok, diag::err_expected_fn_body);
495
496 // Skip over garbage, until we get to '{'. Don't eat the '{'.
497 SkipUntil(tok::l_brace, true, true);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000498
Chris Lattner4b009652007-07-25 00:24:17 +0000499 // If we didn't find the '{', bail out.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000500 if (Tok.isNot(tok::l_brace))
Chris Lattner4b009652007-07-25 00:24:17 +0000501 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000502 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000503
Chris Lattnerea148702007-10-09 17:14:05 +0000504 SourceLocation BraceLoc = Tok.getLocation();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000505
Chris Lattnerea148702007-10-09 17:14:05 +0000506 // Enter a scope for the function body.
507 EnterScope(Scope::FnScope|Scope::DeclScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000508
Chris Lattnerea148702007-10-09 17:14:05 +0000509 // Tell the actions module that we have entered a function definition with the
510 // specified Declarator for the function.
511 DeclTy *Res = Actions.ActOnStartOfFunctionDef(CurScope, D);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000512
513 return ParseFunctionStatementBody(Res, BraceLoc, BraceLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000514}
515
516/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
517/// types for a function with a K&R-style identifier list for arguments.
518void Parser::ParseKNRParamDeclarations(Declarator &D) {
519 // We know that the top-level of this declarator is a function.
520 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
521
Chris Lattner3e254fb2008-04-08 04:40:51 +0000522 // Enter function-declaration scope, limiting any declarators to the
523 // function prototype scope, including parameter declarators.
Eli Friedman30165752008-05-20 09:10:20 +0000524 EnterScope(Scope::FnScope|Scope::DeclScope);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000525
Chris Lattner4b009652007-07-25 00:24:17 +0000526 // Read all the argument declarations.
527 while (isDeclarationSpecifier()) {
528 SourceLocation DSStart = Tok.getLocation();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000529
Chris Lattner4b009652007-07-25 00:24:17 +0000530 // Parse the common declaration-specifiers piece.
531 DeclSpec DS;
532 ParseDeclarationSpecifiers(DS);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000533
Chris Lattner4b009652007-07-25 00:24:17 +0000534 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
535 // least one declarator'.
536 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
537 // the declarations though. It's trivial to ignore them, really hard to do
538 // anything else with them.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000539 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000540 Diag(DSStart, diag::err_declaration_does_not_declare_param);
541 ConsumeToken();
542 continue;
543 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000544
Chris Lattner4b009652007-07-25 00:24:17 +0000545 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
546 // than register.
547 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
548 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
549 Diag(DS.getStorageClassSpecLoc(),
550 diag::err_invalid_storage_class_in_func_decl);
551 DS.ClearStorageClassSpecs();
552 }
553 if (DS.isThreadSpecified()) {
554 Diag(DS.getThreadSpecLoc(),
555 diag::err_invalid_storage_class_in_func_decl);
556 DS.ClearStorageClassSpecs();
557 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000558
Chris Lattner4b009652007-07-25 00:24:17 +0000559 // Parse the first declarator attached to this declspec.
560 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
561 ParseDeclarator(ParmDeclarator);
562
563 // Handle the full declarator list.
564 while (1) {
565 DeclTy *AttrList;
566 // If attributes are present, parse them.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000567 if (Tok.is(tok::kw___attribute))
Chris Lattner4b009652007-07-25 00:24:17 +0000568 // FIXME: attach attributes too.
569 AttrList = ParseAttributes();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000570
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // Ask the actions module to compute the type for this declarator.
Mike Stumpeda58eb2008-06-19 19:28:49 +0000572 Action::DeclTy *Param =
Chris Lattner3e254fb2008-04-08 04:40:51 +0000573 Actions.ActOnParamDeclarator(CurScope, ParmDeclarator);
Steve Narofffaed3bf2007-09-10 20:51:04 +0000574
Mike Stumpeda58eb2008-06-19 19:28:49 +0000575 if (Param &&
Chris Lattner4b009652007-07-25 00:24:17 +0000576 // A missing identifier has already been diagnosed.
577 ParmDeclarator.getIdentifier()) {
578
579 // Scan the argument list looking for the correct param to apply this
580 // type.
581 for (unsigned i = 0; ; ++i) {
582 // C99 6.9.1p6: those declarators shall declare only identifiers from
583 // the identifier list.
584 if (i == FTI.NumArgs) {
585 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param,
586 ParmDeclarator.getIdentifier()->getName());
587 break;
588 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000589
Chris Lattner4b009652007-07-25 00:24:17 +0000590 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
591 // Reject redefinitions of parameters.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000592 if (FTI.ArgInfo[i].Param) {
Chris Lattner4b009652007-07-25 00:24:17 +0000593 Diag(ParmDeclarator.getIdentifierLoc(),
594 diag::err_param_redefinition,
595 ParmDeclarator.getIdentifier()->getName());
596 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000597 FTI.ArgInfo[i].Param = Param;
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
599 break;
600 }
601 }
602 }
603
604 // If we don't have a comma, it is either the end of the list (a ';') or
605 // an error, bail out.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000606 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000607 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000608
Chris Lattner4b009652007-07-25 00:24:17 +0000609 // Consume the comma.
610 ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000611
Chris Lattner4b009652007-07-25 00:24:17 +0000612 // Parse the next declarator.
613 ParmDeclarator.clear();
614 ParseDeclarator(ParmDeclarator);
615 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000616
Chris Lattner17a5fb62007-10-09 17:23:58 +0000617 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000618 ConsumeToken();
619 } else {
620 Diag(Tok, diag::err_parse_error);
621 // Skip to end of block or statement
622 SkipUntil(tok::semi, true);
Chris Lattner17a5fb62007-10-09 17:23:58 +0000623 if (Tok.is(tok::semi))
Chris Lattner4b009652007-07-25 00:24:17 +0000624 ConsumeToken();
625 }
626 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000627
Chris Lattner3e254fb2008-04-08 04:40:51 +0000628 // Leave prototype scope.
629 ExitScope();
630
Chris Lattner4b009652007-07-25 00:24:17 +0000631 // The actions module must verify that all arguments were declared.
632}
633
634
635/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
636/// allowed to be a wide string, and is not subject to character translation.
637///
638/// [GNU] asm-string-literal:
639/// string-literal
640///
Anders Carlsson076c1112007-11-20 19:21:03 +0000641Parser::ExprResult Parser::ParseAsmStringLiteral() {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 if (!isTokenStringLiteral()) {
643 Diag(Tok, diag::err_expected_string_literal);
Anders Carlsson076c1112007-11-20 19:21:03 +0000644 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000645 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000646
Chris Lattner4b009652007-07-25 00:24:17 +0000647 ExprResult Res = ParseStringLiteralExpression();
Anders Carlsson076c1112007-11-20 19:21:03 +0000648 if (Res.isInvalid) return true;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000649
Chris Lattner4b009652007-07-25 00:24:17 +0000650 // TODO: Diagnose: wide string literal in 'asm'
Mike Stumpeda58eb2008-06-19 19:28:49 +0000651
Anders Carlsson076c1112007-11-20 19:21:03 +0000652 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000653}
654
655/// ParseSimpleAsm
656///
657/// [GNU] simple-asm-expr:
658/// 'asm' '(' asm-string-literal ')'
659///
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000660Parser::ExprResult Parser::ParseSimpleAsm() {
Chris Lattner17a5fb62007-10-09 17:23:58 +0000661 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000662 SourceLocation Loc = ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000663
Chris Lattner17a5fb62007-10-09 17:23:58 +0000664 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000665 Diag(Tok, diag::err_expected_lparen_after, "asm");
Chris Lattnerb36c3652008-05-27 23:32:43 +0000666 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000667 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000668
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000669 ConsumeParen();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000670
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000671 ExprResult Result = ParseAsmStringLiteral();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000672
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000673 if (Result.isInvalid) {
674 SkipUntil(tok::r_paren);
675 } else {
676 MatchRHSPunctuation(tok::r_paren, Loc);
677 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000678
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000679 return Result;
Chris Lattner4b009652007-07-25 00:24:17 +0000680}
681