blob: 70a336678cdac40ab0c54a73667d67859d2d9a51 [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"
Chris Lattner545f39e2009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
Chris Lattner6b3833c2009-03-05 07:24:28 +000018#include "llvm/Support/raw_ostream.h"
Chris Lattnerdaa5c002008-10-20 06:45:43 +000019#include "ExtensionRAIIObject.h"
Daniel Dunbar47f99c92008-10-04 19:21:03 +000020#include "ParsePragma.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22
23Parser::Parser(Preprocessor &pp, Action &actions)
Chris Lattner6b3833c2009-03-05 07:24:28 +000024 : CrashInfo(*this), PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
Douglas Gregor8e458f42009-02-09 18:46:07 +000025 GreaterThanIsOperator(true) {
Chris Lattner4b009652007-07-25 00:24:17 +000026 Tok.setKind(tok::eof);
27 CurScope = 0;
28 NumCachedScopes = 0;
29 ParenCount = BracketCount = BraceCount = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000030 ObjCImpDecl = 0;
Daniel Dunbar47f99c92008-10-04 19:21:03 +000031
32 // Add #pragma handlers. These are removed and destroyed in the
33 // destructor.
34 PackHandler =
35 new PragmaPackHandler(&PP.getIdentifierTable().get("pack"), actions);
36 PP.AddPragmaHandler(0, PackHandler);
37
Argiris Kirtzidis9d784332008-06-24 22:12:16 +000038 // Instantiate a LexedMethodsForTopClass for all the non-nested classes.
39 PushTopClassStack();
Chris Lattner4b009652007-07-25 00:24:17 +000040}
41
Chris Lattner6b3833c2009-03-05 07:24:28 +000042/// If a crash happens while the parser is active, print out a line indicating
43/// what the current token is.
44void PrettyStackTraceParserEntry::print(llvm::raw_ostream &OS) const {
45 const Token &Tok = P.getCurToken();
46 if (Tok.getLocation().isInvalid()) {
47 OS << "<eof> parser at end of file\n";
48 return;
49 }
50
51 const Preprocessor &PP = P.getPreprocessor();
52 Tok.getLocation().print(OS, PP.getSourceManager());
53 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
Douglas Gregor5ff0ee52008-12-30 03:27:21 +000054}
Chris Lattner4b009652007-07-25 00:24:17 +000055
Chris Lattner6b3833c2009-03-05 07:24:28 +000056
Chris Lattner9943e982008-11-22 00:59:29 +000057DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Chris Lattner6b3833c2009-03-05 07:24:28 +000058 return Diags.Report(FullSourceLoc(Loc, PP.getSourceManager()), DiagID);
Chris Lattnerf006a222008-11-18 07:48:38 +000059}
60
Chris Lattner9943e982008-11-22 00:59:29 +000061DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattnerf006a222008-11-18 07:48:38 +000062 return Diag(Tok.getLocation(), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +000063}
64
Douglas Gregor3bb30002009-02-26 21:00:50 +000065/// \brief Emits a diagnostic suggesting parentheses surrounding a
66/// given range.
67///
68/// \param Loc The location where we'll emit the diagnostic.
69/// \param Loc The kind of diagnostic to emit.
70/// \param ParenRange Source range enclosing code that should be parenthesized.
71void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
72 SourceRange ParenRange) {
Douglas Gregor61be3602009-02-27 17:53:17 +000073 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
74 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Douglas Gregor3bb30002009-02-26 21:00:50 +000075 // We can't display the parentheses, so just dig the
76 // warning/error and return.
77 Diag(Loc, DK);
78 return;
79 }
80
Douglas Gregor3bb30002009-02-26 21:00:50 +000081 Diag(Loc, DK)
Douglas Gregor61be3602009-02-27 17:53:17 +000082 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
83 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregor3bb30002009-02-26 21:00:50 +000084}
85
Chris Lattner4b009652007-07-25 00:24:17 +000086/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
87/// this helper function matches and consumes the specified RHS token if
88/// present. If not present, it emits the specified diagnostic indicating
89/// that the parser failed to match the RHS of the token at LHSLoc. LHSName
90/// should be the name of the unmatched LHS token.
91SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
92 SourceLocation LHSLoc) {
Mike Stumpeda58eb2008-06-19 19:28:49 +000093
Chris Lattner17a5fb62007-10-09 17:23:58 +000094 if (Tok.is(RHSTok))
Chris Lattner4b009652007-07-25 00:24:17 +000095 return ConsumeAnyToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +000096
Chris Lattner4b009652007-07-25 00:24:17 +000097 SourceLocation R = Tok.getLocation();
98 const char *LHSName = "unknown";
99 diag::kind DID = diag::err_parse_error;
100 switch (RHSTok) {
101 default: break;
102 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
103 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
104 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
105 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
106 }
107 Diag(Tok, DID);
Chris Lattner921342c2008-11-23 23:17:07 +0000108 Diag(LHSLoc, diag::note_matching) << LHSName;
Chris Lattner4b009652007-07-25 00:24:17 +0000109 SkipUntil(RHSTok);
110 return R;
111}
112
113/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
114/// input. If so, it is consumed and false is returned.
115///
116/// If the input is malformed, this emits the specified diagnostic. Next, if
117/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
118/// returned.
119bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
120 const char *Msg, tok::TokenKind SkipToTok) {
Chris Lattner17a5fb62007-10-09 17:23:58 +0000121 if (Tok.is(ExpectedTok)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000122 ConsumeAnyToken();
123 return false;
124 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000125
Douglas Gregor3bb30002009-02-26 21:00:50 +0000126 const char *Spelling = 0;
Douglas Gregor61be3602009-02-27 17:53:17 +0000127 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
128 if (EndLoc.isValid() &&
129 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Douglas Gregor3bb30002009-02-26 21:00:50 +0000130 // Show what code to insert to fix this problem.
Douglas Gregor61be3602009-02-27 17:53:17 +0000131 Diag(EndLoc, DiagID)
Douglas Gregor3bb30002009-02-26 21:00:50 +0000132 << Msg
Douglas Gregor61be3602009-02-27 17:53:17 +0000133 << CodeModificationHint::CreateInsertion(EndLoc, Spelling);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000134 } else
135 Diag(Tok, DiagID) << Msg;
136
Chris Lattner4b009652007-07-25 00:24:17 +0000137 if (SkipToTok != tok::unknown)
138 SkipUntil(SkipToTok);
139 return true;
140}
141
142//===----------------------------------------------------------------------===//
143// Error recovery.
144//===----------------------------------------------------------------------===//
145
146/// SkipUntil - Read tokens until we get to the specified token, then consume
147/// it (unless DontConsume is true). Because we cannot guarantee that the
148/// token will ever occur, this skips to the next token, or to some likely
149/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
150/// character.
Mike Stumpeda58eb2008-06-19 19:28:49 +0000151///
Chris Lattner4b009652007-07-25 00:24:17 +0000152/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stumpeda58eb2008-06-19 19:28:49 +0000153/// returns false.
Chris Lattner4b009652007-07-25 00:24:17 +0000154bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
155 bool StopAtSemi, bool DontConsume) {
156 // We always want this function to skip at least one token if the first token
157 // isn't T and if not at EOF.
158 bool isFirstTokenSkipped = true;
159 while (1) {
160 // If we found one of the tokens, stop and return true.
161 for (unsigned i = 0; i != NumToks; ++i) {
Chris Lattner17a5fb62007-10-09 17:23:58 +0000162 if (Tok.is(Toks[i])) {
Chris Lattner4b009652007-07-25 00:24:17 +0000163 if (DontConsume) {
164 // Noop, don't consume the token.
165 } else {
166 ConsumeAnyToken();
167 }
168 return true;
169 }
170 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000171
Chris Lattner4b009652007-07-25 00:24:17 +0000172 switch (Tok.getKind()) {
173 case tok::eof:
174 // Ran out of tokens.
175 return false;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000176
Chris Lattner4b009652007-07-25 00:24:17 +0000177 case tok::l_paren:
178 // Recursively skip properly-nested parens.
179 ConsumeParen();
180 SkipUntil(tok::r_paren, false);
181 break;
182 case tok::l_square:
183 // Recursively skip properly-nested square brackets.
184 ConsumeBracket();
185 SkipUntil(tok::r_square, false);
186 break;
187 case tok::l_brace:
188 // Recursively skip properly-nested braces.
189 ConsumeBrace();
190 SkipUntil(tok::r_brace, false);
191 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000192
Chris Lattner4b009652007-07-25 00:24:17 +0000193 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
194 // Since the user wasn't looking for this token (if they were, it would
195 // already be handled), this isn't balanced. If there is a LHS token at a
196 // higher level, we will assume that this matches the unbalanced token
197 // and return it. Otherwise, this is a spurious RHS token, which we skip.
198 case tok::r_paren:
199 if (ParenCount && !isFirstTokenSkipped)
200 return false; // Matches something.
201 ConsumeParen();
202 break;
203 case tok::r_square:
204 if (BracketCount && !isFirstTokenSkipped)
205 return false; // Matches something.
206 ConsumeBracket();
207 break;
208 case tok::r_brace:
209 if (BraceCount && !isFirstTokenSkipped)
210 return false; // Matches something.
211 ConsumeBrace();
212 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000213
Chris Lattner4b009652007-07-25 00:24:17 +0000214 case tok::string_literal:
215 case tok::wide_string_literal:
216 ConsumeStringToken();
217 break;
218 case tok::semi:
219 if (StopAtSemi)
220 return false;
221 // FALL THROUGH.
222 default:
223 // Skip this token.
224 ConsumeToken();
225 break;
226 }
227 isFirstTokenSkipped = false;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000228 }
Chris Lattner4b009652007-07-25 00:24:17 +0000229}
230
231//===----------------------------------------------------------------------===//
232// Scope manipulation
233//===----------------------------------------------------------------------===//
234
235/// EnterScope - Start a new scope.
236void Parser::EnterScope(unsigned ScopeFlags) {
237 if (NumCachedScopes) {
238 Scope *N = ScopeCache[--NumCachedScopes];
239 N->Init(CurScope, ScopeFlags);
240 CurScope = N;
241 } else {
242 CurScope = new Scope(CurScope, ScopeFlags);
243 }
244}
245
246/// ExitScope - Pop a scope off the scope stack.
247void Parser::ExitScope() {
248 assert(CurScope && "Scope imbalance!");
249
Chris Lattner62231492007-10-09 20:37:18 +0000250 // Inform the actions module that this scope is going away if there are any
251 // decls in it.
252 if (!CurScope->decl_empty())
Steve Naroff9637a9b2007-10-09 22:01:59 +0000253 Actions.ActOnPopScope(Tok.getLocation(), CurScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000254
Chris Lattner4b009652007-07-25 00:24:17 +0000255 Scope *OldScope = CurScope;
256 CurScope = OldScope->getParent();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000257
Chris Lattner4b009652007-07-25 00:24:17 +0000258 if (NumCachedScopes == ScopeCacheSize)
259 delete OldScope;
260 else
261 ScopeCache[NumCachedScopes++] = OldScope;
262}
263
264
265
266
267//===----------------------------------------------------------------------===//
268// C99 6.9: External Definitions.
269//===----------------------------------------------------------------------===//
270
271Parser::~Parser() {
272 // If we still have scopes active, delete the scope tree.
273 delete CurScope;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000274
Chris Lattner4b009652007-07-25 00:24:17 +0000275 // Free the scope cache.
276 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
277 delete ScopeCache[i];
Daniel Dunbar47f99c92008-10-04 19:21:03 +0000278
279 // Remove the pragma handlers we installed.
280 PP.RemovePragmaHandler(0, PackHandler);
281 delete PackHandler;
Chris Lattner4b009652007-07-25 00:24:17 +0000282}
283
284/// Initialize - Warm up the parser.
285///
286void Parser::Initialize() {
287 // Prime the lexer look-ahead.
288 ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000289
Chris Lattnera7549902007-08-26 06:24:45 +0000290 // Create the translation unit scope. Install it as the current scope.
Chris Lattner4b009652007-07-25 00:24:17 +0000291 assert(CurScope == 0 && "A scope is already active?");
Chris Lattnera7549902007-08-26 06:24:45 +0000292 EnterScope(Scope::DeclScope);
Steve Naroff9637a9b2007-10-09 22:01:59 +0000293 Actions.ActOnTranslationUnitScope(Tok.getLocation(), CurScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000294
Chris Lattner17a5fb62007-10-09 17:23:58 +0000295 if (Tok.is(tok::eof) &&
Chris Lattner7bdc85d2007-08-25 05:47:03 +0000296 !getLang().CPlusPlus) // Empty source file is an extension in C
Chris Lattner4b009652007-07-25 00:24:17 +0000297 Diag(Tok, diag::ext_empty_source_file);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000298
Chris Lattner32352462007-08-29 22:54:08 +0000299 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremenek42730c52008-01-07 19:49:32 +0000300 // Referenced in Parser::ParseObjCTypeQualifierList.
Chris Lattner32352462007-08-29 22:54:08 +0000301 if (getLang().ObjC1) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000302 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
303 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
304 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
305 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
306 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
307 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner32352462007-08-29 22:54:08 +0000308 }
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000309
310 Ident_super = &PP.getIdentifierTable().get("super");
Chris Lattner4b009652007-07-25 00:24:17 +0000311}
312
313/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
314/// action tells us to. This returns true if the EOF was encountered.
Steve Naroffca44ffd2007-11-29 23:05:20 +0000315bool Parser::ParseTopLevelDecl(DeclTy*& Result) {
316 Result = 0;
Chris Lattnerc1aea812008-08-23 03:19:52 +0000317 if (Tok.is(tok::eof)) {
318 Actions.ActOnEndOfTranslationUnit();
319 return true;
320 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000321
Steve Naroffca44ffd2007-11-29 23:05:20 +0000322 Result = ParseExternalDeclaration();
Chris Lattner4b009652007-07-25 00:24:17 +0000323 return false;
324}
325
Chris Lattner4b009652007-07-25 00:24:17 +0000326/// ParseTranslationUnit:
327/// translation-unit: [C99 6.9]
Mike Stumpeda58eb2008-06-19 19:28:49 +0000328/// external-declaration
329/// translation-unit external-declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000330void Parser::ParseTranslationUnit() {
Douglas Gregor95d40792008-12-10 06:34:36 +0000331 Initialize();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000332
Steve Naroffca44ffd2007-11-29 23:05:20 +0000333 DeclTy *Res;
334 while (!ParseTopLevelDecl(Res))
Chris Lattner4b009652007-07-25 00:24:17 +0000335 /*parse them all*/;
Chris Lattnerf7df4d12008-08-23 02:00:52 +0000336
337 ExitScope();
338 assert(CurScope == 0 && "Scope imbalance!");
Chris Lattner4b009652007-07-25 00:24:17 +0000339}
340
341/// ParseExternalDeclaration:
Chris Lattnereb54a362008-12-08 21:59:01 +0000342///
Douglas Gregor61818c52008-11-21 16:10:08 +0000343/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattner06f4e752007-08-10 20:57:02 +0000344/// function-definition
345/// declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000346/// [EXT] ';'
347/// [GNU] asm-definition
Chris Lattner06f4e752007-08-10 20:57:02 +0000348/// [GNU] __extension__ external-declaration
Chris Lattner4b009652007-07-25 00:24:17 +0000349/// [OBJC] objc-class-definition
350/// [OBJC] objc-class-declaration
351/// [OBJC] objc-alias-declaration
352/// [OBJC] objc-protocol-definition
353/// [OBJC] objc-method-definition
354/// [OBJC] @end
Douglas Gregor61818c52008-11-21 16:10:08 +0000355/// [C++] linkage-specification
Chris Lattner4b009652007-07-25 00:24:17 +0000356/// [GNU] asm-definition:
357/// simple-asm-expr ';'
358///
359Parser::DeclTy *Parser::ParseExternalDeclaration() {
360 switch (Tok.getKind()) {
361 case tok::semi:
362 Diag(Tok, diag::ext_top_level_semi);
363 ConsumeToken();
364 // TODO: Invoke action for top-level semicolon.
365 return 0;
Chris Lattnereb54a362008-12-08 21:59:01 +0000366 case tok::r_brace:
367 Diag(Tok, diag::err_expected_external_declaration);
368 ConsumeBrace();
369 return 0;
370 case tok::eof:
371 Diag(Tok, diag::err_expected_external_declaration);
372 return 0;
Chris Lattner06f4e752007-08-10 20:57:02 +0000373 case tok::kw___extension__: {
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000374 // __extension__ silences extension warnings in the subexpression.
375 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner658e6872008-10-20 06:51:33 +0000376 ConsumeToken();
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000377 return ParseExternalDeclaration();
Chris Lattner06f4e752007-08-10 20:57:02 +0000378 }
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000379 case tok::kw_asm: {
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000380 OwningExprResult Result(ParseSimpleAsm());
Mike Stumpeda58eb2008-06-19 19:28:49 +0000381
Anders Carlssonf41100b2008-02-08 00:23:11 +0000382 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
383 "top-level asm block");
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000384
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000385 if (!Result.isInvalid())
Sebastian Redl81db6682009-02-05 15:02:23 +0000386 return Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), move(Result));
Chris Lattnerb36c3652008-05-27 23:32:43 +0000387 return 0;
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000388 }
Chris Lattner4b009652007-07-25 00:24:17 +0000389 case tok::at:
390 // @ is not a legal token unless objc is enabled, no need to check.
Steve Narofffaed3bf2007-09-10 20:51:04 +0000391 return ParseObjCAtDirectives();
Chris Lattner4b009652007-07-25 00:24:17 +0000392 case tok::minus:
Chris Lattner4b009652007-07-25 00:24:17 +0000393 case tok::plus:
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +0000394 if (getLang().ObjC1)
Steve Naroff18c83382007-11-13 23:01:27 +0000395 return ParseObjCMethodDefinition();
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +0000396 else {
Chris Lattner4b009652007-07-25 00:24:17 +0000397 Diag(Tok, diag::err_expected_external_declaration);
398 ConsumeToken();
399 }
400 return 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000401 case tok::kw_using:
Chris Lattnerf7b2e552007-08-25 06:57:03 +0000402 case tok::kw_namespace:
Chris Lattner4b009652007-07-25 00:24:17 +0000403 case tok::kw_typedef:
Douglas Gregorb3bec712008-12-01 23:54:00 +0000404 case tok::kw_template:
405 case tok::kw_export: // As in 'export template'
Chris Lattner9c135722007-08-25 18:15:16 +0000406 // A function definition cannot start with a these keywords.
Chris Lattner4b009652007-07-25 00:24:17 +0000407 return ParseDeclaration(Declarator::FileContext);
408 default:
409 // We can't tell whether this is a function-definition or declaration yet.
410 return ParseDeclarationOrFunctionDefinition();
411 }
412}
413
414/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
415/// a declaration. We can't tell which we have until we read up to the
Douglas Gregor52473432008-12-24 02:52:09 +0000416/// compound-statement in function-definition. TemplateParams, if
417/// non-NULL, provides the template parameters when we're parsing a
418/// C++ template-declaration.
Chris Lattner4b009652007-07-25 00:24:17 +0000419///
420/// function-definition: [C99 6.9.1]
Chris Lattnera15e9d22008-04-05 05:52:15 +0000421/// decl-specs declarator declaration-list[opt] compound-statement
422/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpeda58eb2008-06-19 19:28:49 +0000423/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattnera15e9d22008-04-05 05:52:15 +0000424///
Chris Lattner4b009652007-07-25 00:24:17 +0000425/// declaration: [C99 6.7]
Chris Lattneraac973e2007-08-22 06:06:56 +0000426/// declaration-specifiers init-declarator-list[opt] ';'
427/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Chris Lattner4b009652007-07-25 00:24:17 +0000428/// [OMP] threadprivate-directive [TODO]
429///
Douglas Gregor52473432008-12-24 02:52:09 +0000430Parser::DeclTy *
431Parser::ParseDeclarationOrFunctionDefinition(
432 TemplateParameterLists *TemplateParams) {
Chris Lattner4b009652007-07-25 00:24:17 +0000433 // Parse the common declaration-specifiers piece.
434 DeclSpec DS;
Douglas Gregor52473432008-12-24 02:52:09 +0000435 ParseDeclarationSpecifiers(DS, TemplateParams);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000436
Chris Lattner4b009652007-07-25 00:24:17 +0000437 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
438 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner17a5fb62007-10-09 17:23:58 +0000439 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000440 ConsumeToken();
441 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
442 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000443
Daniel Dunbar28680d12008-09-26 04:48:09 +0000444 // ObjC2 allows prefix attributes on class interfaces and protocols.
445 // FIXME: This still needs better diagnostics. We should only accept
446 // attributes here, no types, etc.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000447 if (getLang().ObjC2 && Tok.is(tok::at)) {
Steve Narofffb367882007-08-20 21:31:48 +0000448 SourceLocation AtLoc = ConsumeToken(); // the "@"
Daniel Dunbar28680d12008-09-26 04:48:09 +0000449 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
450 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
451 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattner847f5c12007-12-27 19:57:00 +0000452 SkipUntil(tok::semi); // FIXME: better skip?
453 return 0;
454 }
Fariborz Jahanianf9c0a0d2008-01-02 19:17:38 +0000455 const char *PrevSpec = 0;
456 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec))
Chris Lattnerf006a222008-11-18 07:48:38 +0000457 Diag(AtLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Daniel Dunbar28680d12008-09-26 04:48:09 +0000458 if (Tok.isObjCAtKeyword(tok::objc_protocol))
459 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
Mike Stumpeda58eb2008-06-19 19:28:49 +0000460 return ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
Steve Narofffb367882007-08-20 21:31:48 +0000461 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000462
Chris Lattner806a5f52008-01-12 07:05:38 +0000463 // If the declspec consisted only of 'extern' and we have a string
464 // literal following it, this must be a C++ linkage specifier like
465 // 'extern "C"'.
Chris Lattner1b5c9f72008-01-12 07:08:43 +0000466 if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
Chris Lattner806a5f52008-01-12 07:05:38 +0000467 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
468 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier)
469 return ParseLinkage(Declarator::FileContext);
470
Chris Lattner4b009652007-07-25 00:24:17 +0000471 // Parse the first declarator.
472 Declarator DeclaratorInfo(DS, Declarator::FileContext);
473 ParseDeclarator(DeclaratorInfo);
474 // Error parsing the declarator?
Douglas Gregor6704b312008-11-17 22:58:34 +0000475 if (!DeclaratorInfo.hasName()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000476 // If so, skip until the semi-colon or a }.
Douglas Gregor6f730612008-12-01 23:03:32 +0000477 SkipUntil(tok::r_brace, true, true);
Chris Lattner17a5fb62007-10-09 17:23:58 +0000478 if (Tok.is(tok::semi))
Chris Lattner4b009652007-07-25 00:24:17 +0000479 ConsumeToken();
480 return 0;
481 }
482
483 // If the declarator is the start of a function definition, handle it.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000484 if (Tok.is(tok::equal) || // int X()= -> not a function def
485 Tok.is(tok::comma) || // int X(), -> not a function def
486 Tok.is(tok::semi) || // int X(); -> not a function def
487 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000488 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
489 (getLang().CPlusPlus &&
490 Tok.is(tok::l_paren)) ) { // int X(0) -> not a function def [C++]
Chris Lattner4b009652007-07-25 00:24:17 +0000491 // FALL THROUGH.
492 } else if (DeclaratorInfo.isFunctionDeclarator() &&
Argiris Kirtzidisd1346a52008-06-21 10:00:56 +0000493 (Tok.is(tok::l_brace) || // int X() {}
Chris Lattnerc6f830c2009-02-27 17:15:01 +0000494 (!getLang().CPlusPlus &&
495 isDeclarationSpecifier()))) { // int X(f) int f; {}
Steve Naroff83298852008-02-14 02:58:32 +0000496 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
497 Diag(Tok, diag::err_function_declared_typedef);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000498
Steve Naroff83298852008-02-14 02:58:32 +0000499 if (Tok.is(tok::l_brace)) {
500 // This recovery skips the entire function body. It would be nice
Douglas Gregordd861062008-12-05 18:15:24 +0000501 // to simply call ParseFunctionDefinition() below, however Sema
Steve Naroff83298852008-02-14 02:58:32 +0000502 // assumes the declarator represents a function, not a typedef.
503 ConsumeBrace();
504 SkipUntil(tok::r_brace, true);
505 } else {
506 SkipUntil(tok::semi);
507 }
508 return 0;
509 }
Chris Lattner4b009652007-07-25 00:24:17 +0000510 return ParseFunctionDefinition(DeclaratorInfo);
511 } else {
512 if (DeclaratorInfo.isFunctionDeclarator())
513 Diag(Tok, diag::err_expected_fn_body);
514 else
Chris Lattnerc6f830c2009-02-27 17:15:01 +0000515 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000516 SkipUntil(tok::semi);
517 return 0;
518 }
519
520 // Parse the init-declarator-list for a normal declaration.
521 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
522}
523
524/// ParseFunctionDefinition - We parsed and verified that the specified
525/// Declarator is well formed. If this is a K&R-style function, read the
526/// parameters declaration-list, then start the compound-statement.
527///
Chris Lattnera15e9d22008-04-05 05:52:15 +0000528/// function-definition: [C99 6.9.1]
529/// decl-specs declarator declaration-list[opt] compound-statement
530/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpeda58eb2008-06-19 19:28:49 +0000531/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000532/// [C++] function-definition: [C++ 8.4]
533/// decl-specifier-seq[opt] declarator ctor-initializer[opt] function-body
534/// [C++] function-definition: [C++ 8.4]
535/// decl-specifier-seq[opt] declarator function-try-block [TODO]
Chris Lattner4b009652007-07-25 00:24:17 +0000536///
537Parser::DeclTy *Parser::ParseFunctionDefinition(Declarator &D) {
538 const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
539 assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
540 "This isn't a function declarator!");
541 const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000542
Chris Lattnera15e9d22008-04-05 05:52:15 +0000543 // If this is C90 and the declspecs were completely missing, fudge in an
544 // implicit int. We do this here because this is the only place where
545 // declaration-specifiers are completely optional in the grammar.
Chris Lattner92eca3e2009-02-27 18:35:46 +0000546 if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
Chris Lattnera15e9d22008-04-05 05:52:15 +0000547 const char *PrevSpec;
Chris Lattner509fc802008-10-20 02:01:34 +0000548 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
549 D.getIdentifierLoc(),
550 PrevSpec);
Sebastian Redl0c986032009-02-09 18:23:29 +0000551 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattnera15e9d22008-04-05 05:52:15 +0000552 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000553
Chris Lattner4b009652007-07-25 00:24:17 +0000554 // If this declaration was formed with a K&R-style identifier list for the
555 // arguments, parse declarations for all of the args next.
556 // int foo(a,b) int a; float b; {}
557 if (!FTI.hasPrototype && FTI.NumArgs != 0)
558 ParseKNRParamDeclarations(D);
559
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000560 // We should have either an opening brace or, in a C++ constructor,
561 // we may have a colon.
Sebastian Redlf22270b2008-11-24 21:45:59 +0000562 // FIXME: In C++, we might also find the 'try' keyword.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000563 if (Tok.isNot(tok::l_brace) && Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000564 Diag(Tok, diag::err_expected_fn_body);
565
566 // Skip over garbage, until we get to '{'. Don't eat the '{'.
567 SkipUntil(tok::l_brace, true, true);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000568
Chris Lattner4b009652007-07-25 00:24:17 +0000569 // If we didn't find the '{', bail out.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000570 if (Tok.isNot(tok::l_brace))
Chris Lattner4b009652007-07-25 00:24:17 +0000571 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000572 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000573
Chris Lattnerea148702007-10-09 17:14:05 +0000574 // Enter a scope for the function body.
Douglas Gregor95d40792008-12-10 06:34:36 +0000575 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000576
Chris Lattnerea148702007-10-09 17:14:05 +0000577 // Tell the actions module that we have entered a function definition with the
578 // specified Declarator for the function.
579 DeclTy *Res = Actions.ActOnStartOfFunctionDef(CurScope, D);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000580
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000581 // If we have a colon, then we're probably parsing a C++
582 // ctor-initializer.
583 if (Tok.is(tok::colon))
584 ParseConstructorInitializer(Res);
585
586 SourceLocation BraceLoc = Tok.getLocation();
Chris Lattner0818a7a2009-03-05 00:49:17 +0000587 return ParseFunctionStatementBody(Res);
Chris Lattner4b009652007-07-25 00:24:17 +0000588}
589
590/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
591/// types for a function with a K&R-style identifier list for arguments.
592void Parser::ParseKNRParamDeclarations(Declarator &D) {
593 // We know that the top-level of this declarator is a function.
594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
595
Chris Lattner3e254fb2008-04-08 04:40:51 +0000596 // Enter function-declaration scope, limiting any declarators to the
597 // function prototype scope, including parameter declarators.
Douglas Gregorcab994d2009-01-09 22:42:13 +0000598 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000599
Chris Lattner4b009652007-07-25 00:24:17 +0000600 // Read all the argument declarations.
601 while (isDeclarationSpecifier()) {
602 SourceLocation DSStart = Tok.getLocation();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000603
Chris Lattner4b009652007-07-25 00:24:17 +0000604 // Parse the common declaration-specifiers piece.
605 DeclSpec DS;
606 ParseDeclarationSpecifiers(DS);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000607
Chris Lattner4b009652007-07-25 00:24:17 +0000608 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
609 // least one declarator'.
610 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
611 // the declarations though. It's trivial to ignore them, really hard to do
612 // anything else with them.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000613 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000614 Diag(DSStart, diag::err_declaration_does_not_declare_param);
615 ConsumeToken();
616 continue;
617 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000618
Chris Lattner4b009652007-07-25 00:24:17 +0000619 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
620 // than register.
621 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
622 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
623 Diag(DS.getStorageClassSpecLoc(),
624 diag::err_invalid_storage_class_in_func_decl);
625 DS.ClearStorageClassSpecs();
626 }
627 if (DS.isThreadSpecified()) {
628 Diag(DS.getThreadSpecLoc(),
629 diag::err_invalid_storage_class_in_func_decl);
630 DS.ClearStorageClassSpecs();
631 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000632
Chris Lattner4b009652007-07-25 00:24:17 +0000633 // Parse the first declarator attached to this declspec.
634 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
635 ParseDeclarator(ParmDeclarator);
636
637 // Handle the full declarator list.
638 while (1) {
639 DeclTy *AttrList;
640 // If attributes are present, parse them.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000641 if (Tok.is(tok::kw___attribute))
Chris Lattner4b009652007-07-25 00:24:17 +0000642 // FIXME: attach attributes too.
643 AttrList = ParseAttributes();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 // Ask the actions module to compute the type for this declarator.
Mike Stumpeda58eb2008-06-19 19:28:49 +0000646 Action::DeclTy *Param =
Chris Lattner3e254fb2008-04-08 04:40:51 +0000647 Actions.ActOnParamDeclarator(CurScope, ParmDeclarator);
Steve Narofffaed3bf2007-09-10 20:51:04 +0000648
Mike Stumpeda58eb2008-06-19 19:28:49 +0000649 if (Param &&
Chris Lattner4b009652007-07-25 00:24:17 +0000650 // A missing identifier has already been diagnosed.
651 ParmDeclarator.getIdentifier()) {
652
653 // Scan the argument list looking for the correct param to apply this
654 // type.
655 for (unsigned i = 0; ; ++i) {
656 // C99 6.9.1p6: those declarators shall declare only identifiers from
657 // the identifier list.
658 if (i == FTI.NumArgs) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000659 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattnerb12ef862008-11-19 07:51:13 +0000660 << ParmDeclarator.getIdentifier();
Chris Lattner4b009652007-07-25 00:24:17 +0000661 break;
662 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000663
Chris Lattner4b009652007-07-25 00:24:17 +0000664 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
665 // Reject redefinitions of parameters.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000666 if (FTI.ArgInfo[i].Param) {
Chris Lattner4b009652007-07-25 00:24:17 +0000667 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattnerf006a222008-11-18 07:48:38 +0000668 diag::err_param_redefinition)
Chris Lattnerb12ef862008-11-19 07:51:13 +0000669 << ParmDeclarator.getIdentifier();
Chris Lattner4b009652007-07-25 00:24:17 +0000670 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000671 FTI.ArgInfo[i].Param = Param;
Chris Lattner4b009652007-07-25 00:24:17 +0000672 }
673 break;
674 }
675 }
676 }
677
678 // If we don't have a comma, it is either the end of the list (a ';') or
679 // an error, bail out.
Chris Lattner17a5fb62007-10-09 17:23:58 +0000680 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000681 break;
Mike Stumpeda58eb2008-06-19 19:28:49 +0000682
Chris Lattner4b009652007-07-25 00:24:17 +0000683 // Consume the comma.
684 ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000685
Chris Lattner4b009652007-07-25 00:24:17 +0000686 // Parse the next declarator.
687 ParmDeclarator.clear();
688 ParseDeclarator(ParmDeclarator);
689 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000690
Chris Lattner17a5fb62007-10-09 17:23:58 +0000691 if (Tok.is(tok::semi)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000692 ConsumeToken();
693 } else {
694 Diag(Tok, diag::err_parse_error);
695 // Skip to end of block or statement
696 SkipUntil(tok::semi, true);
Chris Lattner17a5fb62007-10-09 17:23:58 +0000697 if (Tok.is(tok::semi))
Chris Lattner4b009652007-07-25 00:24:17 +0000698 ConsumeToken();
699 }
700 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000701
Chris Lattner4b009652007-07-25 00:24:17 +0000702 // The actions module must verify that all arguments were declared.
Douglas Gregor65075ec2009-01-23 16:23:13 +0000703 Actions.ActOnFinishKNRParamDeclarations(CurScope, D);
Chris Lattner4b009652007-07-25 00:24:17 +0000704}
705
706
707/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
708/// allowed to be a wide string, and is not subject to character translation.
709///
710/// [GNU] asm-string-literal:
711/// string-literal
712///
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000713Parser::OwningExprResult Parser::ParseAsmStringLiteral() {
Chris Lattner4b009652007-07-25 00:24:17 +0000714 if (!isTokenStringLiteral()) {
715 Diag(Tok, diag::err_expected_string_literal);
Sebastian Redl10c32952008-12-11 19:30:53 +0000716 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000717 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000718
Sebastian Redl39d4f022008-12-11 22:51:44 +0000719 OwningExprResult Res(ParseStringLiteralExpression());
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000720 if (Res.isInvalid()) return move(Res);
Mike Stumpeda58eb2008-06-19 19:28:49 +0000721
Chris Lattner4b009652007-07-25 00:24:17 +0000722 // TODO: Diagnose: wide string literal in 'asm'
Mike Stumpeda58eb2008-06-19 19:28:49 +0000723
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000724 return move(Res);
Chris Lattner4b009652007-07-25 00:24:17 +0000725}
726
727/// ParseSimpleAsm
728///
729/// [GNU] simple-asm-expr:
730/// 'asm' '(' asm-string-literal ')'
731///
Sebastian Redl0c986032009-02-09 18:23:29 +0000732Parser::OwningExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner17a5fb62007-10-09 17:23:58 +0000733 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlsson4f7f4412008-02-08 00:33:21 +0000734 SourceLocation Loc = ConsumeToken();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000735
Chris Lattner17a5fb62007-10-09 17:23:58 +0000736 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000737 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl10c32952008-12-11 19:30:53 +0000738 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000739 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000740
Sebastian Redl0c986032009-02-09 18:23:29 +0000741 Loc = ConsumeParen();
Mike Stumpeda58eb2008-06-19 19:28:49 +0000742
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000743 OwningExprResult Result(ParseAsmStringLiteral());
Mike Stumpeda58eb2008-06-19 19:28:49 +0000744
Sebastian Redl0c986032009-02-09 18:23:29 +0000745 if (Result.isInvalid()) {
746 SkipUntil(tok::r_paren, true, true);
747 if (EndLoc)
748 *EndLoc = Tok.getLocation();
749 ConsumeAnyToken();
750 } else {
751 Loc = MatchRHSPunctuation(tok::r_paren, Loc);
752 if (EndLoc)
753 *EndLoc = Loc;
754 }
Mike Stumpeda58eb2008-06-19 19:28:49 +0000755
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000756 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000757}
758
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000759/// TryAnnotateTypeOrScopeToken - If the current token position is on a
760/// typename (possibly qualified in C++) or a C++ scope specifier not followed
761/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
762/// with a single annotation token representing the typename or C++ scope
763/// respectively.
764/// This simplifies handling of C++ scope specifiers and allows efficient
765/// backtracking without the need to re-parse and resolve nested-names and
766/// typenames.
Argiris Kirtzidisfc332322008-11-26 21:51:07 +0000767/// It will mainly be called when we expect to treat identifiers as typenames
768/// (if they are typenames). For example, in C we do not expect identifiers
769/// inside expressions to be treated as typenames so it will not be called
770/// for expressions in C.
771/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroff7b36a1b2009-01-28 19:39:02 +0000772/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argiris Kirtzidisfc332322008-11-26 21:51:07 +0000773/// will not be called twice, once to check whether we have a declaration
774/// specifier, and another one to get the actual type inside
775/// ParseDeclarationSpecifiers).
Chris Lattner1e015942009-01-04 23:23:14 +0000776///
777/// This returns true if the token was annotated.
Chris Lattner2c301452009-01-05 00:13:00 +0000778///
779/// Note that this routine emits an error if you call it with ::new or ::delete
780/// as the current tokens, so only call it in contexts where these are invalid.
Chris Lattner94a15bd2009-01-05 03:55:46 +0000781bool Parser::TryAnnotateTypeOrScopeToken() {
Chris Lattner8376d2e2009-01-05 01:24:05 +0000782 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
783 "Cannot be a type or scope token!");
784
785 // FIXME: Implement template-ids
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000786 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000787 if (getLang().CPlusPlus)
Chris Lattnerd706dc82009-01-06 06:59:53 +0000788 ParseOptionalCXXScopeSpecifier(SS);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000789
790 if (Tok.is(tok::identifier)) {
Chris Lattnera9d6ec72009-01-05 01:49:50 +0000791 // Determine whether the identifier is a type name.
Steve Naroff7b36a1b2009-01-28 19:39:02 +0000792 if (TypeTy *Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
Douglas Gregor1075a162009-02-04 17:00:24 +0000793 Tok.getLocation(), CurScope, &SS)) {
Chris Lattnera9d6ec72009-01-05 01:49:50 +0000794 // This is a typename. Replace the current token in-place with an
795 // annotation type token.
Chris Lattner5d7eace2009-01-06 05:06:21 +0000796 Tok.setKind(tok::annot_typename);
Chris Lattnera9d6ec72009-01-05 01:49:50 +0000797 Tok.setAnnotationValue(Ty);
798 Tok.setAnnotationEndLoc(Tok.getLocation());
799 if (SS.isNotEmpty()) // it was a C++ qualified type name.
800 Tok.setLocation(SS.getBeginLoc());
801
802 // In case the tokens were cached, have Preprocessor replace
803 // them with the annotation token.
804 PP.AnnotateCachedTokens(Tok);
805 return true;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000806 }
807
808 if (!getLang().CPlusPlus) {
Chris Lattnera9d6ec72009-01-05 01:49:50 +0000809 // If we're in C, we can't have :: tokens at all (the lexer won't return
810 // them). If the identifier is not a type, then it can't be scope either,
811 // just early exit.
812 return false;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000813 }
Chris Lattnera9d6ec72009-01-05 01:49:50 +0000814
Douglas Gregor0c281a82009-02-25 19:37:18 +0000815 // If this is a template-id, annotate with a template-id or type token.
Douglas Gregor8e458f42009-02-09 18:46:07 +0000816 if (NextToken().is(tok::less)) {
817 DeclTy *Template;
818 if (TemplateNameKind TNK
819 = Actions.isTemplateName(*Tok.getIdentifierInfo(),
Douglas Gregor0c281a82009-02-25 19:37:18 +0000820 CurScope, Template, &SS))
Douglas Gregor8e458f42009-02-09 18:46:07 +0000821 AnnotateTemplateIdToken(Template, TNK, &SS);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000822 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000823
Douglas Gregor0c281a82009-02-25 19:37:18 +0000824 // The current token, which is either an identifier or a
825 // template-id, is not part of the annotation. Fall through to
826 // push that token back into the stream and complete the C++ scope
827 // specifier annotation.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000828 }
829
Douglas Gregor0c281a82009-02-25 19:37:18 +0000830 if (Tok.is(tok::annot_template_id)) {
831 TemplateIdAnnotation *TemplateId
832 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
833 if (TemplateId->Kind == TNK_Class_template) {
834 // A template-id that refers to a type was parsed into a
835 // template-id annotation in a context where we weren't allowed
836 // to produce a type annotation token. Update the template-id
837 // annotation token to a type annotation token now.
838 return !AnnotateTemplateIdTokenAsType(&SS);
839 }
840 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000841
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000842 if (SS.isEmpty())
Chris Lattner1e015942009-01-04 23:23:14 +0000843 return false;
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000844
845 // A C++ scope specifier that isn't followed by a typename.
846 // Push the current token back into the token stream (or revert it if it is
847 // cached) and use an annotation scope token for current token.
848 if (PP.isBacktrackEnabled())
849 PP.RevertCachedTokens(1);
850 else
851 PP.EnterToken(Tok);
852 Tok.setKind(tok::annot_cxxscope);
853 Tok.setAnnotationValue(SS.getScopeRep());
854 Tok.setAnnotationRange(SS.getRange());
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000855
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000856 // In case the tokens were cached, have Preprocessor replace them with the
857 // annotation token.
858 PP.AnnotateCachedTokens(Tok);
Chris Lattner1e015942009-01-04 23:23:14 +0000859 return true;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000860}
861
862/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Douglas Gregor0c281a82009-02-25 19:37:18 +0000863/// annotates C++ scope specifiers and template-ids. This returns
864/// true if the token was annotated.
Chris Lattner2c301452009-01-05 00:13:00 +0000865///
866/// Note that this routine emits an error if you call it with ::new or ::delete
867/// as the current tokens, so only call it in contexts where these are invalid.
Chris Lattner712f9a32009-01-05 00:07:25 +0000868bool Parser::TryAnnotateCXXScopeToken() {
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000869 assert(getLang().CPlusPlus &&
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000870 "Call sites of this function should be guarded by checking for C++");
Chris Lattner8376d2e2009-01-05 01:24:05 +0000871 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
872 "Cannot be a type or scope token!");
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000873
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000874 CXXScopeSpec SS;
Chris Lattnerd706dc82009-01-06 06:59:53 +0000875 if (!ParseOptionalCXXScopeSpecifier(SS))
Douglas Gregor0c281a82009-02-25 19:37:18 +0000876 return Tok.is(tok::annot_template_id);
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000877
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000878 // Push the current token back into the token stream (or revert it if it is
879 // cached) and use an annotation scope token for current token.
880 if (PP.isBacktrackEnabled())
881 PP.RevertCachedTokens(1);
882 else
883 PP.EnterToken(Tok);
884 Tok.setKind(tok::annot_cxxscope);
885 Tok.setAnnotationValue(SS.getScopeRep());
886 Tok.setAnnotationRange(SS.getRange());
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000887
Chris Lattnerf72f79c2009-01-04 22:32:19 +0000888 // In case the tokens were cached, have Preprocessor replace them with the
889 // annotation token.
890 PP.AnnotateCachedTokens(Tok);
Chris Lattner712f9a32009-01-05 00:07:25 +0000891 return true;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000892}