blob: fef903b2fc75511a7440e3bc979db43768d20fc6 [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//
Chris Lattner5b12ab82007-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 Lattner0bb5f832006-07-31 01:59:18 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner60f36222009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
Chris Lattnerbcfe4f72009-03-05 07:24:28 +000019#include "llvm/Support/raw_ostream.h"
Chris Lattner8a9a97a2009-12-10 00:21:05 +000020#include "RAIIObjectsForParser.h"
Daniel Dunbar921b9682008-10-04 19:21:03 +000021#include "ParsePragma.h"
Francois Pichet1c229c02011-04-22 22:18:13 +000022#include "clang/AST/DeclTemplate.h"
Francois Picheta5b3fcb2011-05-07 17:30:27 +000023#include "clang/AST/ASTConsumer.h"
Chris Lattner0bb5f832006-07-31 01:59:18 +000024using namespace clang;
25
Mahesha S5d610972012-10-27 09:05:45 +000026
Benjamin Kramer7ca3b7c2012-07-13 13:25:11 +000027namespace {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000028/// \brief A comment handler that passes comments found by the preprocessor
29/// to the parser action.
30class ActionCommentHandler : public CommentHandler {
31 Sema &S;
32
33public:
34 explicit ActionCommentHandler(Sema &S) : S(S) { }
35
36 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37 S.ActOnComment(Comment);
38 return false;
39 }
40};
Benjamin Kramer7ca3b7c2012-07-13 13:25:11 +000041} // end anonymous namespace
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000042
Douglas Gregor60060d62011-10-21 03:57:52 +000043IdentifierInfo *Parser::getSEHExceptKeyword() {
44 // __except is accepted as a (contextual) keyword
David Blaikiebbafb8a2012-03-11 07:00:24 +000045 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
Douglas Gregor60060d62011-10-21 03:57:52 +000046 Ident__except = PP.getIdentifierInfo("__except");
47
48 return Ident__except;
49}
50
Erik Verbruggen6e922512012-04-12 10:11:59 +000051Parser::Parser(Preprocessor &pp, Sema &actions, bool SkipFunctionBodies)
Ted Kremenek4c9d46b2011-03-22 01:15:17 +000052 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
Douglas Gregore9bba4f2010-09-15 14:51:05 +000053 GreaterThanIsOperator(true), ColonIsSacred(false),
Erik Verbruggen6e922512012-04-12 10:11:59 +000054 InMessageExpression(false), TemplateParameterDepth(0),
Jordan Rose12e730c2012-07-09 16:54:53 +000055 ParsingInObjCContainer(false), SkipFunctionBodies(SkipFunctionBodies) {
Chris Lattner8c204872006-10-14 05:19:21 +000056 Tok.setKind(tok::eof);
Douglas Gregor0be31a22010-07-02 17:43:08 +000057 Actions.CurScope = 0;
Chris Lattner03928c72007-07-15 00:04:39 +000058 NumCachedScopes = 0;
Chris Lattnereec40f92006-08-06 21:55:29 +000059 ParenCount = BracketCount = BraceCount = 0;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +000060 CurParsedObjCImpl = 0;
Daniel Dunbar921b9682008-10-04 19:21:03 +000061
62 // Add #pragma handlers. These are removed and destroyed in the
63 // destructor.
Eli Friedman68be1642012-10-04 02:36:51 +000064 AlignHandler.reset(new PragmaAlignHandler());
Daniel Dunbarcb82acb2010-07-31 19:17:07 +000065 PP.AddPragmaHandler(AlignHandler.get());
66
Eli Friedman68be1642012-10-04 02:36:51 +000067 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
Eli Friedman570024a2010-08-05 06:57:20 +000068 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
69
Eli Friedman68be1642012-10-04 02:36:51 +000070 OptionsHandler.reset(new PragmaOptionsHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000071 PP.AddPragmaHandler(OptionsHandler.get());
Daniel Dunbar75c9be72010-05-26 23:29:06 +000072
Eli Friedman68be1642012-10-04 02:36:51 +000073 PackHandler.reset(new PragmaPackHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000074 PP.AddPragmaHandler(PackHandler.get());
Fariborz Jahanian743dda42011-04-25 18:49:15 +000075
Eli Friedman68be1642012-10-04 02:36:51 +000076 MSStructHandler.reset(new PragmaMSStructHandler());
Fariborz Jahanian743dda42011-04-25 18:49:15 +000077 PP.AddPragmaHandler(MSStructHandler.get());
Mike Stump11289f42009-09-09 15:08:12 +000078
Eli Friedman68be1642012-10-04 02:36:51 +000079 UnusedHandler.reset(new PragmaUnusedHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000080 PP.AddPragmaHandler(UnusedHandler.get());
Eli Friedmanf5867dd2009-06-05 00:49:58 +000081
Eli Friedman68be1642012-10-04 02:36:51 +000082 WeakHandler.reset(new PragmaWeakHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000083 PP.AddPragmaHandler(WeakHandler.get());
Peter Collingbourne564c0fa2011-02-14 01:42:35 +000084
Eli Friedman68be1642012-10-04 02:36:51 +000085 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
David Chisnall0867d9c2012-02-18 16:12:34 +000086 PP.AddPragmaHandler(RedefineExtnameHandler.get());
87
Eli Friedman68be1642012-10-04 02:36:51 +000088 FPContractHandler.reset(new PragmaFPContractHandler());
Peter Collingbourne564c0fa2011-02-14 01:42:35 +000089 PP.AddPragmaHandler("STDC", FPContractHandler.get());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +000090
David Blaikiebbafb8a2012-03-11 07:00:24 +000091 if (getLangOpts().OpenCL) {
Eli Friedman68be1642012-10-04 02:36:51 +000092 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +000093 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
94
95 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
96 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000097
Dmitri Gribenko17e147f2012-06-20 01:06:08 +000098 CommentSemaHandler.reset(new ActionCommentHandler(actions));
99 PP.addCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000100
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000101 PP.setCodeCompletionHandler(*this);
Chris Lattner971c6b62006-08-05 22:46:42 +0000102}
103
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000104/// If a crash happens while the parser is active, print out a line indicating
105/// what the current token is.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000106void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000107 const Token &Tok = P.getCurToken();
Chris Lattnerf02db352009-03-05 07:27:50 +0000108 if (Tok.is(tok::eof)) {
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000109 OS << "<eof> parser at end of file\n";
110 return;
111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattnerf02db352009-03-05 07:27:50 +0000113 if (Tok.getLocation().isInvalid()) {
114 OS << "<unknown> parser at unknown location\n";
115 return;
116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000118 const Preprocessor &PP = P.getPreprocessor();
119 Tok.getLocation().print(OS, PP.getSourceManager());
Daniel Dunbar68d9d7b2009-10-17 06:13:04 +0000120 if (Tok.isAnnotation())
121 OS << ": at annotation token \n";
122 else
123 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
Douglas Gregord7c4d982008-12-30 03:27:21 +0000124}
Chris Lattner0bb5f832006-07-31 01:59:18 +0000125
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000126
Chris Lattner427c9c12008-11-22 00:59:29 +0000127DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000128 return Diags.Report(Loc, DiagID);
Chris Lattner6d29c102008-11-18 07:48:38 +0000129}
130
Chris Lattner427c9c12008-11-22 00:59:29 +0000131DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000132 return Diag(Tok.getLocation(), DiagID);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000133}
134
Douglas Gregor87f95b02009-02-26 21:00:50 +0000135/// \brief Emits a diagnostic suggesting parentheses surrounding a
136/// given range.
137///
138/// \param Loc The location where we'll emit the diagnostic.
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000139/// \param DK The kind of diagnostic to emit.
Douglas Gregor87f95b02009-02-26 21:00:50 +0000140/// \param ParenRange Source range enclosing code that should be parenthesized.
141void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
142 SourceRange ParenRange) {
Douglas Gregor96977da2009-02-27 17:53:17 +0000143 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
144 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Douglas Gregor87f95b02009-02-26 21:00:50 +0000145 // We can't display the parentheses, so just dig the
146 // warning/error and return.
147 Diag(Loc, DK);
148 return;
149 }
Mike Stump11289f42009-09-09 15:08:12 +0000150
151 Diag(Loc, DK)
Douglas Gregora771f462010-03-31 17:46:05 +0000152 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
153 << FixItHint::CreateInsertion(EndLoc, ")");
Douglas Gregor87f95b02009-02-26 21:00:50 +0000154}
155
John McCall1ca73da2010-09-07 18:31:03 +0000156static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
157 switch (ExpectedTok) {
Richard Smith0875c532012-09-18 00:52:05 +0000158 case tok::semi:
159 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
John McCall1ca73da2010-09-07 18:31:03 +0000160 default: return false;
161 }
162}
163
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000164/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
165/// input. If so, it is consumed and false is returned.
166///
167/// If the input is malformed, this emits the specified diagnostic. Next, if
168/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
169/// returned.
170bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
Chris Lattner6d7e6342006-08-15 03:41:14 +0000171 const char *Msg, tok::TokenKind SkipToTok) {
Douglas Gregor6da3db42010-05-25 05:58:43 +0000172 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
Chris Lattner15a00da2006-08-15 04:10:31 +0000173 ConsumeAnyToken();
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000174 return false;
175 }
Mike Stump01e07652008-06-19 19:28:49 +0000176
John McCall1ca73da2010-09-07 18:31:03 +0000177 // Detect common single-character typos and resume.
178 if (IsCommonTypo(ExpectedTok, Tok)) {
179 SourceLocation Loc = Tok.getLocation();
180 Diag(Loc, DiagID)
181 << Msg
182 << FixItHint::CreateReplacement(SourceRange(Loc),
183 getTokenSimpleSpelling(ExpectedTok));
184 ConsumeAnyToken();
185
186 // Pretend there wasn't a problem.
187 return false;
188 }
189
Douglas Gregor87f95b02009-02-26 21:00:50 +0000190 const char *Spelling = 0;
Douglas Gregor96977da2009-02-27 17:53:17 +0000191 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
Mike Stump11289f42009-09-09 15:08:12 +0000192 if (EndLoc.isValid() &&
Douglas Gregor96977da2009-02-27 17:53:17 +0000193 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Douglas Gregor87f95b02009-02-26 21:00:50 +0000194 // Show what code to insert to fix this problem.
Mike Stump11289f42009-09-09 15:08:12 +0000195 Diag(EndLoc, DiagID)
Douglas Gregor87f95b02009-02-26 21:00:50 +0000196 << Msg
Douglas Gregora771f462010-03-31 17:46:05 +0000197 << FixItHint::CreateInsertion(EndLoc, Spelling);
Douglas Gregor87f95b02009-02-26 21:00:50 +0000198 } else
199 Diag(Tok, DiagID) << Msg;
200
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000201 if (SkipToTok != tok::unknown)
202 SkipUntil(SkipToTok);
203 return true;
204}
205
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000206bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
207 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
Douglas Gregor25c16092012-05-02 14:34:16 +0000208 ConsumeToken();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000209 return false;
210 }
211
212 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
213 NextToken().is(tok::semi)) {
214 Diag(Tok, diag::err_extraneous_token_before_semi)
215 << PP.getSpelling(Tok)
216 << FixItHint::CreateRemoval(Tok.getLocation());
217 ConsumeAnyToken(); // The ')' or ']'.
218 ConsumeToken(); // The ';'.
219 return false;
220 }
221
222 return ExpectAndConsume(tok::semi, DiagID);
223}
224
Richard Smith87f5dc52012-07-23 05:45:25 +0000225void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
Richard Trieu2f7dc462012-05-16 19:04:59 +0000226 if (!Tok.is(tok::semi)) return;
227
Richard Smith87f5dc52012-07-23 05:45:25 +0000228 bool HadMultipleSemis = false;
Richard Trieu2f7dc462012-05-16 19:04:59 +0000229 SourceLocation StartLoc = Tok.getLocation();
230 SourceLocation EndLoc = Tok.getLocation();
231 ConsumeToken();
232
233 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
Richard Smith87f5dc52012-07-23 05:45:25 +0000234 HadMultipleSemis = true;
Richard Trieu2f7dc462012-05-16 19:04:59 +0000235 EndLoc = Tok.getLocation();
236 ConsumeToken();
237 }
238
Richard Smith87f5dc52012-07-23 05:45:25 +0000239 // C++11 allows extra semicolons at namespace scope, but not in any of the
240 // other contexts.
241 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
242 if (getLangOpts().CPlusPlus0x)
243 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
244 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
245 else
246 Diag(StartLoc, diag::ext_extra_semi_cxx11)
247 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu2f7dc462012-05-16 19:04:59 +0000248 return;
249 }
250
Richard Smith87f5dc52012-07-23 05:45:25 +0000251 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
252 Diag(StartLoc, diag::ext_extra_semi)
253 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
254 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
255 else
256 // A single semicolon is valid after a member function definition.
257 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
258 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu2f7dc462012-05-16 19:04:59 +0000259}
260
Chris Lattner70f32b72006-07-31 05:09:04 +0000261//===----------------------------------------------------------------------===//
Chris Lattnereec40f92006-08-06 21:55:29 +0000262// Error recovery.
263//===----------------------------------------------------------------------===//
264
265/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner01e4b242007-07-24 17:03:04 +0000266/// it (unless DontConsume is true). Because we cannot guarantee that the
Chris Lattnereec40f92006-08-06 21:55:29 +0000267/// token will ever occur, this skips to the next token, or to some likely
268/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
269/// character.
Mike Stump01e07652008-06-19 19:28:49 +0000270///
Chris Lattnereec40f92006-08-06 21:55:29 +0000271/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stump01e07652008-06-19 19:28:49 +0000272/// returns false.
David Blaikie80cdddc2012-04-09 16:37:11 +0000273bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
274 bool DontConsume, bool StopAtCodeCompletion) {
Chris Lattner5bd57e02006-08-11 06:40:25 +0000275 // We always want this function to skip at least one token if the first token
276 // isn't T and if not at EOF.
277 bool isFirstTokenSkipped = true;
Chris Lattnereec40f92006-08-06 21:55:29 +0000278 while (1) {
Chris Lattner83b94e02007-04-27 19:12:15 +0000279 // If we found one of the tokens, stop and return true.
David Blaikie80cdddc2012-04-09 16:37:11 +0000280 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
Chris Lattner0ab032a2007-10-09 17:23:58 +0000281 if (Tok.is(Toks[i])) {
Chris Lattner83b94e02007-04-27 19:12:15 +0000282 if (DontConsume) {
283 // Noop, don't consume the token.
284 } else {
285 ConsumeAnyToken();
286 }
287 return true;
Chris Lattnereec40f92006-08-06 21:55:29 +0000288 }
Chris Lattnereec40f92006-08-06 21:55:29 +0000289 }
Mike Stump01e07652008-06-19 19:28:49 +0000290
Chris Lattnereec40f92006-08-06 21:55:29 +0000291 switch (Tok.getKind()) {
292 case tok::eof:
293 // Ran out of tokens.
294 return false;
Douglas Gregor6da3db42010-05-25 05:58:43 +0000295
296 case tok::code_completion:
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000297 if (!StopAtCodeCompletion)
298 ConsumeToken();
Douglas Gregor6da3db42010-05-25 05:58:43 +0000299 return false;
300
Chris Lattnereec40f92006-08-06 21:55:29 +0000301 case tok::l_paren:
302 // Recursively skip properly-nested parens.
303 ConsumeParen();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000304 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000305 break;
306 case tok::l_square:
307 // Recursively skip properly-nested square brackets.
308 ConsumeBracket();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000309 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000310 break;
311 case tok::l_brace:
312 // Recursively skip properly-nested braces.
313 ConsumeBrace();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000314 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000315 break;
Mike Stump01e07652008-06-19 19:28:49 +0000316
Chris Lattnereec40f92006-08-06 21:55:29 +0000317 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
318 // Since the user wasn't looking for this token (if they were, it would
319 // already be handled), this isn't balanced. If there is a LHS token at a
320 // higher level, we will assume that this matches the unbalanced token
321 // and return it. Otherwise, this is a spurious RHS token, which we skip.
322 case tok::r_paren:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000323 if (ParenCount && !isFirstTokenSkipped)
324 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000325 ConsumeParen();
326 break;
327 case tok::r_square:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000328 if (BracketCount && !isFirstTokenSkipped)
329 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000330 ConsumeBracket();
331 break;
332 case tok::r_brace:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000333 if (BraceCount && !isFirstTokenSkipped)
334 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000335 ConsumeBrace();
336 break;
Mike Stump01e07652008-06-19 19:28:49 +0000337
Chris Lattnereec40f92006-08-06 21:55:29 +0000338 case tok::string_literal:
Chris Lattnerd3e98952006-10-06 05:22:26 +0000339 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000340 case tok::utf8_string_literal:
341 case tok::utf16_string_literal:
342 case tok::utf32_string_literal:
Chris Lattnereec40f92006-08-06 21:55:29 +0000343 ConsumeStringToken();
344 break;
Fariborz Jahanian82ff1e52011-02-23 00:11:21 +0000345
Chris Lattnereec40f92006-08-06 21:55:29 +0000346 case tok::semi:
347 if (StopAtSemi)
348 return false;
349 // FALL THROUGH.
350 default:
351 // Skip this token.
352 ConsumeToken();
353 break;
354 }
Chris Lattner5bd57e02006-08-11 06:40:25 +0000355 isFirstTokenSkipped = false;
Mike Stump01e07652008-06-19 19:28:49 +0000356 }
Chris Lattnereec40f92006-08-06 21:55:29 +0000357}
358
359//===----------------------------------------------------------------------===//
Chris Lattnere4e38592006-08-14 00:15:05 +0000360// Scope manipulation
361//===----------------------------------------------------------------------===//
362
363/// EnterScope - Start a new scope.
Chris Lattner33ad2ca2006-11-05 23:47:55 +0000364void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner03928c72007-07-15 00:04:39 +0000365 if (NumCachedScopes) {
366 Scope *N = ScopeCache[--NumCachedScopes];
Douglas Gregor0be31a22010-07-02 17:43:08 +0000367 N->Init(getCurScope(), ScopeFlags);
368 Actions.CurScope = N;
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000369 } else {
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +0000370 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000371 }
Chris Lattnere4e38592006-08-14 00:15:05 +0000372}
373
374/// ExitScope - Pop a scope off the scope stack.
375void Parser::ExitScope() {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000376 assert(getCurScope() && "Scope imbalance!");
Chris Lattnere4e38592006-08-14 00:15:05 +0000377
Chris Lattner87547e62007-10-09 20:37:18 +0000378 // Inform the actions module that this scope is going away if there are any
379 // decls in it.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000380 if (!getCurScope()->decl_empty())
381 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
Mike Stump01e07652008-06-19 19:28:49 +0000382
Douglas Gregor0be31a22010-07-02 17:43:08 +0000383 Scope *OldScope = getCurScope();
384 Actions.CurScope = OldScope->getParent();
Mike Stump01e07652008-06-19 19:28:49 +0000385
Chris Lattner03928c72007-07-15 00:04:39 +0000386 if (NumCachedScopes == ScopeCacheSize)
387 delete OldScope;
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000388 else
Chris Lattner03928c72007-07-15 00:04:39 +0000389 ScopeCache[NumCachedScopes++] = OldScope;
Chris Lattnere4e38592006-08-14 00:15:05 +0000390}
391
Richard Smith938f40b2011-06-11 17:19:42 +0000392/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
393/// this object does nothing.
394Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
395 bool ManageFlags)
396 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
397 if (CurScope) {
398 OldFlags = CurScope->getFlags();
399 CurScope->setFlags(ScopeFlags);
400 }
401}
Chris Lattnere4e38592006-08-14 00:15:05 +0000402
Richard Smith938f40b2011-06-11 17:19:42 +0000403/// Restore the flags for the current scope to what they were before this
404/// object overrode them.
405Parser::ParseScopeFlags::~ParseScopeFlags() {
406 if (CurScope)
407 CurScope->setFlags(OldFlags);
408}
Chris Lattnere4e38592006-08-14 00:15:05 +0000409
410
411//===----------------------------------------------------------------------===//
Chris Lattner70f32b72006-07-31 05:09:04 +0000412// C99 6.9: External Definitions.
413//===----------------------------------------------------------------------===//
Chris Lattner0bb5f832006-07-31 01:59:18 +0000414
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000415Parser::~Parser() {
416 // If we still have scopes active, delete the scope tree.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000417 delete getCurScope();
418 Actions.CurScope = 0;
419
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000420 // Free the scope cache.
Chris Lattner03928c72007-07-15 00:04:39 +0000421 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
422 delete ScopeCache[i];
Daniel Dunbar921b9682008-10-04 19:21:03 +0000423
Francois Pichet1c229c02011-04-22 22:18:13 +0000424 // Free LateParsedTemplatedFunction nodes.
425 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
426 it != LateParsedTemplateMap.end(); ++it)
427 delete it->second;
428
Daniel Dunbar921b9682008-10-04 19:21:03 +0000429 // Remove the pragma handlers we installed.
Daniel Dunbarcb82acb2010-07-31 19:17:07 +0000430 PP.RemovePragmaHandler(AlignHandler.get());
431 AlignHandler.reset();
Eli Friedman570024a2010-08-05 06:57:20 +0000432 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
433 GCCVisibilityHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000434 PP.RemovePragmaHandler(OptionsHandler.get());
Daniel Dunbar75c9be72010-05-26 23:29:06 +0000435 OptionsHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000436 PP.RemovePragmaHandler(PackHandler.get());
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000437 PackHandler.reset();
Fariborz Jahanian743dda42011-04-25 18:49:15 +0000438 PP.RemovePragmaHandler(MSStructHandler.get());
439 MSStructHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000440 PP.RemovePragmaHandler(UnusedHandler.get());
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000441 UnusedHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000442 PP.RemovePragmaHandler(WeakHandler.get());
Eli Friedmanf5867dd2009-06-05 00:49:58 +0000443 WeakHandler.reset();
David Chisnall0867d9c2012-02-18 16:12:34 +0000444 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
445 RedefineExtnameHandler.reset();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000446
David Blaikiebbafb8a2012-03-11 07:00:24 +0000447 if (getLangOpts().OpenCL) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000448 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
449 OpenCLExtensionHandler.reset();
450 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
451 }
452
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000453 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
454 FPContractHandler.reset();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000455
Dmitri Gribenko17e147f2012-06-20 01:06:08 +0000456 PP.removeCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000457
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000458 PP.clearCodeCompletionHandler();
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000459
460 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000461}
462
Chris Lattner38ba3362006-08-17 07:04:37 +0000463/// Initialize - Warm up the parser.
464///
465void Parser::Initialize() {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000466 // Create the translation unit scope. Install it as the current scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000467 assert(getCurScope() == 0 && "A scope is already active?");
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000468 EnterScope(Scope::DeclScope);
Douglas Gregorf11096c2010-08-25 18:07:12 +0000469 Actions.ActOnTranslationUnitScope(getCurScope());
470
471 // Prime the lexer look-ahead.
472 ConsumeToken();
Mike Stump01e07652008-06-19 19:28:49 +0000473
Chris Lattner66782842007-08-29 22:54:08 +0000474 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000475 // Referenced in Parser::ParseObjCTypeQualifierList.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000476 if (getLangOpts().ObjC1) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000477 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
478 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
479 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
480 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
481 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
482 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner66782842007-08-29 22:54:08 +0000483 }
Daniel Dunbar12c9ddc2008-08-14 22:04:54 +0000484
Douglas Gregorbab8a962011-09-08 01:46:34 +0000485 Ident_instancetype = 0;
Anders Carlsson428803b2011-01-20 03:47:08 +0000486 Ident_final = 0;
487 Ident_override = 0;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +0000488
Daniel Dunbar12c9ddc2008-08-14 22:04:54 +0000489 Ident_super = &PP.getIdentifierTable().get("super");
John Thompson22334602010-02-05 00:12:22 +0000490
David Blaikiebbafb8a2012-03-11 07:00:24 +0000491 if (getLangOpts().AltiVec) {
John Thompson22334602010-02-05 00:12:22 +0000492 Ident_vector = &PP.getIdentifierTable().get("vector");
493 Ident_pixel = &PP.getIdentifierTable().get("pixel");
494 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000495
496 Ident_introduced = 0;
497 Ident_deprecated = 0;
498 Ident_obsoleted = 0;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000499 Ident_unavailable = 0;
John Wiegley1c0675e2011-04-28 01:08:34 +0000500
Douglas Gregor60060d62011-10-21 03:57:52 +0000501 Ident__except = 0;
502
John Wiegley1c0675e2011-04-28 01:08:34 +0000503 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
504 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
505 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
506
David Blaikiebbafb8a2012-03-11 07:00:24 +0000507 if(getLangOpts().Borland) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000508 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
509 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
510 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
511 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
512 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
513 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
514 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
515 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
516 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
517
518 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
519 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
520 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
521 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
522 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
523 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
524 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
525 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
526 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
527 }
Chris Lattner38ba3362006-08-17 07:04:37 +0000528}
529
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000530namespace {
531 /// \brief RAIIObject to destroy the contents of a SmallVector of
532 /// TemplateIdAnnotation pointers and clear the vector.
533 class DestroyTemplateIdAnnotationsRAIIObj {
534 SmallVectorImpl<TemplateIdAnnotation *> &Container;
535 public:
536 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
537 &Container)
538 : Container(Container) {}
539
540 ~DestroyTemplateIdAnnotationsRAIIObj() {
541 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
542 Container.begin(), E = Container.end();
543 I != E; ++I)
544 (*I)->Destroy();
545 Container.clear();
546 }
547 };
548}
549
Chris Lattner38ba3362006-08-17 07:04:37 +0000550/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
551/// action tells us to. This returns true if the EOF was encountered.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000552bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000553 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000554
Axel Naumann2eb1d902012-03-16 10:40:17 +0000555 // Skip over the EOF token, flagging end of previous input for incremental
556 // processing
557 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
558 ConsumeToken();
559
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000560 while (Tok.is(tok::annot_pragma_unused))
561 HandlePragmaUnused();
562
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000563 Result = DeclGroupPtrTy();
Chris Lattnerf4404402008-08-23 03:19:52 +0000564 if (Tok.is(tok::eof)) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000565 // Late template parsing can begin.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000566 if (getLangOpts().DelayedTemplateParsing)
Francois Pichet1c229c02011-04-22 22:18:13 +0000567 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
Axel Naumann2eb1d902012-03-16 10:40:17 +0000568 if (!PP.isIncrementalProcessingEnabled())
569 Actions.ActOnEndOfTranslationUnit();
570 //else don't tell Sema that we ended parsing: more input might come.
Francois Pichet1c229c02011-04-22 22:18:13 +0000571
Chris Lattnerf4404402008-08-23 03:19:52 +0000572 return true;
573 }
Mike Stump01e07652008-06-19 19:28:49 +0000574
John McCall084e83d2011-03-24 11:26:52 +0000575 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +0000576 MaybeParseCXX0XAttributes(attrs);
577 MaybeParseMicrosoftAttributes(attrs);
Axel Naumann2eb1d902012-03-16 10:40:17 +0000578
John McCall53fa7142010-12-24 02:08:15 +0000579 Result = ParseExternalDeclaration(attrs);
Chris Lattner38ba3362006-08-17 07:04:37 +0000580 return false;
581}
582
Chris Lattner38ba3362006-08-17 07:04:37 +0000583/// ParseTranslationUnit:
584/// translation-unit: [C99 6.9]
Mike Stump01e07652008-06-19 19:28:49 +0000585/// external-declaration
586/// translation-unit external-declaration
Chris Lattner38ba3362006-08-17 07:04:37 +0000587void Parser::ParseTranslationUnit() {
Douglas Gregor7307d6c2008-12-10 06:34:36 +0000588 Initialize();
Mike Stump01e07652008-06-19 19:28:49 +0000589
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000590 DeclGroupPtrTy Res;
Steve Naroff205ec3d2007-11-29 23:05:20 +0000591 while (!ParseTopLevelDecl(Res))
Chris Lattner38ba3362006-08-17 07:04:37 +0000592 /*parse them all*/;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattner2cc35ae2008-08-23 02:00:52 +0000594 ExitScope();
Douglas Gregor0be31a22010-07-02 17:43:08 +0000595 assert(getCurScope() == 0 && "Scope imbalance!");
Chris Lattner38ba3362006-08-17 07:04:37 +0000596}
597
Chris Lattner0bb5f832006-07-31 01:59:18 +0000598/// ParseExternalDeclaration:
Chris Lattner46415262008-12-08 21:59:01 +0000599///
Douglas Gregor15799fd2008-11-21 16:10:08 +0000600/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattnercccc3112007-08-10 20:57:02 +0000601/// function-definition
602/// declaration
Douglas Gregor8b9575f2009-08-24 12:17:54 +0000603/// [C++0x] empty-declaration
Chris Lattner6d7e6342006-08-15 03:41:14 +0000604/// [GNU] asm-definition
Chris Lattnercccc3112007-08-10 20:57:02 +0000605/// [GNU] __extension__ external-declaration
Chris Lattner40f16b52006-11-05 02:05:37 +0000606/// [OBJC] objc-class-definition
607/// [OBJC] objc-class-declaration
608/// [OBJC] objc-alias-declaration
609/// [OBJC] objc-protocol-definition
610/// [OBJC] objc-method-definition
611/// [OBJC] @end
Douglas Gregor15799fd2008-11-21 16:10:08 +0000612/// [C++] linkage-specification
Chris Lattner6d7e6342006-08-15 03:41:14 +0000613/// [GNU] asm-definition:
614/// simple-asm-expr ';'
615///
Douglas Gregor8b9575f2009-08-24 12:17:54 +0000616/// [C++0x] empty-declaration:
617/// ';'
618///
Douglas Gregor43e75172009-09-04 06:33:52 +0000619/// [C++0x/GNU] 'extern' 'template' declaration
John McCall53fa7142010-12-24 02:08:15 +0000620Parser::DeclGroupPtrTy
621Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
622 ParsingDeclSpec *DS) {
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000623 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000624 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000625
626 if (PP.isCodeCompletionReached()) {
627 cutOffParsing();
628 return DeclGroupPtrTy();
629 }
630
John McCall48871652010-08-21 09:40:31 +0000631 Decl *SingleDecl = 0;
Chris Lattner0bb5f832006-07-31 01:59:18 +0000632 switch (Tok.getKind()) {
Rafael Espindola273fd772012-01-26 02:02:57 +0000633 case tok::annot_pragma_vis:
634 HandlePragmaVisibility();
635 return DeclGroupPtrTy();
Eli Friedmanec52f922012-02-23 23:47:16 +0000636 case tok::annot_pragma_pack:
637 HandlePragmaPack();
638 return DeclGroupPtrTy();
Eli Friedman68be1642012-10-04 02:36:51 +0000639 case tok::annot_pragma_msstruct:
640 HandlePragmaMSStruct();
641 return DeclGroupPtrTy();
642 case tok::annot_pragma_align:
643 HandlePragmaAlign();
644 return DeclGroupPtrTy();
645 case tok::annot_pragma_weak:
646 HandlePragmaWeak();
647 return DeclGroupPtrTy();
648 case tok::annot_pragma_weakalias:
649 HandlePragmaWeakAlias();
650 return DeclGroupPtrTy();
651 case tok::annot_pragma_redefine_extname:
652 HandlePragmaRedefineExtname();
653 return DeclGroupPtrTy();
654 case tok::annot_pragma_fp_contract:
655 HandlePragmaFPContract();
656 return DeclGroupPtrTy();
657 case tok::annot_pragma_opencl_extension:
658 HandlePragmaOpenCLExtension();
659 return DeclGroupPtrTy();
Chris Lattner0bb5f832006-07-31 01:59:18 +0000660 case tok::semi:
Richard Trieu2f7dc462012-05-16 19:04:59 +0000661 ConsumeExtraSemi(OutsideFunction);
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000662 // TODO: Invoke action for top-level semicolon.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000663 return DeclGroupPtrTy();
Chris Lattner46415262008-12-08 21:59:01 +0000664 case tok::r_brace:
Nico Webere1df10a2012-01-17 01:04:27 +0000665 Diag(Tok, diag::err_extraneous_closing_brace);
Chris Lattner46415262008-12-08 21:59:01 +0000666 ConsumeBrace();
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000667 return DeclGroupPtrTy();
Chris Lattner46415262008-12-08 21:59:01 +0000668 case tok::eof:
669 Diag(Tok, diag::err_expected_external_declaration);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000670 return DeclGroupPtrTy();
Chris Lattnercccc3112007-08-10 20:57:02 +0000671 case tok::kw___extension__: {
Chris Lattnerf02ef3e2008-10-20 06:45:43 +0000672 // __extension__ silences extension warnings in the subexpression.
673 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner1ff6e732008-10-20 06:51:33 +0000674 ConsumeToken();
John McCall53fa7142010-12-24 02:08:15 +0000675 return ParseExternalDeclaration(attrs);
Chris Lattnercccc3112007-08-10 20:57:02 +0000676 }
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000677 case tok::kw_asm: {
John McCall53fa7142010-12-24 02:08:15 +0000678 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000679
Abramo Bagnara348823a2011-03-03 14:20:18 +0000680 SourceLocation StartLoc = Tok.getLocation();
681 SourceLocation EndLoc;
682 ExprResult Result(ParseSimpleAsm(&EndLoc));
Mike Stump01e07652008-06-19 19:28:49 +0000683
Anders Carlsson0fae4f52008-02-08 00:23:11 +0000684 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
685 "top-level asm block");
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000686
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000687 if (Result.isInvalid())
688 return DeclGroupPtrTy();
Abramo Bagnara348823a2011-03-03 14:20:18 +0000689 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000690 break;
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000691 }
Steve Naroffb419d3a2006-10-27 23:18:49 +0000692 case tok::at:
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000693 return ParseObjCAtDirectives();
Steve Naroffb419d3a2006-10-27 23:18:49 +0000694 case tok::minus:
Steve Naroffb419d3a2006-10-27 23:18:49 +0000695 case tok::plus:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000696 if (!getLangOpts().ObjC1) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000697 Diag(Tok, diag::err_expected_external_declaration);
698 ConsumeToken();
699 return DeclGroupPtrTy();
700 }
701 SingleDecl = ParseObjCMethodDefinition();
702 break;
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000703 case tok::code_completion:
Douglas Gregor0be31a22010-07-02 17:43:08 +0000704 Actions.CodeCompleteOrdinaryName(getCurScope(),
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +0000705 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
John McCallfaf5fb42010-08-26 23:41:50 +0000706 : Sema::PCC_Namespace);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000707 cutOffParsing();
708 return DeclGroupPtrTy();
Douglas Gregord7c4d982008-12-30 03:27:21 +0000709 case tok::kw_using:
Chris Lattnera5235172007-08-25 06:57:03 +0000710 case tok::kw_namespace:
Chris Lattner302b4be2006-11-19 02:31:38 +0000711 case tok::kw_typedef:
Douglas Gregoreb31f392008-12-01 23:54:00 +0000712 case tok::kw_template:
713 case tok::kw_export: // As in 'export template'
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000714 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000715 case tok::kw__Static_assert:
Chad Rosiere38c0062012-04-25 22:51:41 +0000716 // A function definition cannot start with any of these keywords.
Chris Lattner49836b42009-04-02 04:16:50 +0000717 {
718 SourceLocation DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +0000719 StmtVector Stmts;
John McCall53fa7142010-12-24 02:08:15 +0000720 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000721 }
Sebastian Redl67667942010-08-27 23:12:46 +0000722
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000723 case tok::kw_static:
724 // Parse (then ignore) 'static' prior to a template instantiation. This is
725 // a GCC extension that we intentionally do not support.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000727 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
728 << 0;
Sebastian Redl67667942010-08-27 23:12:46 +0000729 SourceLocation DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +0000730 StmtVector Stmts;
John McCall53fa7142010-12-24 02:08:15 +0000731 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000732 }
733 goto dont_know;
734
735 case tok::kw_inline:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000736 if (getLangOpts().CPlusPlus) {
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000737 tok::TokenKind NextKind = NextToken().getKind();
738
739 // Inline namespaces. Allowed as an extension even in C++03.
740 if (NextKind == tok::kw_namespace) {
741 SourceLocation DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +0000742 StmtVector Stmts;
John McCall53fa7142010-12-24 02:08:15 +0000743 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000744 }
745
746 // Parse (then ignore) 'inline' prior to a template instantiation. This is
747 // a GCC extension that we intentionally do not support.
748 if (NextKind == tok::kw_template) {
749 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
750 << 1;
751 SourceLocation DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +0000752 StmtVector Stmts;
John McCall53fa7142010-12-24 02:08:15 +0000753 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000754 }
Sebastian Redl67667942010-08-27 23:12:46 +0000755 }
756 goto dont_know;
757
Douglas Gregor43e75172009-09-04 06:33:52 +0000758 case tok::kw_extern:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000759 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor43e75172009-09-04 06:33:52 +0000760 // Extern templates
761 SourceLocation ExternLoc = ConsumeToken();
762 SourceLocation TemplateLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000763 Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
Richard Smithf4111962011-10-20 18:35:58 +0000764 diag::warn_cxx98_compat_extern_template :
765 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
Douglas Gregor43e75172009-09-04 06:33:52 +0000766 SourceLocation DeclEnd;
767 return Actions.ConvertDeclToDeclGroup(
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +0000768 ParseExplicitInstantiation(Declarator::FileContext,
769 ExternLoc, TemplateLoc, DeclEnd));
Douglas Gregor43e75172009-09-04 06:33:52 +0000770 }
Douglas Gregor43e75172009-09-04 06:33:52 +0000771 // FIXME: Detect C++ linkage specifications here?
Sebastian Redl67667942010-08-27 23:12:46 +0000772 goto dont_know;
Mike Stump11289f42009-09-09 15:08:12 +0000773
Francois Picheta5b3fcb2011-05-07 17:30:27 +0000774 case tok::kw___if_exists:
775 case tok::kw___if_not_exists:
Francois Pichet8f981d52011-05-25 10:19:49 +0000776 ParseMicrosoftIfExistsExternalDeclaration();
Francois Picheta5b3fcb2011-05-07 17:30:27 +0000777 return DeclGroupPtrTy();
Douglas Gregor08142532011-08-26 23:56:07 +0000778
Chris Lattner0bb5f832006-07-31 01:59:18 +0000779 default:
Sebastian Redl67667942010-08-27 23:12:46 +0000780 dont_know:
Chris Lattner0bb5f832006-07-31 01:59:18 +0000781 // We can't tell whether this is a function-definition or declaration yet.
John McCall53fa7142010-12-24 02:08:15 +0000782 if (DS) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000783 return ParseDeclarationOrFunctionDefinition(attrs, DS);
John McCall53fa7142010-12-24 02:08:15 +0000784 } else {
785 return ParseDeclarationOrFunctionDefinition(attrs);
786 }
Chris Lattner0bb5f832006-07-31 01:59:18 +0000787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000789 // This routine returns a DeclGroup, if the thing we parsed only contains a
790 // single decl, convert it now.
791 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000792}
793
Douglas Gregor23996282009-05-12 21:31:51 +0000794/// \brief Determine whether the current token, if it occurs after a
795/// declarator, continues a declaration or declaration list.
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000796bool Parser::isDeclarationAfterDeclarator() {
797 // Check for '= delete' or '= default'
David Blaikiebbafb8a2012-03-11 07:00:24 +0000798 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000799 const Token &KW = NextToken();
800 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
801 return false;
802 }
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000803
Douglas Gregor23996282009-05-12 21:31:51 +0000804 return Tok.is(tok::equal) || // int X()= -> not a function def
805 Tok.is(tok::comma) || // int X(), -> not a function def
806 Tok.is(tok::semi) || // int X(); -> not a function def
807 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
808 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
David Blaikiebbafb8a2012-03-11 07:00:24 +0000809 (getLangOpts().CPlusPlus &&
Fariborz Jahanian8de79552012-07-05 19:34:20 +0000810 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
Douglas Gregor23996282009-05-12 21:31:51 +0000811}
812
813/// \brief Determine whether the current token, if it occurs after a
814/// declarator, indicates the start of a function definition.
Chris Lattner13901342010-07-11 22:42:07 +0000815bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000816 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
Chris Lattner8c56c492009-12-06 18:34:27 +0000817 if (Tok.is(tok::l_brace)) // int X() {}
818 return true;
819
Chris Lattner13901342010-07-11 22:42:07 +0000820 // Handle K&R C argument lists: int X(f) int f; {}
David Blaikiebbafb8a2012-03-11 07:00:24 +0000821 if (!getLangOpts().CPlusPlus &&
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000822 Declarator.getFunctionTypeInfo().isKNRPrototype())
Chris Lattner13901342010-07-11 22:42:07 +0000823 return isDeclarationSpecifier();
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000824
David Blaikiebbafb8a2012-03-11 07:00:24 +0000825 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000826 const Token &KW = NextToken();
827 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
828 }
Chris Lattner13901342010-07-11 22:42:07 +0000829
Chris Lattner8c56c492009-12-06 18:34:27 +0000830 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
831 Tok.is(tok::kw_try); // X() try { ... }
Douglas Gregor23996282009-05-12 21:31:51 +0000832}
833
Chris Lattner0bb5f832006-07-31 01:59:18 +0000834/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
Chris Lattner70f32b72006-07-31 05:09:04 +0000835/// a declaration. We can't tell which we have until we read up to the
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000836/// compound-statement in function-definition. TemplateParams, if
837/// non-NULL, provides the template parameters when we're parsing a
Mike Stump11289f42009-09-09 15:08:12 +0000838/// C++ template-declaration.
Chris Lattner0bb5f832006-07-31 01:59:18 +0000839///
Chris Lattner70f32b72006-07-31 05:09:04 +0000840/// function-definition: [C99 6.9.1]
Chris Lattner94fc8062008-04-05 05:52:15 +0000841/// decl-specs declarator declaration-list[opt] compound-statement
842/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stump01e07652008-06-19 19:28:49 +0000843/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattner94fc8062008-04-05 05:52:15 +0000844///
Chris Lattner70f32b72006-07-31 05:09:04 +0000845/// declaration: [C99 6.7]
Chris Lattnerf2659392007-08-22 06:06:56 +0000846/// declaration-specifiers init-declarator-list[opt] ';'
847/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Chris Lattner70f32b72006-07-31 05:09:04 +0000848/// [OMP] threadprivate-directive [TODO]
849///
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000850Parser::DeclGroupPtrTy
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000851Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
852 ParsingDeclSpec &DS,
853 AccessSpecifier AS) {
Chris Lattner70f32b72006-07-31 05:09:04 +0000854 // Parse the common declaration-specifiers piece.
Douglas Gregor9de54ea2010-01-13 17:31:36 +0000855 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
Mike Stump01e07652008-06-19 19:28:49 +0000856
Chris Lattnerd2864882006-08-05 08:09:44 +0000857 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
Chris Lattner53361ac2006-08-10 05:19:57 +0000858 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner0ab032a2007-10-09 17:23:58 +0000859 if (Tok.is(tok::semi)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000860 ProhibitAttributes(attrs);
Chris Lattner0e894622006-08-13 19:58:17 +0000861 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000862 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall28a6aea2009-11-04 02:18:39 +0000863 DS.complete(TheDecl);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000864 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +0000865 }
Mike Stump01e07652008-06-19 19:28:49 +0000866
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000867 DS.takeAttributesFrom(attrs);
868
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000869 // ObjC2 allows prefix attributes on class interfaces and protocols.
870 // FIXME: This still needs better diagnostics. We should only accept
871 // attributes here, no types, etc.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
Steve Naroff1eb1ad62007-08-20 21:31:48 +0000873 SourceLocation AtLoc = ConsumeToken(); // the "@"
Mike Stump11289f42009-09-09 15:08:12 +0000874 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000875 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
876 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattner5e530bc2007-12-27 19:57:00 +0000877 SkipUntil(tok::semi); // FIXME: better skip?
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000878 return DeclGroupPtrTy();
Chris Lattner5e530bc2007-12-27 19:57:00 +0000879 }
John McCalld5a36322009-11-03 19:26:08 +0000880
John McCall28a6aea2009-11-04 02:18:39 +0000881 DS.abort();
882
Fariborz Jahanian056e3a42008-01-02 19:17:38 +0000883 const char *PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +0000884 unsigned DiagID;
885 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
886 Diag(AtLoc, DiagID) << PrevSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000888 if (Tok.isObjCAtKeyword(tok::objc_protocol))
Douglas Gregorf6102672012-01-01 21:23:57 +0000889 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
890
891 return Actions.ConvertDeclToDeclGroup(
892 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
Steve Naroff1eb1ad62007-08-20 21:31:48 +0000893 }
Mike Stump01e07652008-06-19 19:28:49 +0000894
Chris Lattner38376f12008-01-12 07:05:38 +0000895 // If the declspec consisted only of 'extern' and we have a string
896 // literal following it, this must be a C++ linkage specifier like
897 // 'extern "C"'.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000898 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
Chris Lattner38376f12008-01-12 07:05:38 +0000899 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000900 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
John McCall48871652010-08-21 09:40:31 +0000901 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000902 return Actions.ConvertDeclToDeclGroup(TheDecl);
903 }
Chris Lattner38376f12008-01-12 07:05:38 +0000904
John McCalld5a36322009-11-03 19:26:08 +0000905 return ParseDeclGroup(DS, Declarator::FileContext, true);
Chris Lattner70f32b72006-07-31 05:09:04 +0000906}
907
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000908Parser::DeclGroupPtrTy
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000909Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
910 ParsingDeclSpec *DS,
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000911 AccessSpecifier AS) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000912 if (DS) {
913 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
914 } else {
915 ParsingDeclSpec PDS(*this);
916 // Must temporarily exit the objective-c container scope for
917 // parsing c constructs and re-enter objc container scope
918 // afterwards.
919 ObjCDeclContextSwitch ObjCDC(*this);
920
921 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
922 }
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000923}
924
Chris Lattnerfff824f2006-08-07 06:31:38 +0000925/// ParseFunctionDefinition - We parsed and verified that the specified
926/// Declarator is well formed. If this is a K&R-style function, read the
927/// parameters declaration-list, then start the compound-statement.
928///
Chris Lattner94fc8062008-04-05 05:52:15 +0000929/// function-definition: [C99 6.9.1]
930/// decl-specs declarator declaration-list[opt] compound-statement
931/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stump01e07652008-06-19 19:28:49 +0000932/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregore8381c02008-11-05 04:29:56 +0000933/// [C++] function-definition: [C++ 8.4]
Chris Lattnerefb0f112009-03-29 17:18:04 +0000934/// decl-specifier-seq[opt] declarator ctor-initializer[opt]
935/// function-body
Douglas Gregore8381c02008-11-05 04:29:56 +0000936/// [C++] function-definition: [C++ 8.4]
Sebastian Redla7b98a72009-04-26 20:35:05 +0000937/// decl-specifier-seq[opt] declarator function-try-block
Chris Lattnerfff824f2006-08-07 06:31:38 +0000938///
John McCall48871652010-08-21 09:40:31 +0000939Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000940 const ParsedTemplateInfo &TemplateInfo,
941 LateParsedAttrList *LateParsedAttrs) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000942 // Poison the SEH identifiers so they are flagged as illegal in function bodies
943 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000944 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump01e07652008-06-19 19:28:49 +0000945
Chris Lattner94fc8062008-04-05 05:52:15 +0000946 // If this is C90 and the declspecs were completely missing, fudge in an
947 // implicit int. We do this here because this is the only place where
948 // declaration-specifiers are completely optional in the grammar.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000949 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
Chris Lattner94fc8062008-04-05 05:52:15 +0000950 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +0000951 unsigned DiagID;
Chris Lattnerfcc390a2008-10-20 02:01:34 +0000952 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
953 D.getIdentifierLoc(),
John McCall49bfce42009-08-03 20:12:06 +0000954 PrevSpec, DiagID);
Sebastian Redlf6591ca2009-02-09 18:23:29 +0000955 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattner94fc8062008-04-05 05:52:15 +0000956 }
Mike Stump01e07652008-06-19 19:28:49 +0000957
Chris Lattnerfff824f2006-08-07 06:31:38 +0000958 // If this declaration was formed with a K&R-style identifier list for the
959 // arguments, parse declarations for all of the args next.
960 // int foo(a,b) int a; float b; {}
Chris Lattner13901342010-07-11 22:42:07 +0000961 if (FTI.isKNRPrototype())
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000962 ParseKNRParamDeclarations(D);
Chris Lattnerfff824f2006-08-07 06:31:38 +0000963
Douglas Gregore8381c02008-11-05 04:29:56 +0000964 // We should have either an opening brace or, in a C++ constructor,
965 // we may have a colon.
Douglas Gregor0fcaac92011-02-04 11:57:16 +0000966 if (Tok.isNot(tok::l_brace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000967 (!getLangOpts().CPlusPlus ||
Alexis Hunt61ae8d32011-05-23 23:14:04 +0000968 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
969 Tok.isNot(tok::equal)))) {
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000970 Diag(Tok, diag::err_expected_fn_body);
971
972 // Skip over garbage, until we get to '{'. Don't eat the '{'.
973 SkipUntil(tok::l_brace, true, true);
Mike Stump01e07652008-06-19 19:28:49 +0000974
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000975 // If we didn't find the '{', bail out.
Chris Lattner0ab032a2007-10-09 17:23:58 +0000976 if (Tok.isNot(tok::l_brace))
John McCall48871652010-08-21 09:40:31 +0000977 return 0;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000978 }
Mike Stump01e07652008-06-19 19:28:49 +0000979
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000980 // Check to make sure that any normal attributes are allowed to be on
981 // a definition. Late parsed attributes are checked at the end.
982 if (Tok.isNot(tok::equal)) {
983 AttributeList *DtorAttrs = D.getAttributes();
984 while (DtorAttrs) {
985 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
986 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
987 << DtorAttrs->getName()->getName();
988 }
989 DtorAttrs = DtorAttrs->getNext();
990 }
991 }
992
Francois Pichet1c229c02011-04-22 22:18:13 +0000993 // In delayed template parsing mode, for function template we consume the
994 // tokens and store them for late parsing at the end of the translation unit.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000995 if (getLangOpts().DelayedTemplateParsing &&
Douglas Gregor1edf5762012-06-28 21:43:01 +0000996 Tok.isNot(tok::equal) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000997 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000998 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
Francois Pichet1c229c02011-04-22 22:18:13 +0000999
1000 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1001 Scope *ParentScope = getCurScope()->getParent();
1002
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00001003 D.setFunctionDefinitionKind(FDK_Definition);
Francois Pichet1c229c02011-04-22 22:18:13 +00001004 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001005 TemplateParameterLists);
Francois Pichet1c229c02011-04-22 22:18:13 +00001006 D.complete(DP);
1007 D.getMutableDeclSpec().abort();
1008
1009 if (DP) {
Francois Pichet33786cb2011-12-08 09:11:52 +00001010 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
Francois Pichet1c229c02011-04-22 22:18:13 +00001011
1012 FunctionDecl *FnD = 0;
1013 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1014 FnD = FunTmpl->getTemplatedDecl();
1015 else
1016 FnD = cast<FunctionDecl>(DP);
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00001017 Actions.CheckForFunctionRedefinition(FnD);
Francois Pichet1c229c02011-04-22 22:18:13 +00001018
1019 LateParsedTemplateMap[FnD] = LPT;
1020 Actions.MarkAsLateParsedTemplate(FnD);
1021 LexTemplateFunctionForLateParsing(LPT->Toks);
1022 } else {
1023 CachedTokens Toks;
1024 LexTemplateFunctionForLateParsing(Toks);
1025 }
1026 return DP;
1027 }
Fariborz Jahanian8cecfe92012-08-10 18:10:56 +00001028 else if (CurParsedObjCImpl &&
Fariborz Jahanianf64b4722012-08-10 21:15:06 +00001029 !TemplateInfo.TemplateParams &&
1030 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1031 Tok.is(tok::colon)) &&
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001032 Actions.CurContext->isTranslationUnit()) {
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001033 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1034 Scope *ParentScope = getCurScope()->getParent();
1035
1036 D.setFunctionDefinitionKind(FDK_Definition);
1037 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001038 MultiTemplateParamsArg());
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001039 D.complete(FuncDecl);
1040 D.getMutableDeclSpec().abort();
1041 if (FuncDecl) {
1042 // Consume the tokens and store them for later parsing.
1043 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1044 CurParsedObjCImpl->HasCFunction = true;
1045 return FuncDecl;
1046 }
1047 }
1048
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001049 // Enter a scope for the function body.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001050 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stump01e07652008-06-19 19:28:49 +00001051
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001052 // Tell the actions module that we have entered a function definition with the
1053 // specified Declarator for the function.
John McCall48871652010-08-21 09:40:31 +00001054 Decl *Res = TemplateInfo.TemplateParams?
Douglas Gregor0be31a22010-07-02 17:43:08 +00001055 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001056 *TemplateInfo.TemplateParams, D)
Douglas Gregor0be31a22010-07-02 17:43:08 +00001057 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
Mike Stump01e07652008-06-19 19:28:49 +00001058
John McCall28a6aea2009-11-04 02:18:39 +00001059 // Break out of the ParsingDeclarator context before we parse the body.
1060 D.complete(Res);
1061
1062 // Break out of the ParsingDeclSpec context, too. This const_cast is
1063 // safe because we're always the sole owner.
1064 D.getMutableDeclSpec().abort();
1065
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001066 if (Tok.is(tok::equal)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001067 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001068 ConsumeToken();
1069
1070 Actions.ActOnFinishFunctionBody(Res, 0, false);
1071
1072 bool Delete = false;
1073 SourceLocation KWLoc;
1074 if (Tok.is(tok::kw_delete)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001075 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001076 diag::warn_cxx98_compat_deleted_function :
Richard Smithe4345902011-12-29 21:57:33 +00001077 diag::ext_deleted_function);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001078
1079 KWLoc = ConsumeToken();
1080 Actions.SetDeclDeleted(Res, KWLoc);
1081 Delete = true;
1082 } else if (Tok.is(tok::kw_default)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001083 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001084 diag::warn_cxx98_compat_defaulted_function :
Richard Smithe4345902011-12-29 21:57:33 +00001085 diag::ext_defaulted_function);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001086
1087 KWLoc = ConsumeToken();
1088 Actions.SetDeclDefaulted(Res, KWLoc);
1089 } else {
1090 llvm_unreachable("function definition after = not 'delete' or 'default'");
1091 }
1092
1093 if (Tok.is(tok::comma)) {
1094 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1095 << Delete;
1096 SkipUntil(tok::semi);
1097 } else {
1098 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1099 Delete ? "delete" : "default", tok::semi);
1100 }
1101
1102 return Res;
1103 }
1104
Sebastian Redla7b98a72009-04-26 20:35:05 +00001105 if (Tok.is(tok::kw_try))
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001106 return ParseFunctionTryBlock(Res, BodyScope);
Sebastian Redla7b98a72009-04-26 20:35:05 +00001107
Douglas Gregore8381c02008-11-05 04:29:56 +00001108 // If we have a colon, then we're probably parsing a C++
1109 // ctor-initializer.
John McCallbb7b6582010-04-10 07:37:23 +00001110 if (Tok.is(tok::colon)) {
Douglas Gregore8381c02008-11-05 04:29:56 +00001111 ParseConstructorInitializer(Res);
John McCallbb7b6582010-04-10 07:37:23 +00001112
1113 // Recover from error.
1114 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001115 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00001116 Actions.ActOnFinishFunctionBody(Res, 0);
John McCallbb7b6582010-04-10 07:37:23 +00001117 return Res;
1118 }
1119 } else
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001120 Actions.ActOnDefaultCtorInitializers(Res);
Douglas Gregore8381c02008-11-05 04:29:56 +00001121
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001122 // Late attributes are parsed in the same scope as the function body.
1123 if (LateParsedAttrs)
1124 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1125
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001126 return ParseFunctionStatementBody(Res, BodyScope);
Chris Lattnerfff824f2006-08-07 06:31:38 +00001127}
1128
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001129/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1130/// types for a function with a K&R-style identifier list for arguments.
1131void Parser::ParseKNRParamDeclarations(Declarator &D) {
1132 // We know that the top-level of this declarator is a function.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001133 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001134
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001135 // Enter function-declaration scope, limiting any declarators to the
1136 // function prototype scope, including parameter declarators.
Douglas Gregor658b9552009-01-09 22:42:13 +00001137 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001138
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001139 // Read all the argument declarations.
1140 while (isDeclarationSpecifier()) {
1141 SourceLocation DSStart = Tok.getLocation();
Mike Stump01e07652008-06-19 19:28:49 +00001142
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001143 // Parse the common declaration-specifiers piece.
John McCall084e83d2011-03-24 11:26:52 +00001144 DeclSpec DS(AttrFactory);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001145 ParseDeclarationSpecifiers(DS);
Mike Stump01e07652008-06-19 19:28:49 +00001146
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001147 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1148 // least one declarator'.
1149 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1150 // the declarations though. It's trivial to ignore them, really hard to do
1151 // anything else with them.
Chris Lattner0ab032a2007-10-09 17:23:58 +00001152 if (Tok.is(tok::semi)) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001153 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1154 ConsumeToken();
1155 continue;
1156 }
Mike Stump01e07652008-06-19 19:28:49 +00001157
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001158 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1159 // than register.
1160 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1161 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1162 Diag(DS.getStorageClassSpecLoc(),
1163 diag::err_invalid_storage_class_in_func_decl);
1164 DS.ClearStorageClassSpecs();
1165 }
1166 if (DS.isThreadSpecified()) {
1167 Diag(DS.getThreadSpecLoc(),
1168 diag::err_invalid_storage_class_in_func_decl);
1169 DS.ClearStorageClassSpecs();
1170 }
Mike Stump01e07652008-06-19 19:28:49 +00001171
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001172 // Parse the first declarator attached to this declspec.
1173 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1174 ParseDeclarator(ParmDeclarator);
1175
1176 // Handle the full declarator list.
1177 while (1) {
1178 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001179 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump01e07652008-06-19 19:28:49 +00001180
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001181 // Ask the actions module to compute the type for this declarator.
John McCall48871652010-08-21 09:40:31 +00001182 Decl *Param =
Douglas Gregor0be31a22010-07-02 17:43:08 +00001183 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Steve Naroffacb1e742007-09-10 20:51:04 +00001184
Mike Stump01e07652008-06-19 19:28:49 +00001185 if (Param &&
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001186 // A missing identifier has already been diagnosed.
1187 ParmDeclarator.getIdentifier()) {
1188
1189 // Scan the argument list looking for the correct param to apply this
1190 // type.
1191 for (unsigned i = 0; ; ++i) {
1192 // C99 6.9.1p6: those declarators shall declare only identifiers from
1193 // the identifier list.
1194 if (i == FTI.NumArgs) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001195 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattner760d19ad2008-11-19 07:51:13 +00001196 << ParmDeclarator.getIdentifier();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001197 break;
1198 }
Mike Stump01e07652008-06-19 19:28:49 +00001199
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001200 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1201 // Reject redefinitions of parameters.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001202 if (FTI.ArgInfo[i].Param) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001203 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00001204 diag::err_param_redefinition)
Chris Lattner760d19ad2008-11-19 07:51:13 +00001205 << ParmDeclarator.getIdentifier();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001206 } else {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001207 FTI.ArgInfo[i].Param = Param;
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001208 }
1209 break;
1210 }
1211 }
1212 }
1213
1214 // If we don't have a comma, it is either the end of the list (a ';') or
1215 // an error, bail out.
Chris Lattner0ab032a2007-10-09 17:23:58 +00001216 if (Tok.isNot(tok::comma))
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001217 break;
Mike Stump01e07652008-06-19 19:28:49 +00001218
Richard Smith8d06f422012-01-12 23:53:29 +00001219 ParmDeclarator.clear();
1220
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001221 // Consume the comma.
Richard Smith8d06f422012-01-12 23:53:29 +00001222 ParmDeclarator.setCommaLoc(ConsumeToken());
Mike Stump01e07652008-06-19 19:28:49 +00001223
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001224 // Parse the next declarator.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001225 ParseDeclarator(ParmDeclarator);
1226 }
Mike Stump01e07652008-06-19 19:28:49 +00001227
Chris Lattner02f1b612012-04-28 16:12:17 +00001228 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001229 // Skip to end of block or statement
1230 SkipUntil(tok::semi, true);
Chris Lattner0ab032a2007-10-09 17:23:58 +00001231 if (Tok.is(tok::semi))
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001232 ConsumeToken();
1233 }
1234 }
Mike Stump01e07652008-06-19 19:28:49 +00001235
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001236 // The actions module must verify that all arguments were declared.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001237 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001238}
1239
1240
Chris Lattner0116c472006-08-15 06:03:28 +00001241/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1242/// allowed to be a wide string, and is not subject to character translation.
1243///
1244/// [GNU] asm-string-literal:
1245/// string-literal
1246///
John McCalldadc5752010-08-24 06:29:42 +00001247Parser::ExprResult Parser::ParseAsmStringLiteral() {
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001248 switch (Tok.getKind()) {
1249 case tok::string_literal:
1250 break;
Richard Smithd67aea22012-03-06 03:21:47 +00001251 case tok::utf8_string_literal:
1252 case tok::utf16_string_literal:
1253 case tok::utf32_string_literal:
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001254 case tok::wide_string_literal: {
1255 SourceLocation L = Tok.getLocation();
1256 Diag(Tok, diag::err_asm_operand_wide_string_literal)
Richard Smithd67aea22012-03-06 03:21:47 +00001257 << (Tok.getKind() == tok::wide_string_literal)
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001258 << SourceRange(L, L);
1259 return ExprError();
1260 }
1261 default:
1262 Diag(Tok, diag::err_expected_string_literal);
1263 return ExprError();
Chris Lattner0116c472006-08-15 06:03:28 +00001264 }
Mike Stump01e07652008-06-19 19:28:49 +00001265
Richard Smithd67aea22012-03-06 03:21:47 +00001266 return ParseStringLiteralExpression();
Chris Lattner0116c472006-08-15 06:03:28 +00001267}
1268
Chris Lattner6d7e6342006-08-15 03:41:14 +00001269/// ParseSimpleAsm
1270///
1271/// [GNU] simple-asm-expr:
1272/// 'asm' '(' asm-string-literal ')'
Chris Lattner6d7e6342006-08-15 03:41:14 +00001273///
John McCalldadc5752010-08-24 06:29:42 +00001274Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner0ab032a2007-10-09 17:23:58 +00001275 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlsson5c6c0592008-02-08 00:33:21 +00001276 SourceLocation Loc = ConsumeToken();
Mike Stump01e07652008-06-19 19:28:49 +00001277
John McCall9dfb1622010-01-25 22:27:48 +00001278 if (Tok.is(tok::kw_volatile)) {
John McCall5cb52872010-01-25 23:12:50 +00001279 // Remove from the end of 'asm' to the end of 'volatile'.
1280 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1281 PP.getLocForEndOfToken(Tok.getLocation()));
1282
1283 Diag(Tok, diag::warn_file_asm_volatile)
Douglas Gregora771f462010-03-31 17:46:05 +00001284 << FixItHint::CreateRemoval(RemovalRange);
John McCall9dfb1622010-01-25 22:27:48 +00001285 ConsumeToken();
1286 }
1287
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001288 BalancedDelimiterTracker T(*this, tok::l_paren);
1289 if (T.consumeOpen()) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001290 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl042ad952008-12-11 19:30:53 +00001291 return ExprError();
Chris Lattner6d7e6342006-08-15 03:41:14 +00001292 }
Mike Stump01e07652008-06-19 19:28:49 +00001293
John McCalldadc5752010-08-24 06:29:42 +00001294 ExprResult Result(ParseAsmStringLiteral());
Mike Stump01e07652008-06-19 19:28:49 +00001295
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001296 if (Result.isInvalid()) {
1297 SkipUntil(tok::r_paren, true, true);
1298 if (EndLoc)
1299 *EndLoc = Tok.getLocation();
1300 ConsumeAnyToken();
1301 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001302 // Close the paren and get the location of the end bracket
1303 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001304 if (EndLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001305 *EndLoc = T.getCloseLocation();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001306 }
Mike Stump01e07652008-06-19 19:28:49 +00001307
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001308 return Result;
Chris Lattner6d7e6342006-08-15 03:41:14 +00001309}
Steve Naroffb419d3a2006-10-27 23:18:49 +00001310
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001311/// \brief Get the TemplateIdAnnotation from the token and put it in the
1312/// cleanup pool so that it gets destroyed when parsing the current top level
1313/// declaration is finished.
1314TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1315 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1316 TemplateIdAnnotation *
1317 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001318 return Id;
1319}
1320
Richard Smith4f605af2012-08-18 00:55:03 +00001321void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1322 // Push the current token back into the token stream (or revert it if it is
1323 // cached) and use an annotation scope token for current token.
1324 if (PP.isBacktrackEnabled())
1325 PP.RevertCachedTokens(1);
1326 else
1327 PP.EnterToken(Tok);
1328 Tok.setKind(tok::annot_cxxscope);
1329 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1330 Tok.setAnnotationRange(SS.getRange());
1331
1332 // In case the tokens were cached, have Preprocessor replace them
1333 // with the annotation token. We don't need to do this if we've
1334 // just reverted back to a prior state.
1335 if (IsNewAnnotation)
1336 PP.AnnotateCachedTokens(Tok);
1337}
1338
1339/// \brief Attempt to classify the name at the current token position. This may
1340/// form a type, scope or primary expression annotation, or replace the token
1341/// with a typo-corrected keyword. This is only appropriate when the current
1342/// name must refer to an entity which has already been declared.
1343///
1344/// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1345/// and might possibly have a dependent nested name specifier.
1346/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1347/// no typo correction will be performed.
1348Parser::AnnotatedNameKind
1349Parser::TryAnnotateName(bool IsAddressOfOperand,
1350 CorrectionCandidateCallback *CCC) {
1351 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1352
1353 const bool EnteringContext = false;
1354 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1355
1356 CXXScopeSpec SS;
1357 if (getLangOpts().CPlusPlus &&
1358 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1359 return ANK_Error;
1360
1361 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1362 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1363 !WasScopeAnnotation))
1364 return ANK_Error;
1365 return ANK_Unresolved;
1366 }
1367
1368 IdentifierInfo *Name = Tok.getIdentifierInfo();
1369 SourceLocation NameLoc = Tok.getLocation();
1370
1371 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1372 // typo-correct to tentatively-declared identifiers.
1373 if (isTentativelyDeclared(Name)) {
1374 // Identifier has been tentatively declared, and thus cannot be resolved as
1375 // an expression. Fall back to annotating it as a type.
1376 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1377 !WasScopeAnnotation))
1378 return ANK_Error;
1379 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1380 }
1381
1382 Token Next = NextToken();
1383
1384 // Look up and classify the identifier. We don't perform any typo-correction
1385 // after a scope specifier, because in general we can't recover from typos
1386 // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1387 // back into scope specifier parsing).
1388 Sema::NameClassification Classification
1389 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1390 IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1391
1392 switch (Classification.getKind()) {
1393 case Sema::NC_Error:
1394 return ANK_Error;
1395
1396 case Sema::NC_Keyword:
1397 // The identifier was typo-corrected to a keyword.
1398 Tok.setIdentifierInfo(Name);
1399 Tok.setKind(Name->getTokenID());
1400 PP.TypoCorrectToken(Tok);
1401 if (SS.isNotEmpty())
1402 AnnotateScopeToken(SS, !WasScopeAnnotation);
1403 // We've "annotated" this as a keyword.
1404 return ANK_Success;
1405
1406 case Sema::NC_Unknown:
1407 // It's not something we know about. Leave it unannotated.
1408 break;
1409
1410 case Sema::NC_Type:
1411 Tok.setKind(tok::annot_typename);
1412 setTypeAnnotation(Tok, Classification.getType());
1413 Tok.setAnnotationEndLoc(NameLoc);
1414 if (SS.isNotEmpty())
1415 Tok.setLocation(SS.getBeginLoc());
1416 PP.AnnotateCachedTokens(Tok);
1417 return ANK_Success;
1418
1419 case Sema::NC_Expression:
1420 Tok.setKind(tok::annot_primary_expr);
1421 setExprAnnotation(Tok, Classification.getExpression());
1422 Tok.setAnnotationEndLoc(NameLoc);
1423 if (SS.isNotEmpty())
1424 Tok.setLocation(SS.getBeginLoc());
1425 PP.AnnotateCachedTokens(Tok);
1426 return ANK_Success;
1427
1428 case Sema::NC_TypeTemplate:
1429 if (Next.isNot(tok::less)) {
1430 // This may be a type template being used as a template template argument.
1431 if (SS.isNotEmpty())
1432 AnnotateScopeToken(SS, !WasScopeAnnotation);
1433 return ANK_TemplateName;
1434 }
1435 // Fall through.
1436 case Sema::NC_FunctionTemplate: {
1437 // We have a type or function template followed by '<'.
1438 ConsumeToken();
1439 UnqualifiedId Id;
1440 Id.setIdentifier(Name, NameLoc);
1441 if (AnnotateTemplateIdToken(
1442 TemplateTy::make(Classification.getTemplateName()),
1443 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1444 return ANK_Error;
1445 return ANK_Success;
1446 }
1447
1448 case Sema::NC_NestedNameSpecifier:
1449 llvm_unreachable("already parsed nested name specifier");
1450 }
1451
1452 // Unable to classify the name, but maybe we can annotate a scope specifier.
1453 if (SS.isNotEmpty())
1454 AnnotateScopeToken(SS, !WasScopeAnnotation);
1455 return ANK_Unresolved;
1456}
1457
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001458/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1459/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1460/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1461/// with a single annotation token representing the typename or C++ scope
1462/// respectively.
1463/// This simplifies handling of C++ scope specifiers and allows efficient
1464/// backtracking without the need to re-parse and resolve nested-names and
1465/// typenames.
Argyrios Kyrtzidis0c4162a2008-11-26 21:51:07 +00001466/// It will mainly be called when we expect to treat identifiers as typenames
1467/// (if they are typenames). For example, in C we do not expect identifiers
1468/// inside expressions to be treated as typenames so it will not be called
1469/// for expressions in C.
1470/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroff16c8e592009-01-28 19:39:02 +00001471/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argyrios Kyrtzidis0c4162a2008-11-26 21:51:07 +00001472/// will not be called twice, once to check whether we have a declaration
1473/// specifier, and another one to get the actual type inside
1474/// ParseDeclarationSpecifiers).
Chris Lattner9a8968b2009-01-04 23:23:14 +00001475///
John McCall1f476a12010-02-26 08:45:28 +00001476/// This returns true if an error occurred.
Mike Stump11289f42009-09-09 15:08:12 +00001477///
Chris Lattner45ddec32009-01-05 00:13:00 +00001478/// Note that this routine emits an error if you call it with ::new or ::delete
1479/// as the current tokens, so only call it in contexts where these are invalid.
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001480bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
Mike Stump11289f42009-09-09 15:08:12 +00001481 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
David Blaikie15a430a2011-12-04 05:04:18 +00001482 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
Richard Smithb71e7322012-05-14 22:43:34 +00001483 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1484 && "Cannot be a type or scope token!");
Mike Stump11289f42009-09-09 15:08:12 +00001485
Douglas Gregor333489b2009-03-27 23:10:48 +00001486 if (Tok.is(tok::kw_typename)) {
1487 // Parse a C++ typename-specifier, e.g., "typename T::type".
1488 //
1489 // typename-specifier:
1490 // 'typename' '::' [opt] nested-name-specifier identifier
Mike Stump11289f42009-09-09 15:08:12 +00001491 // 'typename' '::' [opt] nested-name-specifier template [opt]
Douglas Gregordce2b622009-04-01 00:28:59 +00001492 // simple-template-id
Douglas Gregor333489b2009-03-27 23:10:48 +00001493 SourceLocation TypenameLoc = ConsumeToken();
1494 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +00001495 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1496 /*EnteringContext=*/false,
Francois Pichet4e7a2c02011-03-27 19:41:34 +00001497 0, /*IsTypename*/true))
John McCall1f476a12010-02-26 08:45:28 +00001498 return true;
1499 if (!SS.isSet()) {
Francois Pichetf5b24e02012-07-22 15:10:57 +00001500 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1501 Tok.is(tok::annot_decltype)) {
Richard Smithb71e7322012-05-14 22:43:34 +00001502 // Attempt to recover by skipping the invalid 'typename'
Francois Pichetf5b24e02012-07-22 15:10:57 +00001503 if (Tok.is(tok::annot_decltype) ||
1504 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1505 Tok.isAnnotation())) {
Richard Smithb71e7322012-05-14 22:43:34 +00001506 unsigned DiagID = diag::err_expected_qualified_after_typename;
1507 // MS compatibility: MSVC permits using known types with typename.
1508 // e.g. "typedef typename T* pointer_type"
1509 if (getLangOpts().MicrosoftExt)
1510 DiagID = diag::warn_expected_qualified_after_typename;
1511 Diag(Tok.getLocation(), DiagID);
1512 return false;
1513 }
1514 }
1515
1516 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
John McCall1f476a12010-02-26 08:45:28 +00001517 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00001518 }
1519
1520 TypeResult Ty;
1521 if (Tok.is(tok::identifier)) {
1522 // FIXME: check whether the next token is '<', first!
Douglas Gregor0be31a22010-07-02 17:43:08 +00001523 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Douglas Gregorf7d77712010-06-16 22:31:08 +00001524 *Tok.getIdentifierInfo(),
Douglas Gregor333489b2009-03-27 23:10:48 +00001525 Tok.getLocation());
Douglas Gregordce2b622009-04-01 00:28:59 +00001526 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001527 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregordce2b622009-04-01 00:28:59 +00001528 if (TemplateId->Kind == TNK_Function_template) {
1529 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1530 << Tok.getAnnotationRange();
John McCall1f476a12010-02-26 08:45:28 +00001531 return true;
Douglas Gregordce2b622009-04-01 00:28:59 +00001532 }
Douglas Gregor333489b2009-03-27 23:10:48 +00001533
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001534 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb09518c2011-02-27 22:46:49 +00001535 TemplateId->NumArgs);
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001536
Douglas Gregorb09518c2011-02-27 22:46:49 +00001537 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001538 TemplateId->TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00001539 TemplateId->Template,
1540 TemplateId->TemplateNameLoc,
1541 TemplateId->LAngleLoc,
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001542 TemplateArgsPtr,
Douglas Gregorb09518c2011-02-27 22:46:49 +00001543 TemplateId->RAngleLoc);
Douglas Gregordce2b622009-04-01 00:28:59 +00001544 } else {
1545 Diag(Tok, diag::err_expected_type_name_after_typename)
1546 << SS.getRange();
John McCall1f476a12010-02-26 08:45:28 +00001547 return true;
Douglas Gregordce2b622009-04-01 00:28:59 +00001548 }
1549
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +00001550 SourceLocation EndLoc = Tok.getLastLoc();
Douglas Gregordce2b622009-04-01 00:28:59 +00001551 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +00001552 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +00001553 Tok.setAnnotationEndLoc(EndLoc);
Douglas Gregordce2b622009-04-01 00:28:59 +00001554 Tok.setLocation(TypenameLoc);
1555 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001556 return false;
Douglas Gregor333489b2009-03-27 23:10:48 +00001557 }
1558
John McCalle2ade282009-12-19 00:35:18 +00001559 // Remembers whether the token was originally a scope annotation.
Richard Smith4f605af2012-08-18 00:55:03 +00001560 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
John McCalle2ade282009-12-19 00:35:18 +00001561
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001562 CXXScopeSpec SS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001563 if (getLangOpts().CPlusPlus)
John McCallba7bf592010-08-24 05:47:05 +00001564 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall1f476a12010-02-26 08:45:28 +00001565 return true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001566
Richard Smith4f605af2012-08-18 00:55:03 +00001567 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1568 SS, !WasScopeAnnotation);
1569}
1570
1571/// \brief Try to annotate a type or scope token, having already parsed an
1572/// optional scope specifier. \p IsNewScope should be \c true unless the scope
1573/// specifier was extracted from an existing tok::annot_cxxscope annotation.
1574bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1575 bool NeedType,
1576 CXXScopeSpec &SS,
1577 bool IsNewScope) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001578 if (Tok.is(tok::identifier)) {
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001579 IdentifierInfo *CorrectedII = 0;
Chris Lattnerda030082009-01-05 01:49:50 +00001580 // Determine whether the identifier is a type name.
John McCallba7bf592010-08-24 05:47:05 +00001581 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1582 Tok.getLocation(), getCurScope(),
Fariborz Jahanian87967422011-02-08 18:05:59 +00001583 &SS, false,
Douglas Gregor844cb502011-03-01 18:12:44 +00001584 NextToken().is(tok::period),
1585 ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +00001586 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001587 /*NonTrivialTypeSourceInfo*/true,
1588 NeedType ? &CorrectedII : NULL)) {
1589 // A FixIt was applied as a result of typo correction
1590 if (CorrectedII)
1591 Tok.setIdentifierInfo(CorrectedII);
Chris Lattnerda030082009-01-05 01:49:50 +00001592 // This is a typename. Replace the current token in-place with an
1593 // annotation type token.
Chris Lattnera8a3f732009-01-06 05:06:21 +00001594 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +00001595 setTypeAnnotation(Tok, Ty);
Chris Lattnerda030082009-01-05 01:49:50 +00001596 Tok.setAnnotationEndLoc(Tok.getLocation());
1597 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1598 Tok.setLocation(SS.getBeginLoc());
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattnerda030082009-01-05 01:49:50 +00001600 // In case the tokens were cached, have Preprocessor replace
1601 // them with the annotation token.
1602 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001603 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001604 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001605
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 if (!getLangOpts().CPlusPlus) {
Chris Lattnerda030082009-01-05 01:49:50 +00001607 // If we're in C, we can't have :: tokens at all (the lexer won't return
1608 // them). If the identifier is not a type, then it can't be scope either,
Mike Stump11289f42009-09-09 15:08:12 +00001609 // just early exit.
Chris Lattnerda030082009-01-05 01:49:50 +00001610 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregor7f741122009-02-25 19:37:18 +00001613 // If this is a template-id, annotate with a template-id or type token.
Douglas Gregor8bf42052009-02-09 18:46:07 +00001614 if (NextToken().is(tok::less)) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001615 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001616 UnqualifiedId TemplateName;
1617 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +00001618 bool MemberOfUnknownSpecialization;
Mike Stump11289f42009-09-09 15:08:12 +00001619 if (TemplateNameKind TNK
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001620 = Actions.isTemplateName(getCurScope(), SS,
1621 /*hasTemplateKeyword=*/false, TemplateName,
John McCallba7bf592010-08-24 05:47:05 +00001622 /*ObjectType=*/ ParsedType(),
1623 EnteringContext,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001624 Template, MemberOfUnknownSpecialization)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00001625 // Consume the identifier.
1626 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001627 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1628 TemplateName)) {
Chris Lattner5558e9f2009-06-26 04:27:47 +00001629 // If an unrecoverable error occurred, we need to return true here,
1630 // because the token stream is in a damaged state. We may not return
1631 // a valid identifier.
John McCall1f476a12010-02-26 08:45:28 +00001632 return true;
Chris Lattner5558e9f2009-06-26 04:27:47 +00001633 }
Douglas Gregor71395fa2009-11-04 00:56:37 +00001634 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00001635 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001636
Douglas Gregor7f741122009-02-25 19:37:18 +00001637 // The current token, which is either an identifier or a
1638 // template-id, is not part of the annotation. Fall through to
1639 // push that token back into the stream and complete the C++ scope
1640 // specifier annotation.
Mike Stump11289f42009-09-09 15:08:12 +00001641 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001642
Douglas Gregor7f741122009-02-25 19:37:18 +00001643 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001644 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001645 if (TemplateId->Kind == TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001646 // A template-id that refers to a type was parsed into a
1647 // template-id annotation in a context where we weren't allowed
1648 // to produce a type annotation token. Update the template-id
1649 // annotation token to a type annotation token now.
Douglas Gregore7c20652011-03-02 00:47:37 +00001650 AnnotateTemplateIdTokenAsType();
John McCall1f476a12010-02-26 08:45:28 +00001651 return false;
Douglas Gregor7f741122009-02-25 19:37:18 +00001652 }
1653 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001654
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001655 if (SS.isEmpty())
John McCall1f476a12010-02-26 08:45:28 +00001656 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001657
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001658 // A C++ scope specifier that isn't followed by a typename.
Richard Smith4f605af2012-08-18 00:55:03 +00001659 AnnotateScopeToken(SS, IsNewScope);
John McCall1f476a12010-02-26 08:45:28 +00001660 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001661}
1662
1663/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Douglas Gregor7f741122009-02-25 19:37:18 +00001664/// annotates C++ scope specifiers and template-ids. This returns
Richard Smith45855df2012-05-09 08:23:23 +00001665/// true if there was an error that could not be recovered from.
Mike Stump11289f42009-09-09 15:08:12 +00001666///
Chris Lattner45ddec32009-01-05 00:13:00 +00001667/// Note that this routine emits an error if you call it with ::new or ::delete
1668/// as the current tokens, so only call it in contexts where these are invalid.
Douglas Gregore861bac2009-08-25 22:51:20 +00001669bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001670 assert(getLangOpts().CPlusPlus &&
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001671 "Call sites of this function should be guarded by checking for C++");
Douglas Gregor8b02cd02011-04-27 04:48:22 +00001672 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
David Blaikie15a430a2011-12-04 05:04:18 +00001673 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1674 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001675
Argyrios Kyrtzidisace521a2008-11-26 21:41:52 +00001676 CXXScopeSpec SS;
John McCallba7bf592010-08-24 05:47:05 +00001677 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall1f476a12010-02-26 08:45:28 +00001678 return true;
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00001679 if (SS.isEmpty())
John McCall1f476a12010-02-26 08:45:28 +00001680 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001681
Richard Smith4f605af2012-08-18 00:55:03 +00001682 AnnotateScopeToken(SS, true);
John McCall1f476a12010-02-26 08:45:28 +00001683 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001684}
John McCall37958aa2009-11-03 19:33:12 +00001685
Richard Trieu4972a6d2012-01-19 22:01:51 +00001686bool Parser::isTokenEqualOrEqualTypo() {
1687 tok::TokenKind Kind = Tok.getKind();
1688 switch (Kind) {
1689 default:
Richard Trieuc64d3232012-01-18 22:54:52 +00001690 return false;
Richard Trieu4972a6d2012-01-19 22:01:51 +00001691 case tok::ampequal: // &=
1692 case tok::starequal: // *=
1693 case tok::plusequal: // +=
1694 case tok::minusequal: // -=
1695 case tok::exclaimequal: // !=
1696 case tok::slashequal: // /=
1697 case tok::percentequal: // %=
1698 case tok::lessequal: // <=
1699 case tok::lesslessequal: // <<=
1700 case tok::greaterequal: // >=
1701 case tok::greatergreaterequal: // >>=
1702 case tok::caretequal: // ^=
1703 case tok::pipeequal: // |=
1704 case tok::equalequal: // ==
1705 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1706 << getTokenSimpleSpelling(Kind)
1707 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1708 case tok::equal:
1709 return true;
1710 }
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001711}
1712
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001713SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1714 assert(Tok.is(tok::code_completion));
1715 PrevTokLocation = Tok.getLocation();
1716
Douglas Gregor0be31a22010-07-02 17:43:08 +00001717 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregor6da3db42010-05-25 05:58:43 +00001718 if (S->getFlags() & Scope::FnScope) {
John McCallfaf5fb42010-08-26 23:41:50 +00001719 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001720 cutOffParsing();
1721 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001722 }
1723
1724 if (S->getFlags() & Scope::ClassScope) {
John McCallfaf5fb42010-08-26 23:41:50 +00001725 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001726 cutOffParsing();
1727 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001728 }
1729 }
1730
John McCallfaf5fb42010-08-26 23:41:50 +00001731 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001732 cutOffParsing();
1733 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001734}
1735
John McCall37958aa2009-11-03 19:33:12 +00001736// Anchor the Parser::FieldCallback vtable to this translation unit.
1737// We use a spurious method instead of the destructor because
1738// destroying FieldCallbacks can actually be slightly
1739// performance-sensitive.
1740void Parser::FieldCallback::_anchor() {
1741}
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001742
1743// Code-completion pass-through functions
1744
1745void Parser::CodeCompleteDirective(bool InConditional) {
Douglas Gregorec00a262010-08-24 22:20:20 +00001746 Actions.CodeCompletePreprocessorDirective(InConditional);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001747}
1748
1749void Parser::CodeCompleteInConditionalExclusion() {
1750 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1751}
Douglas Gregor12785102010-08-24 20:21:13 +00001752
1753void Parser::CodeCompleteMacroName(bool IsDefinition) {
Douglas Gregorec00a262010-08-24 22:20:20 +00001754 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1755}
1756
1757void Parser::CodeCompletePreprocessorExpression() {
1758 Actions.CodeCompletePreprocessorExpression();
1759}
1760
1761void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1762 MacroInfo *MacroInfo,
1763 unsigned ArgumentIndex) {
1764 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1765 ArgumentIndex);
Douglas Gregor12785102010-08-24 20:21:13 +00001766}
Douglas Gregor11583702010-08-25 17:04:25 +00001767
1768void Parser::CodeCompleteNaturalLanguage() {
1769 Actions.CodeCompleteNaturalLanguage();
1770}
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001771
Douglas Gregor43edb322011-10-24 22:31:10 +00001772bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001773 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1774 "Expected '__if_exists' or '__if_not_exists'");
Douglas Gregor43edb322011-10-24 22:31:10 +00001775 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1776 Result.KeywordLoc = ConsumeToken();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001777
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001778 BalancedDelimiterTracker T(*this, tok::l_paren);
1779 if (T.consumeOpen()) {
Douglas Gregor43edb322011-10-24 22:31:10 +00001780 Diag(Tok, diag::err_expected_lparen_after)
1781 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001782 return true;
1783 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001784
1785 // Parse nested-name-specifier.
Douglas Gregordf593fb2011-11-07 17:33:42 +00001786 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1787 /*EnteringContext=*/false);
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001788
1789 // Check nested-name specifier.
Douglas Gregor43edb322011-10-24 22:31:10 +00001790 if (Result.SS.isInvalid()) {
1791 T.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001792 return true;
1793 }
1794
Abramo Bagnara7945c982012-01-27 09:46:47 +00001795 // Parse the unqualified-id.
1796 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1797 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1798 TemplateKWLoc, Result.Name)) {
Douglas Gregor43edb322011-10-24 22:31:10 +00001799 T.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001800 return true;
1801 }
1802
Douglas Gregor43edb322011-10-24 22:31:10 +00001803 if (T.consumeClose())
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001804 return true;
Douglas Gregor43edb322011-10-24 22:31:10 +00001805
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001806 // Check if the symbol exists.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001807 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1808 Result.IsIfExists, Result.SS,
Douglas Gregor43edb322011-10-24 22:31:10 +00001809 Result.Name)) {
1810 case Sema::IER_Exists:
1811 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1812 break;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001813
Douglas Gregor43edb322011-10-24 22:31:10 +00001814 case Sema::IER_DoesNotExist:
1815 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1816 break;
1817
1818 case Sema::IER_Dependent:
1819 Result.Behavior = IEB_Dependent;
1820 break;
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001821
1822 case Sema::IER_Error:
1823 return true;
Douglas Gregor43edb322011-10-24 22:31:10 +00001824 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001825
1826 return false;
1827}
1828
Francois Pichet8f981d52011-05-25 10:19:49 +00001829void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
Douglas Gregor43edb322011-10-24 22:31:10 +00001830 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001831 if (ParseMicrosoftIfExistsCondition(Result))
1832 return;
1833
Douglas Gregor43edb322011-10-24 22:31:10 +00001834 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1835 if (Braces.consumeOpen()) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001836 Diag(Tok, diag::err_expected_lbrace);
1837 return;
1838 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001839
Douglas Gregor43edb322011-10-24 22:31:10 +00001840 switch (Result.Behavior) {
1841 case IEB_Parse:
1842 // Parse declarations below.
1843 break;
1844
1845 case IEB_Dependent:
1846 llvm_unreachable("Cannot have a dependent external declaration");
1847
1848 case IEB_Skip:
1849 Braces.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001850 return;
1851 }
1852
Douglas Gregor43edb322011-10-24 22:31:10 +00001853 // Parse the declarations.
1854 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001855 ParsedAttributesWithRange attrs(AttrFactory);
1856 MaybeParseCXX0XAttributes(attrs);
1857 MaybeParseMicrosoftAttributes(attrs);
1858 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1859 if (Result && !getCurScope()->getParent())
1860 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00001861 }
1862 Braces.consumeClose();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001863}
Douglas Gregor08142532011-08-26 23:56:07 +00001864
Douglas Gregor22d09742012-01-03 18:04:46 +00001865Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001866 assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&
Douglas Gregorca975892011-08-31 18:19:09 +00001867 "Improper start to module import");
Douglas Gregor08142532011-08-26 23:56:07 +00001868 SourceLocation ImportLoc = ConsumeToken();
1869
Douglas Gregor71944202011-11-30 00:36:36 +00001870 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor08142532011-08-26 23:56:07 +00001871
Douglas Gregor71944202011-11-30 00:36:36 +00001872 // Parse the module path.
1873 do {
1874 if (!Tok.is(tok::identifier)) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001875 if (Tok.is(tok::code_completion)) {
1876 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1877 ConsumeCodeCompletionToken();
1878 SkipUntil(tok::semi);
1879 return DeclGroupPtrTy();
1880 }
1881
Douglas Gregor71944202011-11-30 00:36:36 +00001882 Diag(Tok, diag::err_module_expected_ident);
1883 SkipUntil(tok::semi);
1884 return DeclGroupPtrTy();
1885 }
1886
1887 // Record this part of the module path.
1888 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1889 ConsumeToken();
1890
1891 if (Tok.is(tok::period)) {
1892 ConsumeToken();
1893 continue;
1894 }
1895
1896 break;
1897 } while (true);
1898
Douglas Gregor22d09742012-01-03 18:04:46 +00001899 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
Douglas Gregor08142532011-08-26 23:56:07 +00001900 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1901 if (Import.isInvalid())
1902 return DeclGroupPtrTy();
1903
1904 return Actions.ConvertDeclToDeclGroup(Import.get());
1905}
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001906
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001907bool BalancedDelimiterTracker::diagnoseOverflow() {
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001908 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1909 P.SkipUntil(tok::eof);
1910 return true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001911}
1912
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001913bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001914 const char *Msg,
1915 tok::TokenKind SkipToToc ) {
1916 LOpen = P.Tok.getLocation();
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001917 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1918 return true;
1919
1920 if (getDepth() < MaxDepth)
1921 return false;
1922
1923 return diagnoseOverflow();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001924}
1925
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001926bool BalancedDelimiterTracker::diagnoseMissingClose() {
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001927 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1928
1929 const char *LHSName = "unknown";
David Blaikie89f13cb2012-04-06 23:33:59 +00001930 diag::kind DID;
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001931 switch (Close) {
David Blaikie89f13cb2012-04-06 23:33:59 +00001932 default: llvm_unreachable("Unexpected balanced token");
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001933 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1934 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1935 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001936 }
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001937 P.Diag(P.Tok, DID);
1938 P.Diag(LOpen, diag::note_matching) << LHSName;
1939 if (P.SkipUntil(Close))
1940 LClose = P.Tok.getLocation();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001941 return true;
1942}
Douglas Gregor43edb322011-10-24 22:31:10 +00001943
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001944void BalancedDelimiterTracker::skipToEnd() {
Douglas Gregor43edb322011-10-24 22:31:10 +00001945 P.SkipUntil(Close, false);
Douglas Gregor43edb322011-10-24 22:31:10 +00001946}