blob: 581d585a82af4585649e0ab406cbf26662d98e2f [file] [log] [blame]
Chris Lattnereb8a28f2006-08-10 18:43:39 +00001//===--- Parser.cpp - C Language Family Parser ----------------------------===//
Chris Lattner0bb5f832006-07-31 01:59:18 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner288e86ff12006-11-11 23:03:42 +000015#include "clang/Parse/DeclSpec.h"
Chris Lattner971c6b62006-08-05 22:46:42 +000016#include "clang/Parse/Scope.h"
Chris Lattner0bb5f832006-07-31 01:59:18 +000017using namespace clang;
18
Chris Lattner697e5d62006-11-09 06:32:27 +000019Parser::Parser(Preprocessor &pp, Action &actions)
20 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()) {
Chris Lattner8c204872006-10-14 05:19:21 +000021 Tok.setKind(tok::eof);
Chris Lattnere4e38592006-08-14 00:15:05 +000022 CurScope = 0;
Chris Lattner03928c72007-07-15 00:04:39 +000023 NumCachedScopes = 0;
Chris Lattnereec40f92006-08-06 21:55:29 +000024 ParenCount = BracketCount = BraceCount = 0;
Chris Lattner971c6b62006-08-05 22:46:42 +000025}
26
Chris Lattner685ed1e2006-08-14 00:22:04 +000027/// Out-of-line virtual destructor to provide home for Action class.
28Action::~Action() {}
Chris Lattnere4e38592006-08-14 00:15:05 +000029
Chris Lattner0bb5f832006-07-31 01:59:18 +000030
Chris Lattnerb9093cd2006-08-04 04:39:53 +000031void Parser::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner0bb5f832006-07-31 01:59:18 +000032 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +000033 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner0bb5f832006-07-31 01:59:18 +000034}
35
Chris Lattner4564bc12006-08-10 23:14:52 +000036/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
37/// this helper function matches and consumes the specified RHS token if
38/// present. If not present, it emits the specified diagnostic indicating
39/// that the parser failed to match the RHS of the token at LHSLoc. LHSName
40/// should be the name of the unmatched LHS token.
Chris Lattner71e23ce2006-11-04 20:18:38 +000041SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
42 SourceLocation LHSLoc) {
Chris Lattner4564bc12006-08-10 23:14:52 +000043
Chris Lattner71e23ce2006-11-04 20:18:38 +000044 if (Tok.getKind() == RHSTok)
45 return ConsumeAnyToken();
46
47 SourceLocation R = Tok.getLocation();
48 const char *LHSName = "unknown";
49 diag::kind DID = diag::err_parse_error;
50 switch (RHSTok) {
51 default: break;
52 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
53 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
54 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
Chris Lattner29375652006-12-04 18:06:35 +000055 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
Chris Lattner4564bc12006-08-10 23:14:52 +000056 }
Chris Lattner71e23ce2006-11-04 20:18:38 +000057 Diag(Tok, DID);
58 Diag(LHSLoc, diag::err_matching, LHSName);
59 SkipUntil(RHSTok);
60 return R;
Chris Lattner4564bc12006-08-10 23:14:52 +000061}
62
Chris Lattnerdbb2a462006-08-12 19:26:13 +000063/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
64/// input. If so, it is consumed and false is returned.
65///
66/// If the input is malformed, this emits the specified diagnostic. Next, if
67/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
68/// returned.
69bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
Chris Lattner6d7e6342006-08-15 03:41:14 +000070 const char *Msg, tok::TokenKind SkipToTok) {
Chris Lattnerdbb2a462006-08-12 19:26:13 +000071 if (Tok.getKind() == ExpectedTok) {
Chris Lattner15a00da2006-08-15 04:10:31 +000072 ConsumeAnyToken();
Chris Lattnerdbb2a462006-08-12 19:26:13 +000073 return false;
74 }
75
Chris Lattner6d7e6342006-08-15 03:41:14 +000076 Diag(Tok, DiagID, Msg);
Chris Lattnerdbb2a462006-08-12 19:26:13 +000077 if (SkipToTok != tok::unknown)
78 SkipUntil(SkipToTok);
79 return true;
80}
81
Chris Lattner70f32b72006-07-31 05:09:04 +000082//===----------------------------------------------------------------------===//
Chris Lattnereec40f92006-08-06 21:55:29 +000083// Error recovery.
84//===----------------------------------------------------------------------===//
85
86/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner01e4b242007-07-24 17:03:04 +000087/// it (unless DontConsume is true). Because we cannot guarantee that the
Chris Lattnereec40f92006-08-06 21:55:29 +000088/// token will ever occur, this skips to the next token, or to some likely
89/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
90/// character.
91///
92/// If SkipUntil finds the specified token, it returns true, otherwise it
93/// returns false.
Chris Lattner83b94e02007-04-27 19:12:15 +000094bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
95 bool StopAtSemi, bool DontConsume) {
Chris Lattner5bd57e02006-08-11 06:40:25 +000096 // We always want this function to skip at least one token if the first token
97 // isn't T and if not at EOF.
98 bool isFirstTokenSkipped = true;
Chris Lattnereec40f92006-08-06 21:55:29 +000099 while (1) {
Chris Lattner83b94e02007-04-27 19:12:15 +0000100 // If we found one of the tokens, stop and return true.
101 for (unsigned i = 0; i != NumToks; ++i) {
102 if (Tok.getKind() == Toks[i]) {
103 if (DontConsume) {
104 // Noop, don't consume the token.
105 } else {
106 ConsumeAnyToken();
107 }
108 return true;
Chris Lattnereec40f92006-08-06 21:55:29 +0000109 }
Chris Lattnereec40f92006-08-06 21:55:29 +0000110 }
111
112 switch (Tok.getKind()) {
113 case tok::eof:
114 // Ran out of tokens.
115 return false;
116
117 case tok::l_paren:
118 // Recursively skip properly-nested parens.
119 ConsumeParen();
Chris Lattner5bd57e02006-08-11 06:40:25 +0000120 SkipUntil(tok::r_paren, false);
Chris Lattnereec40f92006-08-06 21:55:29 +0000121 break;
122 case tok::l_square:
123 // Recursively skip properly-nested square brackets.
124 ConsumeBracket();
Chris Lattner5bd57e02006-08-11 06:40:25 +0000125 SkipUntil(tok::r_square, false);
Chris Lattnereec40f92006-08-06 21:55:29 +0000126 break;
127 case tok::l_brace:
128 // Recursively skip properly-nested braces.
129 ConsumeBrace();
Chris Lattner5bd57e02006-08-11 06:40:25 +0000130 SkipUntil(tok::r_brace, false);
Chris Lattnereec40f92006-08-06 21:55:29 +0000131 break;
132
133 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
134 // Since the user wasn't looking for this token (if they were, it would
135 // already be handled), this isn't balanced. If there is a LHS token at a
136 // higher level, we will assume that this matches the unbalanced token
137 // and return it. Otherwise, this is a spurious RHS token, which we skip.
138 case tok::r_paren:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000139 if (ParenCount && !isFirstTokenSkipped)
140 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000141 ConsumeParen();
142 break;
143 case tok::r_square:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000144 if (BracketCount && !isFirstTokenSkipped)
145 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000146 ConsumeBracket();
147 break;
148 case tok::r_brace:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000149 if (BraceCount && !isFirstTokenSkipped)
150 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000151 ConsumeBrace();
152 break;
153
154 case tok::string_literal:
Chris Lattnerd3e98952006-10-06 05:22:26 +0000155 case tok::wide_string_literal:
Chris Lattnereec40f92006-08-06 21:55:29 +0000156 ConsumeStringToken();
157 break;
158 case tok::semi:
159 if (StopAtSemi)
160 return false;
161 // FALL THROUGH.
162 default:
163 // Skip this token.
164 ConsumeToken();
165 break;
166 }
Chris Lattner5bd57e02006-08-11 06:40:25 +0000167 isFirstTokenSkipped = false;
Chris Lattnereec40f92006-08-06 21:55:29 +0000168 }
169}
170
171//===----------------------------------------------------------------------===//
Chris Lattnere4e38592006-08-14 00:15:05 +0000172// Scope manipulation
173//===----------------------------------------------------------------------===//
174
175/// EnterScope - Start a new scope.
Chris Lattner33ad2ca2006-11-05 23:47:55 +0000176void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner03928c72007-07-15 00:04:39 +0000177 if (NumCachedScopes) {
178 Scope *N = ScopeCache[--NumCachedScopes];
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000179 N->Init(CurScope, ScopeFlags);
180 CurScope = N;
181 } else {
182 CurScope = new Scope(CurScope, ScopeFlags);
183 }
Chris Lattnere4e38592006-08-14 00:15:05 +0000184}
185
186/// ExitScope - Pop a scope off the scope stack.
187void Parser::ExitScope() {
188 assert(CurScope && "Scope imbalance!");
189
190 // Inform the actions module that this scope is going away.
191 Actions.PopScope(Tok.getLocation(), CurScope);
192
Chris Lattner03928c72007-07-15 00:04:39 +0000193 Scope *OldScope = CurScope;
194 CurScope = OldScope->getParent();
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000195
Chris Lattner03928c72007-07-15 00:04:39 +0000196 if (NumCachedScopes == ScopeCacheSize)
197 delete OldScope;
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000198 else
Chris Lattner03928c72007-07-15 00:04:39 +0000199 ScopeCache[NumCachedScopes++] = OldScope;
Chris Lattnere4e38592006-08-14 00:15:05 +0000200}
201
202
203
204
205//===----------------------------------------------------------------------===//
Chris Lattner70f32b72006-07-31 05:09:04 +0000206// C99 6.9: External Definitions.
207//===----------------------------------------------------------------------===//
Chris Lattner0bb5f832006-07-31 01:59:18 +0000208
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000209Parser::~Parser() {
210 // If we still have scopes active, delete the scope tree.
211 delete CurScope;
212
213 // Free the scope cache.
Chris Lattner03928c72007-07-15 00:04:39 +0000214 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
215 delete ScopeCache[i];
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000216}
217
Chris Lattner38ba3362006-08-17 07:04:37 +0000218/// Initialize - Warm up the parser.
219///
220void Parser::Initialize() {
Chris Lattnere4e38592006-08-14 00:15:05 +0000221 // Prime the lexer look-ahead.
222 ConsumeToken();
223
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000224 // Create the translation unit scope. Install it as the current scope.
Chris Lattnere4e38592006-08-14 00:15:05 +0000225 assert(CurScope == 0 && "A scope is already active?");
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000226 EnterScope(Scope::DeclScope);
227
Chris Lattner6d7e6342006-08-15 03:41:14 +0000228 // Install builtin types.
229 // TODO: Move this someplace more useful.
230 {
Chris Lattner353f5742006-11-28 04:50:12 +0000231 const char *Dummy;
232
Chris Lattner6d7e6342006-08-15 03:41:14 +0000233 //__builtin_va_list
234 DeclSpec DS;
Chris Lattner4d8f8732006-11-28 05:05:08 +0000235 bool Error = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, SourceLocation(),
236 Dummy);
Chris Lattner6d7e6342006-08-15 03:41:14 +0000237
238 // TODO: add a 'TST_builtin' type?
Chris Lattnerb20e8942006-11-28 05:30:29 +0000239 Error |= DS.SetTypeSpecType(DeclSpec::TST_int, SourceLocation(), Dummy);
Chris Lattner353f5742006-11-28 04:50:12 +0000240 assert(!Error && "Error setting up __builtin_va_list!");
Chris Lattner38ba3362006-08-17 07:04:37 +0000241
Chris Lattner6d7e6342006-08-15 03:41:14 +0000242 Declarator D(DS, Declarator::FileContext);
243 D.SetIdentifier(PP.getIdentifierInfo("__builtin_va_list"),SourceLocation());
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000244 Actions.ParseDeclarator(CurScope, D, 0, 0);
Chris Lattner6d7e6342006-08-15 03:41:14 +0000245 }
246
Chris Lattner66b67ef2007-08-25 05:47:03 +0000247 if (Tok.getKind() == tok::eof &&
248 !getLang().CPlusPlus) // Empty source file is an extension in C
Chris Lattnerbd638922006-11-10 05:19:25 +0000249 Diag(Tok, diag::ext_empty_source_file);
Chris Lattner66782842007-08-29 22:54:08 +0000250
251 // Initialization for Objective-C context sensitive keywords recognition.
252 // Referenced in Parser::isObjCTypeQualifier.
253 if (getLang().ObjC1) {
254 ObjcTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
255 ObjcTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
256 ObjcTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
257 ObjcTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
258 ObjcTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
259 ObjcTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
260 }
Chris Lattner38ba3362006-08-17 07:04:37 +0000261}
262
263/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
264/// action tells us to. This returns true if the EOF was encountered.
265bool Parser::ParseTopLevelDecl(DeclTy*& Result) {
266 Result = 0;
267 if (Tok.getKind() == tok::eof) return true;
Chris Lattner0bb5f832006-07-31 01:59:18 +0000268
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000269 Result = ParseExternalDeclaration();
Chris Lattner38ba3362006-08-17 07:04:37 +0000270 return false;
271}
272
273/// Finalize - Shut down the parser.
274///
275void Parser::Finalize() {
Chris Lattnere4e38592006-08-14 00:15:05 +0000276 ExitScope();
277 assert(CurScope == 0 && "Scope imbalance!");
Chris Lattner0bb5f832006-07-31 01:59:18 +0000278}
279
Chris Lattner38ba3362006-08-17 07:04:37 +0000280/// ParseTranslationUnit:
281/// translation-unit: [C99 6.9]
282/// external-declaration
283/// translation-unit external-declaration
284void Parser::ParseTranslationUnit() {
285 Initialize();
286
287 DeclTy *Res;
288 while (!ParseTopLevelDecl(Res))
289 /*parse them all*/;
290
291 Finalize();
292}
293
Chris Lattner0bb5f832006-07-31 01:59:18 +0000294/// ParseExternalDeclaration:
Chris Lattner70f32b72006-07-31 05:09:04 +0000295/// external-declaration: [C99 6.9]
Chris Lattnercccc3112007-08-10 20:57:02 +0000296/// function-definition
297/// declaration
Chris Lattner0bb5f832006-07-31 01:59:18 +0000298/// [EXT] ';'
Chris Lattner6d7e6342006-08-15 03:41:14 +0000299/// [GNU] asm-definition
Chris Lattnercccc3112007-08-10 20:57:02 +0000300/// [GNU] __extension__ external-declaration
Chris Lattner40f16b52006-11-05 02:05:37 +0000301/// [OBJC] objc-class-definition
302/// [OBJC] objc-class-declaration
303/// [OBJC] objc-alias-declaration
304/// [OBJC] objc-protocol-definition
305/// [OBJC] objc-method-definition
306/// [OBJC] @end
Chris Lattner0bb5f832006-07-31 01:59:18 +0000307///
Chris Lattner6d7e6342006-08-15 03:41:14 +0000308/// [GNU] asm-definition:
309/// simple-asm-expr ';'
310///
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000311Parser::DeclTy *Parser::ParseExternalDeclaration() {
Chris Lattner0bb5f832006-07-31 01:59:18 +0000312 switch (Tok.getKind()) {
313 case tok::semi:
Chris Lattnerbd638922006-11-10 05:19:25 +0000314 Diag(Tok, diag::ext_top_level_semi);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000315 ConsumeToken();
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000316 // TODO: Invoke action for top-level semicolon.
317 return 0;
Chris Lattnercccc3112007-08-10 20:57:02 +0000318 case tok::kw___extension__: {
319 ConsumeToken();
320 // FIXME: Disable extension warnings.
321 DeclTy *RV = ParseExternalDeclaration();
322 // FIXME: Restore extension warnings.
323 return RV;
324 }
Chris Lattner6d7e6342006-08-15 03:41:14 +0000325 case tok::kw_asm:
326 ParseSimpleAsm();
327 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
328 "top-level asm block");
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000329 // TODO: Invoke action for top-level asm.
330 return 0;
Steve Naroffb419d3a2006-10-27 23:18:49 +0000331 case tok::at:
Chris Lattnerc24278d2007-05-02 23:45:06 +0000332 // @ is not a legal token unless objc is enabled, no need to check.
Chris Lattnerb26b6652006-11-08 06:10:32 +0000333 ParseObjCAtDirectives();
Steve Naroffb419d3a2006-10-27 23:18:49 +0000334 return 0;
335 case tok::minus:
Chris Lattnerc24278d2007-05-02 23:45:06 +0000336 if (getLang().ObjC1) {
Steve Naroff0b6a01a2007-08-22 22:17:26 +0000337 ParseObjCInstanceMethodDefinition();
Chris Lattnerc24278d2007-05-02 23:45:06 +0000338 } else {
339 Diag(Tok, diag::err_expected_external_declaration);
340 ConsumeToken();
341 }
Chris Lattneraacc5af2006-11-03 07:21:07 +0000342 return 0;
Steve Naroffb419d3a2006-10-27 23:18:49 +0000343 case tok::plus:
Chris Lattnerc24278d2007-05-02 23:45:06 +0000344 if (getLang().ObjC1) {
Steve Naroff0b6a01a2007-08-22 22:17:26 +0000345 ParseObjCClassMethodDefinition();
Chris Lattnerc24278d2007-05-02 23:45:06 +0000346 } else {
347 Diag(Tok, diag::err_expected_external_declaration);
348 ConsumeToken();
349 }
Steve Naroffb419d3a2006-10-27 23:18:49 +0000350 return 0;
Chris Lattnera5235172007-08-25 06:57:03 +0000351 case tok::kw_namespace:
Chris Lattner302b4be2006-11-19 02:31:38 +0000352 case tok::kw_typedef:
Chris Lattner479ed3a2007-08-25 18:15:16 +0000353 // A function definition cannot start with a these keywords.
Chris Lattner302b4be2006-11-19 02:31:38 +0000354 return ParseDeclaration(Declarator::FileContext);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000355 default:
356 // We can't tell whether this is a function-definition or declaration yet.
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000357 return ParseDeclarationOrFunctionDefinition();
Chris Lattner0bb5f832006-07-31 01:59:18 +0000358 }
359}
360
361/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
Chris Lattner70f32b72006-07-31 05:09:04 +0000362/// a declaration. We can't tell which we have until we read up to the
363/// compound-statement in function-definition.
Chris Lattner0bb5f832006-07-31 01:59:18 +0000364///
Chris Lattner70f32b72006-07-31 05:09:04 +0000365/// function-definition: [C99 6.9.1]
366/// declaration-specifiers[opt] declarator declaration-list[opt]
Chris Lattnerf2659392007-08-22 06:06:56 +0000367/// compound-statement
Chris Lattner70f32b72006-07-31 05:09:04 +0000368/// declaration: [C99 6.7]
Chris Lattnerf2659392007-08-22 06:06:56 +0000369/// declaration-specifiers init-declarator-list[opt] ';'
370/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Chris Lattner70f32b72006-07-31 05:09:04 +0000371/// [OMP] threadprivate-directive [TODO]
372///
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000373Parser::DeclTy *Parser::ParseDeclarationOrFunctionDefinition() {
Chris Lattner70f32b72006-07-31 05:09:04 +0000374 // Parse the common declaration-specifiers piece.
Chris Lattnerb9093cd2006-08-04 04:39:53 +0000375 DeclSpec DS;
376 ParseDeclarationSpecifiers(DS);
Chris Lattnerd2864882006-08-05 08:09:44 +0000377
378 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
Chris Lattner53361ac2006-08-10 05:19:57 +0000379 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner0e894622006-08-13 19:58:17 +0000380 if (Tok.getKind() == tok::semi) {
Chris Lattner0e894622006-08-13 19:58:17 +0000381 ConsumeToken();
Chris Lattner200bdc32006-11-19 02:43:37 +0000382 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
Chris Lattner0e894622006-08-13 19:58:17 +0000383 }
Chris Lattner70f32b72006-07-31 05:09:04 +0000384
Steve Naroff4e1f80d2007-08-23 19:56:30 +0000385 // ObjC2 allows prefix attributes on class interfaces.
386 if (getLang().ObjC2 && Tok.getKind() == tok::at) {
Steve Naroff1eb1ad62007-08-20 21:31:48 +0000387 SourceLocation AtLoc = ConsumeToken(); // the "@"
388 if (Tok.getIdentifierInfo()->getObjCKeywordID() == tok::objc_interface)
389 return ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
390 }
391
Chris Lattnerfff824f2006-08-07 06:31:38 +0000392 // Parse the first declarator.
393 Declarator DeclaratorInfo(DS, Declarator::FileContext);
394 ParseDeclarator(DeclaratorInfo);
395 // Error parsing the declarator?
396 if (DeclaratorInfo.getIdentifier() == 0) {
397 // If so, skip until the semi-colon or a }.
398 SkipUntil(tok::r_brace, true);
399 if (Tok.getKind() == tok::semi)
400 ConsumeToken();
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000401 return 0;
Chris Lattnerfff824f2006-08-07 06:31:38 +0000402 }
Chris Lattner70f32b72006-07-31 05:09:04 +0000403
Chris Lattnerfff824f2006-08-07 06:31:38 +0000404 // If the declarator is the start of a function definition, handle it.
405 if (Tok.getKind() == tok::equal || // int X()= -> not a function def
406 Tok.getKind() == tok::comma || // int X(), -> not a function def
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000407 Tok.getKind() == tok::semi || // int X(); -> not a function def
Chris Lattnerfff824f2006-08-07 06:31:38 +0000408 Tok.getKind() == tok::kw_asm || // int X() __asm__ -> not a fn def
409 Tok.getKind() == tok::kw___attribute) {// int X() __attr__ -> not a fn def
410 // FALL THROUGH.
Chris Lattnera11999d2006-10-15 22:34:45 +0000411 } else if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattnerfff824f2006-08-07 06:31:38 +0000412 (Tok.getKind() == tok::l_brace || // int X() {}
413 isDeclarationSpecifier())) { // int X(f) int f; {}
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000414 return ParseFunctionDefinition(DeclaratorInfo);
Chris Lattnerfff824f2006-08-07 06:31:38 +0000415 } else {
Chris Lattnera11999d2006-10-15 22:34:45 +0000416 if (DeclaratorInfo.isFunctionDeclarator())
Chris Lattnerfff824f2006-08-07 06:31:38 +0000417 Diag(Tok, diag::err_expected_fn_body);
418 else
419 Diag(Tok, diag::err_expected_after_declarator);
Chris Lattnere4e38592006-08-14 00:15:05 +0000420 SkipUntil(tok::semi);
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000421 return 0;
Chris Lattnerfff824f2006-08-07 06:31:38 +0000422 }
Chris Lattnerd9c3c592006-08-05 06:26:47 +0000423
Chris Lattner53361ac2006-08-10 05:19:57 +0000424 // Parse the init-declarator-list for a normal declaration.
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000425 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
Chris Lattner70f32b72006-07-31 05:09:04 +0000426}
427
Chris Lattnerfff824f2006-08-07 06:31:38 +0000428/// ParseFunctionDefinition - We parsed and verified that the specified
429/// Declarator is well formed. If this is a K&R-style function, read the
430/// parameters declaration-list, then start the compound-statement.
431///
432/// declaration-specifiers[opt] declarator declaration-list[opt]
433/// compound-statement [TODO]
434///
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000435Parser::DeclTy *Parser::ParseFunctionDefinition(Declarator &D) {
Chris Lattnercbc426d2006-12-02 06:43:02 +0000436 const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
437 assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
Chris Lattnerfff824f2006-08-07 06:31:38 +0000438 "This isn't a function declarator!");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000439 const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
Chris Lattnerfff824f2006-08-07 06:31:38 +0000440
441 // If this declaration was formed with a K&R-style identifier list for the
442 // arguments, parse declarations for all of the args next.
443 // int foo(a,b) int a; float b; {}
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000444 if (!FTI.hasPrototype && FTI.NumArgs != 0)
445 ParseKNRParamDeclarations(D);
Chris Lattnerfff824f2006-08-07 06:31:38 +0000446
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000447 // Enter a scope for the function body.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000448 EnterScope(Scope::FnScope|Scope::DeclScope);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000449
Chris Lattner2114d5e2006-12-04 07:40:24 +0000450 // Tell the actions module that we have entered a function definition with the
451 // specified Declarator for the function.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000452 DeclTy *Res = Actions.ParseStartOfFunctionDef(CurScope, D);
453
454
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000455 // We should have an opening brace now.
456 if (Tok.getKind() != tok::l_brace) {
457 Diag(Tok, diag::err_expected_fn_body);
458
459 // Skip over garbage, until we get to '{'. Don't eat the '{'.
460 SkipUntil(tok::l_brace, true, true);
461
462 // If we didn't find the '{', bail out.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000463 if (Tok.getKind() != tok::l_brace) {
464 ExitScope();
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000465 return 0;
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000466 }
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000467 }
Chris Lattnerfff824f2006-08-07 06:31:38 +0000468
Chris Lattner7f58c3d2007-01-21 06:56:16 +0000469 // Do not enter a scope for the brace, as the arguments are in the same scope
470 // (the function body) as the body itself. Instead, just read the statement
471 // list and put it into a CompoundStmt for safe keeping.
472 StmtResult FnBody = ParseCompoundStatementBody();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000473 if (FnBody.isInvalid) {
474 ExitScope();
475 return 0;
476 }
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000477
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000478 // Leave the function body scope.
479 ExitScope();
Chris Lattner7014fb82006-11-05 07:36:23 +0000480
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000481 // TODO: Pass argument information.
Chris Lattner229ce602006-11-21 01:21:07 +0000482 return Actions.ParseFunctionDefBody(Res, FnBody.Val);
Chris Lattnerfff824f2006-08-07 06:31:38 +0000483}
484
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000485/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
486/// types for a function with a K&R-style identifier list for arguments.
487void Parser::ParseKNRParamDeclarations(Declarator &D) {
488 // We know that the top-level of this declarator is a function.
489 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
490
491 // Read all the argument declarations.
492 while (isDeclarationSpecifier()) {
493 SourceLocation DSStart = Tok.getLocation();
494
495 // Parse the common declaration-specifiers piece.
496 DeclSpec DS;
497 ParseDeclarationSpecifiers(DS);
498
499 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
500 // least one declarator'.
501 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
502 // the declarations though. It's trivial to ignore them, really hard to do
503 // anything else with them.
504 if (Tok.getKind() == tok::semi) {
505 Diag(DSStart, diag::err_declaration_does_not_declare_param);
506 ConsumeToken();
507 continue;
508 }
509
510 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
511 // than register.
512 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
513 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
514 Diag(DS.getStorageClassSpecLoc(),
515 diag::err_invalid_storage_class_in_func_decl);
516 DS.ClearStorageClassSpecs();
517 }
518 if (DS.isThreadSpecified()) {
519 Diag(DS.getThreadSpecLoc(),
520 diag::err_invalid_storage_class_in_func_decl);
521 DS.ClearStorageClassSpecs();
522 }
523
524 // Parse the first declarator attached to this declspec.
525 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
526 ParseDeclarator(ParmDeclarator);
527
528 // Handle the full declarator list.
529 while (1) {
Steve Naroff0f2fe172007-06-01 17:11:19 +0000530 DeclTy *AttrList;
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000531 // If attributes are present, parse them.
532 if (Tok.getKind() == tok::kw___attribute)
533 // FIXME: attach attributes too.
Steve Naroff0f2fe172007-06-01 17:11:19 +0000534 AttrList = ParseAttributes();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000535
536 // Ask the actions module to compute the type for this declarator.
537 Action::TypeResult TR =
538 Actions.ParseParamDeclaratorType(CurScope, ParmDeclarator);
539 if (!TR.isInvalid &&
540 // A missing identifier has already been diagnosed.
541 ParmDeclarator.getIdentifier()) {
542
543 // Scan the argument list looking for the correct param to apply this
544 // type.
545 for (unsigned i = 0; ; ++i) {
546 // C99 6.9.1p6: those declarators shall declare only identifiers from
547 // the identifier list.
548 if (i == FTI.NumArgs) {
549 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param,
550 ParmDeclarator.getIdentifier()->getName());
551 break;
552 }
553
554 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
555 // Reject redefinitions of parameters.
556 if (FTI.ArgInfo[i].TypeInfo) {
557 Diag(ParmDeclarator.getIdentifierLoc(),
558 diag::err_param_redefinition,
559 ParmDeclarator.getIdentifier()->getName());
560 } else {
561 FTI.ArgInfo[i].TypeInfo = TR.Val;
562 }
563 break;
564 }
565 }
566 }
567
568 // If we don't have a comma, it is either the end of the list (a ';') or
569 // an error, bail out.
570 if (Tok.getKind() != tok::comma)
571 break;
572
573 // Consume the comma.
574 ConsumeToken();
575
576 // Parse the next declarator.
577 ParmDeclarator.clear();
578 ParseDeclarator(ParmDeclarator);
579 }
580
581 if (Tok.getKind() == tok::semi) {
582 ConsumeToken();
583 } else {
584 Diag(Tok, diag::err_parse_error);
585 // Skip to end of block or statement
586 SkipUntil(tok::semi, true);
587 if (Tok.getKind() == tok::semi)
588 ConsumeToken();
589 }
590 }
591
592 // The actions module must verify that all arguments were declared.
593}
594
595
Chris Lattner0116c472006-08-15 06:03:28 +0000596/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
597/// allowed to be a wide string, and is not subject to character translation.
598///
599/// [GNU] asm-string-literal:
600/// string-literal
601///
602void Parser::ParseAsmStringLiteral() {
Chris Lattnerd3e98952006-10-06 05:22:26 +0000603 if (!isTokenStringLiteral()) {
Chris Lattner0116c472006-08-15 06:03:28 +0000604 Diag(Tok, diag::err_expected_string_literal);
605 return;
606 }
607
608 ExprResult Res = ParseStringLiteralExpression();
609 if (Res.isInvalid) return;
610
611 // TODO: Diagnose: wide string literal in 'asm'
612}
613
Chris Lattner6d7e6342006-08-15 03:41:14 +0000614/// ParseSimpleAsm
615///
616/// [GNU] simple-asm-expr:
617/// 'asm' '(' asm-string-literal ')'
Chris Lattner6d7e6342006-08-15 03:41:14 +0000618///
619void Parser::ParseSimpleAsm() {
620 assert(Tok.getKind() == tok::kw_asm && "Not an asm!");
621 ConsumeToken();
622
623 if (Tok.getKind() != tok::l_paren) {
624 Diag(Tok, diag::err_expected_lparen_after, "asm");
625 return;
626 }
627
Chris Lattner04132372006-10-16 06:12:55 +0000628 SourceLocation Loc = ConsumeParen();
Chris Lattner6d7e6342006-08-15 03:41:14 +0000629
Chris Lattner0116c472006-08-15 06:03:28 +0000630 ParseAsmStringLiteral();
Chris Lattner6d7e6342006-08-15 03:41:14 +0000631
Chris Lattner04f80192006-08-15 04:55:54 +0000632 MatchRHSPunctuation(tok::r_paren, Loc);
Chris Lattner6d7e6342006-08-15 03:41:14 +0000633}
Steve Naroffb419d3a2006-10-27 23:18:49 +0000634