blob: e6b49474f796ea9f03f94a2dcaa425bc2348c79b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Parser.cpp - C Language Family Parser ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner500d3292009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
Chris Lattner0102c302009-03-05 07:24:28 +000019#include "llvm/Support/raw_ostream.h"
Chris Lattnerd167ca02009-12-10 00:21:05 +000020#include "RAIIObjectsForParser.h"
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +000021#include "ParsePragma.h"
Francois Pichet8387e2a2011-04-22 22:18:13 +000022#include "clang/AST/DeclTemplate.h"
Francois Pichetf9860382011-05-07 17:30:27 +000023#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Mahesha S68de1402012-10-27 09:05:45 +000026
Benjamin Kramer69b5e952012-07-13 13:25:11 +000027namespace {
Dmitri Gribenkoaa0cd852012-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 Kramer69b5e952012-07-13 13:25:11 +000041} // end anonymous namespace
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000042
Douglas Gregorb57791e2011-10-21 03:57:52 +000043IdentifierInfo *Parser::getSEHExceptKeyword() {
44 // __except is accepted as a (contextual) keyword
David Blaikie4e4d0842012-03-11 07:00:24 +000045 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
Douglas Gregorb57791e2011-10-21 03:57:52 +000046 Ident__except = PP.getIdentifierInfo("__except");
47
48 return Ident__except;
49}
50
Argyrios Kyrtzidis25893e02012-10-31 17:29:22 +000051Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
Ted Kremenek614f96a2011-03-22 01:15:17 +000052 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
Douglas Gregor0fbda682010-09-15 14:51:05 +000053 GreaterThanIsOperator(true), ColonIsSacred(false),
Erik Verbruggen6a91d382012-04-12 10:11:59 +000054 InMessageExpression(false), TemplateParameterDepth(0),
Argyrios Kyrtzidis25893e02012-10-31 17:29:22 +000055 ParsingInObjCContainer(false) {
56 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
Chris Lattner2b970e92012-10-27 19:49:20 +000057 Tok.startToken();
Reid Spencer5f016e22007-07-11 17:01:13 +000058 Tok.setKind(tok::eof);
Douglas Gregor23c94db2010-07-02 17:43:08 +000059 Actions.CurScope = 0;
Chris Lattner9e344c62007-07-15 00:04:39 +000060 NumCachedScopes = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000061 ParenCount = BracketCount = BraceCount = 0;
Argyrios Kyrtzidis849639d2012-02-07 16:50:53 +000062 CurParsedObjCImpl = 0;
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +000063
64 // Add #pragma handlers. These are removed and destroyed in the
65 // destructor.
Eli Friedman9595c7e2012-10-04 02:36:51 +000066 AlignHandler.reset(new PragmaAlignHandler());
Daniel Dunbarcbb98ed2010-07-31 19:17:07 +000067 PP.AddPragmaHandler(AlignHandler.get());
68
Eli Friedman9595c7e2012-10-04 02:36:51 +000069 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
Eli Friedmanaa8b0d12010-08-05 06:57:20 +000070 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
71
Eli Friedman9595c7e2012-10-04 02:36:51 +000072 OptionsHandler.reset(new PragmaOptionsHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000073 PP.AddPragmaHandler(OptionsHandler.get());
Daniel Dunbar861800c2010-05-26 23:29:06 +000074
Eli Friedman9595c7e2012-10-04 02:36:51 +000075 PackHandler.reset(new PragmaPackHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000076 PP.AddPragmaHandler(PackHandler.get());
Fariborz Jahanian62c92582011-04-25 18:49:15 +000077
Eli Friedman9595c7e2012-10-04 02:36:51 +000078 MSStructHandler.reset(new PragmaMSStructHandler());
Fariborz Jahanian62c92582011-04-25 18:49:15 +000079 PP.AddPragmaHandler(MSStructHandler.get());
Mike Stump1eb44332009-09-09 15:08:12 +000080
Eli Friedman9595c7e2012-10-04 02:36:51 +000081 UnusedHandler.reset(new PragmaUnusedHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000082 PP.AddPragmaHandler(UnusedHandler.get());
Eli Friedman99914792009-06-05 00:49:58 +000083
Eli Friedman9595c7e2012-10-04 02:36:51 +000084 WeakHandler.reset(new PragmaWeakHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000085 PP.AddPragmaHandler(WeakHandler.get());
Peter Collingbourne321b8172011-02-14 01:42:35 +000086
Eli Friedman9595c7e2012-10-04 02:36:51 +000087 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
David Chisnall5f3c1632012-02-18 16:12:34 +000088 PP.AddPragmaHandler(RedefineExtnameHandler.get());
89
Eli Friedman9595c7e2012-10-04 02:36:51 +000090 FPContractHandler.reset(new PragmaFPContractHandler());
Peter Collingbourne321b8172011-02-14 01:42:35 +000091 PP.AddPragmaHandler("STDC", FPContractHandler.get());
Peter Collingbournef315fa82011-02-14 01:42:53 +000092
David Blaikie4e4d0842012-03-11 07:00:24 +000093 if (getLangOpts().OpenCL) {
Eli Friedman9595c7e2012-10-04 02:36:51 +000094 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
Peter Collingbournef315fa82011-02-14 01:42:53 +000095 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
96
97 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
98 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000099
Dmitri Gribenko056e2c32012-06-20 01:06:08 +0000100 CommentSemaHandler.reset(new ActionCommentHandler(actions));
101 PP.addCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000102
Douglas Gregorf44e8542010-08-24 19:08:16 +0000103 PP.setCodeCompletionHandler(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000104}
105
Chris Lattner0102c302009-03-05 07:24:28 +0000106/// If a crash happens while the parser is active, print out a line indicating
107/// what the current token is.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
Chris Lattner0102c302009-03-05 07:24:28 +0000109 const Token &Tok = P.getCurToken();
Chris Lattnerddcbc0a2009-03-05 07:27:50 +0000110 if (Tok.is(tok::eof)) {
Chris Lattner0102c302009-03-05 07:24:28 +0000111 OS << "<eof> parser at end of file\n";
112 return;
113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Chris Lattnerddcbc0a2009-03-05 07:27:50 +0000115 if (Tok.getLocation().isInvalid()) {
116 OS << "<unknown> parser at unknown location\n";
117 return;
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattner0102c302009-03-05 07:24:28 +0000120 const Preprocessor &PP = P.getPreprocessor();
121 Tok.getLocation().print(OS, PP.getSourceManager());
Daniel Dunbar9fa31dd2009-10-17 06:13:04 +0000122 if (Tok.isAnnotation())
123 OS << ": at annotation token \n";
124 else
125 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
Douglas Gregorf780abc2008-12-30 03:27:21 +0000126}
Reid Spencer5f016e22007-07-11 17:01:13 +0000127
Chris Lattner0102c302009-03-05 07:24:28 +0000128
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000129DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000130 return Diags.Report(Loc, DiagID);
Chris Lattner1ab3b962008-11-18 07:48:38 +0000131}
132
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000133DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000134 return Diag(Tok.getLocation(), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135}
136
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000137/// \brief Emits a diagnostic suggesting parentheses surrounding a
138/// given range.
139///
140/// \param Loc The location where we'll emit the diagnostic.
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000141/// \param DK The kind of diagnostic to emit.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000142/// \param ParenRange Source range enclosing code that should be parenthesized.
143void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
144 SourceRange ParenRange) {
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000145 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
146 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000147 // We can't display the parentheses, so just dig the
148 // warning/error and return.
149 Diag(Loc, DK);
150 return;
151 }
Mike Stump1eb44332009-09-09 15:08:12 +0000152
153 Diag(Loc, DK)
Douglas Gregor849b2432010-03-31 17:46:05 +0000154 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
155 << FixItHint::CreateInsertion(EndLoc, ")");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000156}
157
John McCall837b1a32010-09-07 18:31:03 +0000158static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
159 switch (ExpectedTok) {
Richard Smith4b082422012-09-18 00:52:05 +0000160 case tok::semi:
161 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
John McCall837b1a32010-09-07 18:31:03 +0000162 default: return false;
163 }
164}
165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
167/// input. If so, it is consumed and false is returned.
168///
169/// If the input is malformed, this emits the specified diagnostic. Next, if
170/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
171/// returned.
172bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
173 const char *Msg, tok::TokenKind SkipToTok) {
Douglas Gregordc845342010-05-25 05:58:43 +0000174 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 ConsumeAnyToken();
176 return false;
177 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000178
John McCall837b1a32010-09-07 18:31:03 +0000179 // Detect common single-character typos and resume.
180 if (IsCommonTypo(ExpectedTok, Tok)) {
181 SourceLocation Loc = Tok.getLocation();
182 Diag(Loc, DiagID)
183 << Msg
184 << FixItHint::CreateReplacement(SourceRange(Loc),
185 getTokenSimpleSpelling(ExpectedTok));
186 ConsumeAnyToken();
187
188 // Pretend there wasn't a problem.
189 return false;
190 }
191
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000192 const char *Spelling = 0;
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000193 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
Mike Stump1eb44332009-09-09 15:08:12 +0000194 if (EndLoc.isValid() &&
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000195 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000196 // Show what code to insert to fix this problem.
Mike Stump1eb44332009-09-09 15:08:12 +0000197 Diag(EndLoc, DiagID)
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000198 << Msg
Douglas Gregor849b2432010-03-31 17:46:05 +0000199 << FixItHint::CreateInsertion(EndLoc, Spelling);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000200 } else
201 Diag(Tok, DiagID) << Msg;
202
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 if (SkipToTok != tok::unknown)
204 SkipUntil(SkipToTok);
205 return true;
206}
207
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000208bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
209 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
Douglas Gregorfb5825d2012-05-02 14:34:16 +0000210 ConsumeToken();
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000211 return false;
212 }
213
214 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
215 NextToken().is(tok::semi)) {
216 Diag(Tok, diag::err_extraneous_token_before_semi)
217 << PP.getSpelling(Tok)
218 << FixItHint::CreateRemoval(Tok.getLocation());
219 ConsumeAnyToken(); // The ')' or ']'.
220 ConsumeToken(); // The ';'.
221 return false;
222 }
223
224 return ExpectAndConsume(tok::semi, DiagID);
225}
226
Richard Smitheab9d6f2012-07-23 05:45:25 +0000227void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000228 if (!Tok.is(tok::semi)) return;
229
Richard Smitheab9d6f2012-07-23 05:45:25 +0000230 bool HadMultipleSemis = false;
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000231 SourceLocation StartLoc = Tok.getLocation();
232 SourceLocation EndLoc = Tok.getLocation();
233 ConsumeToken();
234
235 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
Richard Smitheab9d6f2012-07-23 05:45:25 +0000236 HadMultipleSemis = true;
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000237 EndLoc = Tok.getLocation();
238 ConsumeToken();
239 }
240
Richard Smitheab9d6f2012-07-23 05:45:25 +0000241 // C++11 allows extra semicolons at namespace scope, but not in any of the
242 // other contexts.
243 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
244 if (getLangOpts().CPlusPlus0x)
245 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
246 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
247 else
248 Diag(StartLoc, diag::ext_extra_semi_cxx11)
249 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000250 return;
251 }
252
Richard Smitheab9d6f2012-07-23 05:45:25 +0000253 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
254 Diag(StartLoc, diag::ext_extra_semi)
255 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
256 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
257 else
258 // A single semicolon is valid after a member function definition.
259 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
260 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000261}
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263//===----------------------------------------------------------------------===//
264// Error recovery.
265//===----------------------------------------------------------------------===//
266
267/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner012cf462007-07-24 17:03:04 +0000268/// it (unless DontConsume is true). Because we cannot guarantee that the
Reid Spencer5f016e22007-07-11 17:01:13 +0000269/// token will ever occur, this skips to the next token, or to some likely
270/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
271/// character.
Mike Stumpa6f01772008-06-19 19:28:49 +0000272///
Reid Spencer5f016e22007-07-11 17:01:13 +0000273/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stumpa6f01772008-06-19 19:28:49 +0000274/// returns false.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000275bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
276 bool DontConsume, bool StopAtCodeCompletion) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // We always want this function to skip at least one token if the first token
278 // isn't T and if not at EOF.
279 bool isFirstTokenSkipped = true;
280 while (1) {
281 // If we found one of the tokens, stop and return true.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000282 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
Chris Lattner00073222007-10-09 17:23:58 +0000283 if (Tok.is(Toks[i])) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 if (DontConsume) {
285 // Noop, don't consume the token.
286 } else {
287 ConsumeAnyToken();
288 }
289 return true;
290 }
291 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 switch (Tok.getKind()) {
294 case tok::eof:
295 // Ran out of tokens.
296 return false;
Douglas Gregordc845342010-05-25 05:58:43 +0000297
298 case tok::code_completion:
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000299 if (!StopAtCodeCompletion)
300 ConsumeToken();
Douglas Gregordc845342010-05-25 05:58:43 +0000301 return false;
302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 case tok::l_paren:
304 // Recursively skip properly-nested parens.
305 ConsumeParen();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000306 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 break;
308 case tok::l_square:
309 // Recursively skip properly-nested square brackets.
310 ConsumeBracket();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000311 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 break;
313 case tok::l_brace:
314 // Recursively skip properly-nested braces.
315 ConsumeBrace();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000316 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000318
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
320 // Since the user wasn't looking for this token (if they were, it would
321 // already be handled), this isn't balanced. If there is a LHS token at a
322 // higher level, we will assume that this matches the unbalanced token
323 // and return it. Otherwise, this is a spurious RHS token, which we skip.
324 case tok::r_paren:
325 if (ParenCount && !isFirstTokenSkipped)
326 return false; // Matches something.
327 ConsumeParen();
328 break;
329 case tok::r_square:
330 if (BracketCount && !isFirstTokenSkipped)
331 return false; // Matches something.
332 ConsumeBracket();
333 break;
334 case tok::r_brace:
335 if (BraceCount && !isFirstTokenSkipped)
336 return false; // Matches something.
337 ConsumeBrace();
338 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 case tok::string_literal:
341 case tok::wide_string_literal:
Douglas Gregor5cee1192011-07-27 05:40:30 +0000342 case tok::utf8_string_literal:
343 case tok::utf16_string_literal:
344 case tok::utf32_string_literal:
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 ConsumeStringToken();
346 break;
Fariborz Jahanian55edca92011-02-23 00:11:21 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 case tok::semi:
349 if (StopAtSemi)
350 return false;
351 // FALL THROUGH.
352 default:
353 // Skip this token.
354 ConsumeToken();
355 break;
356 }
357 isFirstTokenSkipped = false;
Mike Stumpa6f01772008-06-19 19:28:49 +0000358 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000359}
360
361//===----------------------------------------------------------------------===//
362// Scope manipulation
363//===----------------------------------------------------------------------===//
364
Reid Spencer5f016e22007-07-11 17:01:13 +0000365/// EnterScope - Start a new scope.
366void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner9e344c62007-07-15 00:04:39 +0000367 if (NumCachedScopes) {
368 Scope *N = ScopeCache[--NumCachedScopes];
Douglas Gregor23c94db2010-07-02 17:43:08 +0000369 N->Init(getCurScope(), ScopeFlags);
370 Actions.CurScope = N;
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 } else {
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +0000372 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 }
374}
375
376/// ExitScope - Pop a scope off the scope stack.
377void Parser::ExitScope() {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000378 assert(getCurScope() && "Scope imbalance!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000379
Chris Lattner90ae68a2007-10-09 20:37:18 +0000380 // Inform the actions module that this scope is going away if there are any
381 // decls in it.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000382 if (!getCurScope()->decl_empty())
383 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
Mike Stumpa6f01772008-06-19 19:28:49 +0000384
Douglas Gregor23c94db2010-07-02 17:43:08 +0000385 Scope *OldScope = getCurScope();
386 Actions.CurScope = OldScope->getParent();
Mike Stumpa6f01772008-06-19 19:28:49 +0000387
Chris Lattner9e344c62007-07-15 00:04:39 +0000388 if (NumCachedScopes == ScopeCacheSize)
389 delete OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 else
Chris Lattner9e344c62007-07-15 00:04:39 +0000391 ScopeCache[NumCachedScopes++] = OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000392}
393
Richard Smith7a614d82011-06-11 17:19:42 +0000394/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
395/// this object does nothing.
396Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
397 bool ManageFlags)
398 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
399 if (CurScope) {
400 OldFlags = CurScope->getFlags();
401 CurScope->setFlags(ScopeFlags);
402 }
403}
Reid Spencer5f016e22007-07-11 17:01:13 +0000404
Richard Smith7a614d82011-06-11 17:19:42 +0000405/// Restore the flags for the current scope to what they were before this
406/// object overrode them.
407Parser::ParseScopeFlags::~ParseScopeFlags() {
408 if (CurScope)
409 CurScope->setFlags(OldFlags);
410}
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
412
413//===----------------------------------------------------------------------===//
414// C99 6.9: External Definitions.
415//===----------------------------------------------------------------------===//
416
417Parser::~Parser() {
418 // If we still have scopes active, delete the scope tree.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000419 delete getCurScope();
420 Actions.CurScope = 0;
421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Free the scope cache.
Chris Lattner9e344c62007-07-15 00:04:39 +0000423 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
424 delete ScopeCache[i];
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +0000425
Francois Pichet8387e2a2011-04-22 22:18:13 +0000426 // Free LateParsedTemplatedFunction nodes.
427 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
428 it != LateParsedTemplateMap.end(); ++it)
429 delete it->second;
430
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +0000431 // Remove the pragma handlers we installed.
Daniel Dunbarcbb98ed2010-07-31 19:17:07 +0000432 PP.RemovePragmaHandler(AlignHandler.get());
433 AlignHandler.reset();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000434 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
435 GCCVisibilityHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000436 PP.RemovePragmaHandler(OptionsHandler.get());
Daniel Dunbar861800c2010-05-26 23:29:06 +0000437 OptionsHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000438 PP.RemovePragmaHandler(PackHandler.get());
Ted Kremenek4726d032009-03-23 22:28:25 +0000439 PackHandler.reset();
Fariborz Jahanian62c92582011-04-25 18:49:15 +0000440 PP.RemovePragmaHandler(MSStructHandler.get());
441 MSStructHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000442 PP.RemovePragmaHandler(UnusedHandler.get());
Ted Kremenek4726d032009-03-23 22:28:25 +0000443 UnusedHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000444 PP.RemovePragmaHandler(WeakHandler.get());
Eli Friedman99914792009-06-05 00:49:58 +0000445 WeakHandler.reset();
David Chisnall5f3c1632012-02-18 16:12:34 +0000446 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
447 RedefineExtnameHandler.reset();
Peter Collingbournef315fa82011-02-14 01:42:53 +0000448
David Blaikie4e4d0842012-03-11 07:00:24 +0000449 if (getLangOpts().OpenCL) {
Peter Collingbournef315fa82011-02-14 01:42:53 +0000450 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
451 OpenCLExtensionHandler.reset();
452 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
453 }
454
Peter Collingbourne321b8172011-02-14 01:42:35 +0000455 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
456 FPContractHandler.reset();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000457
Dmitri Gribenko056e2c32012-06-20 01:06:08 +0000458 PP.removeCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000459
Douglas Gregorf44e8542010-08-24 19:08:16 +0000460 PP.clearCodeCompletionHandler();
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000461
462 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000463}
464
465/// Initialize - Warm up the parser.
466///
467void Parser::Initialize() {
Chris Lattner31e05722007-08-26 06:24:45 +0000468 // Create the translation unit scope. Install it as the current scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000469 assert(getCurScope() == 0 && "A scope is already active?");
Chris Lattner31e05722007-08-26 06:24:45 +0000470 EnterScope(Scope::DeclScope);
Douglas Gregorc1a3e5e2010-08-25 18:07:12 +0000471 Actions.ActOnTranslationUnitScope(getCurScope());
472
473 // Prime the lexer look-ahead.
474 ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +0000475
Chris Lattner34870da2007-08-29 22:54:08 +0000476 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000477 // Referenced in Parser::ParseObjCTypeQualifierList.
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().ObjC1) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000479 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
480 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
481 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
482 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
483 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
484 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner34870da2007-08-29 22:54:08 +0000485 }
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000486
Douglas Gregore97179c2011-09-08 01:46:34 +0000487 Ident_instancetype = 0;
Anders Carlsson7eeb4ec2011-01-20 03:47:08 +0000488 Ident_final = 0;
489 Ident_override = 0;
Anders Carlsson1f3b6fd2011-01-16 23:56:42 +0000490
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000491 Ident_super = &PP.getIdentifierTable().get("super");
John Thompson82287d12010-02-05 00:12:22 +0000492
David Blaikie4e4d0842012-03-11 07:00:24 +0000493 if (getLangOpts().AltiVec) {
John Thompson82287d12010-02-05 00:12:22 +0000494 Ident_vector = &PP.getIdentifierTable().get("vector");
495 Ident_pixel = &PP.getIdentifierTable().get("pixel");
496 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000497
498 Ident_introduced = 0;
499 Ident_deprecated = 0;
500 Ident_obsoleted = 0;
Douglas Gregorb53e4172011-03-26 03:35:55 +0000501 Ident_unavailable = 0;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000502
Douglas Gregorb57791e2011-10-21 03:57:52 +0000503 Ident__except = 0;
504
John Wiegley28bbe4b2011-04-28 01:08:34 +0000505 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
506 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
507 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
508
David Blaikie4e4d0842012-03-11 07:00:24 +0000509 if(getLangOpts().Borland) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000510 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
511 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
512 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
513 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
514 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
515 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
516 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
517 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
518 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
519
520 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
521 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
522 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
523 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
524 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
525 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
526 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
527 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
528 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
529 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000530}
531
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000532namespace {
533 /// \brief RAIIObject to destroy the contents of a SmallVector of
534 /// TemplateIdAnnotation pointers and clear the vector.
535 class DestroyTemplateIdAnnotationsRAIIObj {
536 SmallVectorImpl<TemplateIdAnnotation *> &Container;
537 public:
538 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
539 &Container)
540 : Container(Container) {}
541
542 ~DestroyTemplateIdAnnotationsRAIIObj() {
543 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
544 Container.begin(), E = Container.end();
545 I != E; ++I)
546 (*I)->Destroy();
547 Container.clear();
548 }
549 };
550}
551
Reid Spencer5f016e22007-07-11 17:01:13 +0000552/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
553/// action tells us to. This returns true if the EOF was encountered.
Chris Lattner682bf922009-03-29 16:50:03 +0000554bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000555 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000556
Axel Naumanne55329d2012-03-16 10:40:17 +0000557 // Skip over the EOF token, flagging end of previous input for incremental
558 // processing
559 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
560 ConsumeToken();
561
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000562 while (Tok.is(tok::annot_pragma_unused))
563 HandlePragmaUnused();
564
Chris Lattner682bf922009-03-29 16:50:03 +0000565 Result = DeclGroupPtrTy();
Chris Lattner9299f3f2008-08-23 03:19:52 +0000566 if (Tok.is(tok::eof)) {
Francois Pichet8387e2a2011-04-22 22:18:13 +0000567 // Late template parsing can begin.
David Blaikie4e4d0842012-03-11 07:00:24 +0000568 if (getLangOpts().DelayedTemplateParsing)
Francois Pichet8387e2a2011-04-22 22:18:13 +0000569 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
Axel Naumanne55329d2012-03-16 10:40:17 +0000570 if (!PP.isIncrementalProcessingEnabled())
571 Actions.ActOnEndOfTranslationUnit();
572 //else don't tell Sema that we ended parsing: more input might come.
Francois Pichet8387e2a2011-04-22 22:18:13 +0000573
Chris Lattner9299f3f2008-08-23 03:19:52 +0000574 return true;
575 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000576
John McCall0b7e6782011-03-24 11:26:52 +0000577 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000578 MaybeParseCXX0XAttributes(attrs);
579 MaybeParseMicrosoftAttributes(attrs);
Axel Naumanne55329d2012-03-16 10:40:17 +0000580
John McCall7f040a92010-12-24 02:08:15 +0000581 Result = ParseExternalDeclaration(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 return false;
583}
584
Reid Spencer5f016e22007-07-11 17:01:13 +0000585/// ParseTranslationUnit:
586/// translation-unit: [C99 6.9]
Mike Stumpa6f01772008-06-19 19:28:49 +0000587/// external-declaration
588/// translation-unit external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000589void Parser::ParseTranslationUnit() {
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000590 Initialize();
Mike Stumpa6f01772008-06-19 19:28:49 +0000591
Chris Lattner682bf922009-03-29 16:50:03 +0000592 DeclGroupPtrTy Res;
Steve Naroff89307ff2007-11-29 23:05:20 +0000593 while (!ParseTopLevelDecl(Res))
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 /*parse them all*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner06f54852008-08-23 02:00:52 +0000596 ExitScope();
Douglas Gregor23c94db2010-07-02 17:43:08 +0000597 assert(getCurScope() == 0 && "Scope imbalance!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000598}
599
600/// ParseExternalDeclaration:
Chris Lattner90b93d62008-12-08 21:59:01 +0000601///
Douglas Gregorc19923d2008-11-21 16:10:08 +0000602/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattnerc3018152007-08-10 20:57:02 +0000603/// function-definition
604/// declaration
Douglas Gregora1d71ae2009-08-24 12:17:54 +0000605/// [C++0x] empty-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000606/// [GNU] asm-definition
Chris Lattnerc3018152007-08-10 20:57:02 +0000607/// [GNU] __extension__ external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000608/// [OBJC] objc-class-definition
609/// [OBJC] objc-class-declaration
610/// [OBJC] objc-alias-declaration
611/// [OBJC] objc-protocol-definition
612/// [OBJC] objc-method-definition
613/// [OBJC] @end
Douglas Gregorc19923d2008-11-21 16:10:08 +0000614/// [C++] linkage-specification
Reid Spencer5f016e22007-07-11 17:01:13 +0000615/// [GNU] asm-definition:
616/// simple-asm-expr ';'
617///
Douglas Gregora1d71ae2009-08-24 12:17:54 +0000618/// [C++0x] empty-declaration:
619/// ';'
620///
Douglas Gregor45f96552009-09-04 06:33:52 +0000621/// [C++0x/GNU] 'extern' 'template' declaration
John McCall7f040a92010-12-24 02:08:15 +0000622Parser::DeclGroupPtrTy
623Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
624 ParsingDeclSpec *DS) {
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000625 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +0000626 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000627
628 if (PP.isCodeCompletionReached()) {
629 cutOffParsing();
630 return DeclGroupPtrTy();
631 }
632
John McCalld226f652010-08-21 09:40:31 +0000633 Decl *SingleDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 switch (Tok.getKind()) {
Rafael Espindola426fc942012-01-26 02:02:57 +0000635 case tok::annot_pragma_vis:
636 HandlePragmaVisibility();
637 return DeclGroupPtrTy();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000638 case tok::annot_pragma_pack:
639 HandlePragmaPack();
640 return DeclGroupPtrTy();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000641 case tok::annot_pragma_msstruct:
642 HandlePragmaMSStruct();
643 return DeclGroupPtrTy();
644 case tok::annot_pragma_align:
645 HandlePragmaAlign();
646 return DeclGroupPtrTy();
647 case tok::annot_pragma_weak:
648 HandlePragmaWeak();
649 return DeclGroupPtrTy();
650 case tok::annot_pragma_weakalias:
651 HandlePragmaWeakAlias();
652 return DeclGroupPtrTy();
653 case tok::annot_pragma_redefine_extname:
654 HandlePragmaRedefineExtname();
655 return DeclGroupPtrTy();
656 case tok::annot_pragma_fp_contract:
657 HandlePragmaFPContract();
658 return DeclGroupPtrTy();
659 case tok::annot_pragma_opencl_extension:
660 HandlePragmaOpenCLExtension();
661 return DeclGroupPtrTy();
Reid Spencer5f016e22007-07-11 17:01:13 +0000662 case tok::semi:
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000663 ConsumeExtraSemi(OutsideFunction);
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 // TODO: Invoke action for top-level semicolon.
Chris Lattner682bf922009-03-29 16:50:03 +0000665 return DeclGroupPtrTy();
Chris Lattner90b93d62008-12-08 21:59:01 +0000666 case tok::r_brace:
Nico Weber883692e2012-01-17 01:04:27 +0000667 Diag(Tok, diag::err_extraneous_closing_brace);
Chris Lattner90b93d62008-12-08 21:59:01 +0000668 ConsumeBrace();
Chris Lattner682bf922009-03-29 16:50:03 +0000669 return DeclGroupPtrTy();
Chris Lattner90b93d62008-12-08 21:59:01 +0000670 case tok::eof:
671 Diag(Tok, diag::err_expected_external_declaration);
Chris Lattner682bf922009-03-29 16:50:03 +0000672 return DeclGroupPtrTy();
Chris Lattnerc3018152007-08-10 20:57:02 +0000673 case tok::kw___extension__: {
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000674 // __extension__ silences extension warnings in the subexpression.
675 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner39146d62008-10-20 06:51:33 +0000676 ConsumeToken();
John McCall7f040a92010-12-24 02:08:15 +0000677 return ParseExternalDeclaration(attrs);
Chris Lattnerc3018152007-08-10 20:57:02 +0000678 }
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000679 case tok::kw_asm: {
John McCall7f040a92010-12-24 02:08:15 +0000680 ProhibitAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000681
Abramo Bagnara21e006e2011-03-03 14:20:18 +0000682 SourceLocation StartLoc = Tok.getLocation();
683 SourceLocation EndLoc;
684 ExprResult Result(ParseSimpleAsm(&EndLoc));
Mike Stumpa6f01772008-06-19 19:28:49 +0000685
Anders Carlsson3f9424f2008-02-08 00:23:11 +0000686 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
687 "top-level asm block");
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000688
Chris Lattner682bf922009-03-29 16:50:03 +0000689 if (Result.isInvalid())
690 return DeclGroupPtrTy();
Abramo Bagnara21e006e2011-03-03 14:20:18 +0000691 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
Chris Lattner682bf922009-03-29 16:50:03 +0000692 break;
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000693 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 case tok::at:
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000695 return ParseObjCAtDirectives();
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 case tok::minus:
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 case tok::plus:
David Blaikie4e4d0842012-03-11 07:00:24 +0000698 if (!getLangOpts().ObjC1) {
Chris Lattner682bf922009-03-29 16:50:03 +0000699 Diag(Tok, diag::err_expected_external_declaration);
700 ConsumeToken();
701 return DeclGroupPtrTy();
702 }
703 SingleDecl = ParseObjCMethodDefinition();
704 break;
Douglas Gregor791215b2009-09-21 20:51:25 +0000705 case tok::code_completion:
Douglas Gregor23c94db2010-07-02 17:43:08 +0000706 Actions.CodeCompleteOrdinaryName(getCurScope(),
Argyrios Kyrtzidis849639d2012-02-07 16:50:53 +0000707 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
John McCallf312b1e2010-08-26 23:41:50 +0000708 : Sema::PCC_Namespace);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000709 cutOffParsing();
710 return DeclGroupPtrTy();
Douglas Gregorf780abc2008-12-30 03:27:21 +0000711 case tok::kw_using:
Chris Lattner8f08cb72007-08-25 06:57:03 +0000712 case tok::kw_namespace:
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 case tok::kw_typedef:
Douglas Gregoradcac882008-12-01 23:54:00 +0000714 case tok::kw_template:
715 case tok::kw_export: // As in 'export template'
Anders Carlsson511d7ab2009-03-11 16:27:10 +0000716 case tok::kw_static_assert:
Peter Collingbournec6eb44b2011-04-15 00:35:57 +0000717 case tok::kw__Static_assert:
Chad Rosier26d60232012-04-25 22:51:41 +0000718 // A function definition cannot start with any of these keywords.
Chris Lattner97144fc2009-04-02 04:16:50 +0000719 {
720 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000721 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000722 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000723 }
Sebastian Redld078e642010-08-27 23:12:46 +0000724
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000725 case tok::kw_static:
726 // Parse (then ignore) 'static' prior to a template instantiation. This is
727 // a GCC extension that we intentionally do not support.
David Blaikie4e4d0842012-03-11 07:00:24 +0000728 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000729 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
730 << 0;
Sebastian Redld078e642010-08-27 23:12:46 +0000731 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000732 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000733 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000734 }
735 goto dont_know;
736
737 case tok::kw_inline:
David Blaikie4e4d0842012-03-11 07:00:24 +0000738 if (getLangOpts().CPlusPlus) {
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000739 tok::TokenKind NextKind = NextToken().getKind();
740
741 // Inline namespaces. Allowed as an extension even in C++03.
742 if (NextKind == tok::kw_namespace) {
743 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000744 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000745 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000746 }
747
748 // Parse (then ignore) 'inline' prior to a template instantiation. This is
749 // a GCC extension that we intentionally do not support.
750 if (NextKind == tok::kw_template) {
751 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
752 << 1;
753 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000754 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000755 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000756 }
Sebastian Redld078e642010-08-27 23:12:46 +0000757 }
758 goto dont_know;
759
Douglas Gregor45f96552009-09-04 06:33:52 +0000760 case tok::kw_extern:
David Blaikie4e4d0842012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor45f96552009-09-04 06:33:52 +0000762 // Extern templates
763 SourceLocation ExternLoc = ConsumeToken();
764 SourceLocation TemplateLoc = ConsumeToken();
David Blaikie4e4d0842012-03-11 07:00:24 +0000765 Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
Richard Smith93245832011-10-20 18:35:58 +0000766 diag::warn_cxx98_compat_extern_template :
767 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
Douglas Gregor45f96552009-09-04 06:33:52 +0000768 SourceLocation DeclEnd;
769 return Actions.ConvertDeclToDeclGroup(
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +0000770 ParseExplicitInstantiation(Declarator::FileContext,
771 ExternLoc, TemplateLoc, DeclEnd));
Douglas Gregor45f96552009-09-04 06:33:52 +0000772 }
Douglas Gregor45f96552009-09-04 06:33:52 +0000773 // FIXME: Detect C++ linkage specifications here?
Sebastian Redld078e642010-08-27 23:12:46 +0000774 goto dont_know;
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Francois Pichetf9860382011-05-07 17:30:27 +0000776 case tok::kw___if_exists:
777 case tok::kw___if_not_exists:
Francois Pichet563a6452011-05-25 10:19:49 +0000778 ParseMicrosoftIfExistsExternalDeclaration();
Francois Pichetf9860382011-05-07 17:30:27 +0000779 return DeclGroupPtrTy();
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000780
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 default:
Sebastian Redld078e642010-08-27 23:12:46 +0000782 dont_know:
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 // We can't tell whether this is a function-definition or declaration yet.
John McCall7f040a92010-12-24 02:08:15 +0000784 if (DS) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000785 return ParseDeclarationOrFunctionDefinition(attrs, DS);
John McCall7f040a92010-12-24 02:08:15 +0000786 } else {
787 return ParseDeclarationOrFunctionDefinition(attrs);
788 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattner682bf922009-03-29 16:50:03 +0000791 // This routine returns a DeclGroup, if the thing we parsed only contains a
792 // single decl, convert it now.
793 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000794}
795
Douglas Gregor1426e532009-05-12 21:31:51 +0000796/// \brief Determine whether the current token, if it occurs after a
797/// declarator, continues a declaration or declaration list.
Sean Hunte4246a62011-05-12 06:15:49 +0000798bool Parser::isDeclarationAfterDeclarator() {
799 // Check for '= delete' or '= default'
David Blaikie4e4d0842012-03-11 07:00:24 +0000800 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Sean Hunte4246a62011-05-12 06:15:49 +0000801 const Token &KW = NextToken();
802 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
803 return false;
804 }
Fariborz Jahanian6c89eaf2012-07-02 23:37:09 +0000805
Douglas Gregor1426e532009-05-12 21:31:51 +0000806 return Tok.is(tok::equal) || // int X()= -> not a function def
807 Tok.is(tok::comma) || // int X(), -> not a function def
808 Tok.is(tok::semi) || // int X(); -> not a function def
809 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
810 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
David Blaikie4e4d0842012-03-11 07:00:24 +0000811 (getLangOpts().CPlusPlus &&
Fariborz Jahanian39700f82012-07-05 19:34:20 +0000812 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
Douglas Gregor1426e532009-05-12 21:31:51 +0000813}
814
815/// \brief Determine whether the current token, if it occurs after a
816/// declarator, indicates the start of a function definition.
Chris Lattner004659a2010-07-11 22:42:07 +0000817bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000818 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
Chris Lattner5d1c6192009-12-06 18:34:27 +0000819 if (Tok.is(tok::l_brace)) // int X() {}
820 return true;
821
Chris Lattner004659a2010-07-11 22:42:07 +0000822 // Handle K&R C argument lists: int X(f) int f; {}
David Blaikie4e4d0842012-03-11 07:00:24 +0000823 if (!getLangOpts().CPlusPlus &&
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000824 Declarator.getFunctionTypeInfo().isKNRPrototype())
Chris Lattner004659a2010-07-11 22:42:07 +0000825 return isDeclarationSpecifier();
Sean Hunte4246a62011-05-12 06:15:49 +0000826
David Blaikie4e4d0842012-03-11 07:00:24 +0000827 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Sean Hunte4246a62011-05-12 06:15:49 +0000828 const Token &KW = NextToken();
829 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
830 }
Chris Lattner004659a2010-07-11 22:42:07 +0000831
Chris Lattner5d1c6192009-12-06 18:34:27 +0000832 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
833 Tok.is(tok::kw_try); // X() try { ... }
Douglas Gregor1426e532009-05-12 21:31:51 +0000834}
835
Reid Spencer5f016e22007-07-11 17:01:13 +0000836/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
837/// a declaration. We can't tell which we have until we read up to the
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000838/// compound-statement in function-definition. TemplateParams, if
839/// non-NULL, provides the template parameters when we're parsing a
Mike Stump1eb44332009-09-09 15:08:12 +0000840/// C++ template-declaration.
Reid Spencer5f016e22007-07-11 17:01:13 +0000841///
842/// function-definition: [C99 6.9.1]
Chris Lattnera798ebc2008-04-05 05:52:15 +0000843/// decl-specs declarator declaration-list[opt] compound-statement
844/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000845/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattnera798ebc2008-04-05 05:52:15 +0000846///
Reid Spencer5f016e22007-07-11 17:01:13 +0000847/// declaration: [C99 6.7]
Chris Lattner697e15f2007-08-22 06:06:56 +0000848/// declaration-specifiers init-declarator-list[opt] ';'
849/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Reid Spencer5f016e22007-07-11 17:01:13 +0000850/// [OMP] threadprivate-directive [TODO]
851///
Chris Lattner682bf922009-03-29 16:50:03 +0000852Parser::DeclGroupPtrTy
Sean Hunt2edf0a22012-06-23 05:07:58 +0000853Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
854 ParsingDeclSpec &DS,
855 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 // Parse the common declaration-specifiers piece.
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000857 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
Mike Stumpa6f01772008-06-19 19:28:49 +0000858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
860 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner00073222007-10-09 17:23:58 +0000861 if (Tok.is(tok::semi)) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000862 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000864 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000865 DS.complete(TheDecl);
Chris Lattner682bf922009-03-29 16:50:03 +0000866 return Actions.ConvertDeclToDeclGroup(TheDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000868
Sean Hunt2edf0a22012-06-23 05:07:58 +0000869 DS.takeAttributesFrom(attrs);
870
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000871 // ObjC2 allows prefix attributes on class interfaces and protocols.
872 // FIXME: This still needs better diagnostics. We should only accept
873 // attributes here, no types, etc.
David Blaikie4e4d0842012-03-11 07:00:24 +0000874 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
Steve Naroffdac269b2007-08-20 21:31:48 +0000875 SourceLocation AtLoc = ConsumeToken(); // the "@"
Mike Stump1eb44332009-09-09 15:08:12 +0000876 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000877 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
878 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattnercb53b362007-12-27 19:57:00 +0000879 SkipUntil(tok::semi); // FIXME: better skip?
Chris Lattner682bf922009-03-29 16:50:03 +0000880 return DeclGroupPtrTy();
Chris Lattnercb53b362007-12-27 19:57:00 +0000881 }
John McCalld8ac0572009-11-03 19:26:08 +0000882
John McCall54abf7d2009-11-04 02:18:39 +0000883 DS.abort();
884
Fariborz Jahanian0de2ae22008-01-02 19:17:38 +0000885 const char *PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +0000886 unsigned DiagID;
887 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
888 Diag(AtLoc, DiagID) << PrevSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000890 if (Tok.isObjCAtKeyword(tok::objc_protocol))
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000891 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
892
893 return Actions.ConvertDeclToDeclGroup(
894 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
Steve Naroffdac269b2007-08-20 21:31:48 +0000895 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000896
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000897 // If the declspec consisted only of 'extern' and we have a string
898 // literal following it, this must be a C++ linkage specifier like
899 // 'extern "C"'.
David Blaikie4e4d0842012-03-11 07:00:24 +0000900 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000901 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
Chris Lattner682bf922009-03-29 16:50:03 +0000902 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
John McCalld226f652010-08-21 09:40:31 +0000903 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
Chris Lattner682bf922009-03-29 16:50:03 +0000904 return Actions.ConvertDeclToDeclGroup(TheDecl);
905 }
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000906
John McCalld8ac0572009-11-03 19:26:08 +0000907 return ParseDeclGroup(DS, Declarator::FileContext, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000908}
909
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000910Parser::DeclGroupPtrTy
Sean Hunt2edf0a22012-06-23 05:07:58 +0000911Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
912 ParsingDeclSpec *DS,
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000913 AccessSpecifier AS) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000914 if (DS) {
915 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
916 } else {
917 ParsingDeclSpec PDS(*this);
918 // Must temporarily exit the objective-c container scope for
919 // parsing c constructs and re-enter objc container scope
920 // afterwards.
921 ObjCDeclContextSwitch ObjCDC(*this);
922
923 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
924 }
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000925}
926
Reid Spencer5f016e22007-07-11 17:01:13 +0000927/// ParseFunctionDefinition - We parsed and verified that the specified
928/// Declarator is well formed. If this is a K&R-style function, read the
929/// parameters declaration-list, then start the compound-statement.
930///
Chris Lattnera798ebc2008-04-05 05:52:15 +0000931/// function-definition: [C99 6.9.1]
932/// decl-specs declarator declaration-list[opt] compound-statement
933/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000934/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregor7ad83902008-11-05 04:29:56 +0000935/// [C++] function-definition: [C++ 8.4]
Chris Lattner23c4b182009-03-29 17:18:04 +0000936/// decl-specifier-seq[opt] declarator ctor-initializer[opt]
937/// function-body
Douglas Gregor7ad83902008-11-05 04:29:56 +0000938/// [C++] function-definition: [C++ 8.4]
Sebastian Redld3a413d2009-04-26 20:35:05 +0000939/// decl-specifier-seq[opt] declarator function-try-block
Reid Spencer5f016e22007-07-11 17:01:13 +0000940///
John McCalld226f652010-08-21 09:40:31 +0000941Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000942 const ParsedTemplateInfo &TemplateInfo,
943 LateParsedAttrList *LateParsedAttrs) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000944 // Poison the SEH identifiers so they are flagged as illegal in function bodies
945 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000946 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stumpa6f01772008-06-19 19:28:49 +0000947
Chris Lattnera798ebc2008-04-05 05:52:15 +0000948 // If this is C90 and the declspecs were completely missing, fudge in an
949 // implicit int. We do this here because this is the only place where
950 // declaration-specifiers are completely optional in the grammar.
David Blaikie4e4d0842012-03-11 07:00:24 +0000951 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
Chris Lattnera798ebc2008-04-05 05:52:15 +0000952 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +0000953 unsigned DiagID;
Chris Lattner31c28682008-10-20 02:01:34 +0000954 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
955 D.getIdentifierLoc(),
John McCallfec54012009-08-03 20:12:06 +0000956 PrevSpec, DiagID);
Sebastian Redlab197ba2009-02-09 18:23:29 +0000957 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattnera798ebc2008-04-05 05:52:15 +0000958 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000959
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 // If this declaration was formed with a K&R-style identifier list for the
961 // arguments, parse declarations for all of the args next.
962 // int foo(a,b) int a; float b; {}
Chris Lattner004659a2010-07-11 22:42:07 +0000963 if (FTI.isKNRPrototype())
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 ParseKNRParamDeclarations(D);
965
Douglas Gregor7ad83902008-11-05 04:29:56 +0000966 // We should have either an opening brace or, in a C++ constructor,
967 // we may have a colon.
Douglas Gregor758afbc2011-02-04 11:57:16 +0000968 if (Tok.isNot(tok::l_brace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000969 (!getLangOpts().CPlusPlus ||
Sean Huntcd10dec2011-05-23 23:14:04 +0000970 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
971 Tok.isNot(tok::equal)))) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 Diag(Tok, diag::err_expected_fn_body);
973
974 // Skip over garbage, until we get to '{'. Don't eat the '{'.
975 SkipUntil(tok::l_brace, true, true);
Mike Stumpa6f01772008-06-19 19:28:49 +0000976
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 // If we didn't find the '{', bail out.
Chris Lattner00073222007-10-09 17:23:58 +0000978 if (Tok.isNot(tok::l_brace))
John McCalld226f652010-08-21 09:40:31 +0000979 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000981
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000982 // Check to make sure that any normal attributes are allowed to be on
983 // a definition. Late parsed attributes are checked at the end.
984 if (Tok.isNot(tok::equal)) {
985 AttributeList *DtorAttrs = D.getAttributes();
986 while (DtorAttrs) {
987 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
988 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
989 << DtorAttrs->getName()->getName();
990 }
991 DtorAttrs = DtorAttrs->getNext();
992 }
993 }
994
Francois Pichet8387e2a2011-04-22 22:18:13 +0000995 // In delayed template parsing mode, for function template we consume the
996 // tokens and store them for late parsing at the end of the translation unit.
David Blaikie4e4d0842012-03-11 07:00:24 +0000997 if (getLangOpts().DelayedTemplateParsing &&
Douglas Gregor09630172012-06-28 21:43:01 +0000998 Tok.isNot(tok::equal) &&
Francois Pichet8387e2a2011-04-22 22:18:13 +0000999 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00001000 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001001
1002 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1003 Scope *ParentScope = getCurScope()->getParent();
1004
Douglas Gregor45fa5602011-11-07 20:56:01 +00001005 D.setFunctionDefinitionKind(FDK_Definition);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001006 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001007 TemplateParameterLists);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001008 D.complete(DP);
1009 D.getMutableDeclSpec().abort();
1010
1011 if (DP) {
Francois Pichete1fca502011-12-08 09:11:52 +00001012 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001013
1014 FunctionDecl *FnD = 0;
1015 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1016 FnD = FunTmpl->getTemplatedDecl();
1017 else
1018 FnD = cast<FunctionDecl>(DP);
Francois Pichetd4a0caf2011-04-22 23:20:44 +00001019 Actions.CheckForFunctionRedefinition(FnD);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001020
1021 LateParsedTemplateMap[FnD] = LPT;
1022 Actions.MarkAsLateParsedTemplate(FnD);
1023 LexTemplateFunctionForLateParsing(LPT->Toks);
1024 } else {
1025 CachedTokens Toks;
1026 LexTemplateFunctionForLateParsing(Toks);
1027 }
1028 return DP;
1029 }
Fariborz Jahanian2eb362b2012-08-10 18:10:56 +00001030 else if (CurParsedObjCImpl &&
Fariborz Jahanian9e5df312012-08-10 21:15:06 +00001031 !TemplateInfo.TemplateParams &&
1032 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1033 Tok.is(tok::colon)) &&
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001034 Actions.CurContext->isTranslationUnit()) {
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001035 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1036 Scope *ParentScope = getCurScope()->getParent();
1037
1038 D.setFunctionDefinitionKind(FDK_Definition);
1039 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramer5354e772012-08-23 23:38:35 +00001040 MultiTemplateParamsArg());
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001041 D.complete(FuncDecl);
1042 D.getMutableDeclSpec().abort();
1043 if (FuncDecl) {
1044 // Consume the tokens and store them for later parsing.
1045 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1046 CurParsedObjCImpl->HasCFunction = true;
1047 return FuncDecl;
1048 }
1049 }
1050
Chris Lattnerb652cea2007-10-09 17:14:05 +00001051 // Enter a scope for the function body.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001052 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stumpa6f01772008-06-19 19:28:49 +00001053
Chris Lattnerb652cea2007-10-09 17:14:05 +00001054 // Tell the actions module that we have entered a function definition with the
1055 // specified Declarator for the function.
John McCalld226f652010-08-21 09:40:31 +00001056 Decl *Res = TemplateInfo.TemplateParams?
Douglas Gregor23c94db2010-07-02 17:43:08 +00001057 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00001058 *TemplateInfo.TemplateParams, D)
Douglas Gregor23c94db2010-07-02 17:43:08 +00001059 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
Mike Stumpa6f01772008-06-19 19:28:49 +00001060
John McCall54abf7d2009-11-04 02:18:39 +00001061 // Break out of the ParsingDeclarator context before we parse the body.
1062 D.complete(Res);
1063
1064 // Break out of the ParsingDeclSpec context, too. This const_cast is
1065 // safe because we're always the sole owner.
1066 D.getMutableDeclSpec().abort();
1067
Sean Huntcd10dec2011-05-23 23:14:04 +00001068 if (Tok.is(tok::equal)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001069 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
Sean Huntcd10dec2011-05-23 23:14:04 +00001070 ConsumeToken();
1071
1072 Actions.ActOnFinishFunctionBody(Res, 0, false);
1073
1074 bool Delete = false;
1075 SourceLocation KWLoc;
1076 if (Tok.is(tok::kw_delete)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001077 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001078 diag::warn_cxx98_compat_deleted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +00001079 diag::ext_deleted_function);
Sean Huntcd10dec2011-05-23 23:14:04 +00001080
1081 KWLoc = ConsumeToken();
1082 Actions.SetDeclDeleted(Res, KWLoc);
1083 Delete = true;
1084 } else if (Tok.is(tok::kw_default)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001085 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001086 diag::warn_cxx98_compat_defaulted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +00001087 diag::ext_defaulted_function);
Sean Huntcd10dec2011-05-23 23:14:04 +00001088
1089 KWLoc = ConsumeToken();
1090 Actions.SetDeclDefaulted(Res, KWLoc);
1091 } else {
1092 llvm_unreachable("function definition after = not 'delete' or 'default'");
1093 }
1094
1095 if (Tok.is(tok::comma)) {
1096 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1097 << Delete;
1098 SkipUntil(tok::semi);
1099 } else {
1100 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1101 Delete ? "delete" : "default", tok::semi);
1102 }
1103
1104 return Res;
1105 }
1106
Sebastian Redld3a413d2009-04-26 20:35:05 +00001107 if (Tok.is(tok::kw_try))
Douglas Gregorc9977d02011-03-16 17:05:57 +00001108 return ParseFunctionTryBlock(Res, BodyScope);
Sebastian Redld3a413d2009-04-26 20:35:05 +00001109
Douglas Gregor7ad83902008-11-05 04:29:56 +00001110 // If we have a colon, then we're probably parsing a C++
1111 // ctor-initializer.
John McCalld6ca8da2010-04-10 07:37:23 +00001112 if (Tok.is(tok::colon)) {
Douglas Gregor7ad83902008-11-05 04:29:56 +00001113 ParseConstructorInitializer(Res);
John McCalld6ca8da2010-04-10 07:37:23 +00001114
1115 // Recover from error.
1116 if (!Tok.is(tok::l_brace)) {
Douglas Gregorc9977d02011-03-16 17:05:57 +00001117 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001118 Actions.ActOnFinishFunctionBody(Res, 0);
John McCalld6ca8da2010-04-10 07:37:23 +00001119 return Res;
1120 }
1121 } else
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001122 Actions.ActOnDefaultCtorInitializers(Res);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001123
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +00001124 // Late attributes are parsed in the same scope as the function body.
1125 if (LateParsedAttrs)
1126 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1127
Douglas Gregorc9977d02011-03-16 17:05:57 +00001128 return ParseFunctionStatementBody(Res, BodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129}
1130
1131/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1132/// types for a function with a K&R-style identifier list for arguments.
1133void Parser::ParseKNRParamDeclarations(Declarator &D) {
1134 // We know that the top-level of this declarator is a function.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001135 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001136
Chris Lattner04421082008-04-08 04:40:51 +00001137 // Enter function-declaration scope, limiting any declarators to the
1138 // function prototype scope, including parameter declarators.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00001139 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattner04421082008-04-08 04:40:51 +00001140
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 // Read all the argument declarations.
1142 while (isDeclarationSpecifier()) {
1143 SourceLocation DSStart = Tok.getLocation();
Mike Stumpa6f01772008-06-19 19:28:49 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // Parse the common declaration-specifiers piece.
John McCall0b7e6782011-03-24 11:26:52 +00001146 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 ParseDeclarationSpecifiers(DS);
Mike Stumpa6f01772008-06-19 19:28:49 +00001148
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1150 // least one declarator'.
1151 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1152 // the declarations though. It's trivial to ignore them, really hard to do
1153 // anything else with them.
Chris Lattner00073222007-10-09 17:23:58 +00001154 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1156 ConsumeToken();
1157 continue;
1158 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1161 // than register.
1162 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1163 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1164 Diag(DS.getStorageClassSpecLoc(),
1165 diag::err_invalid_storage_class_in_func_decl);
1166 DS.ClearStorageClassSpecs();
1167 }
1168 if (DS.isThreadSpecified()) {
1169 Diag(DS.getThreadSpecLoc(),
1170 diag::err_invalid_storage_class_in_func_decl);
1171 DS.ClearStorageClassSpecs();
1172 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001173
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 // Parse the first declarator attached to this declspec.
1175 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1176 ParseDeclarator(ParmDeclarator);
1177
1178 // Handle the full declarator list.
1179 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001181 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stumpa6f01772008-06-19 19:28:49 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // Ask the actions module to compute the type for this declarator.
John McCalld226f652010-08-21 09:40:31 +00001184 Decl *Param =
Douglas Gregor23c94db2010-07-02 17:43:08 +00001185 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Steve Naroff2bd42fa2007-09-10 20:51:04 +00001186
Mike Stumpa6f01772008-06-19 19:28:49 +00001187 if (Param &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 // A missing identifier has already been diagnosed.
1189 ParmDeclarator.getIdentifier()) {
1190
1191 // Scan the argument list looking for the correct param to apply this
1192 // type.
1193 for (unsigned i = 0; ; ++i) {
1194 // C99 6.9.1p6: those declarators shall declare only identifiers from
1195 // the identifier list.
1196 if (i == FTI.NumArgs) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001197 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattner6898e332008-11-19 07:51:13 +00001198 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 break;
1200 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1203 // Reject redefinitions of parameters.
Chris Lattner04421082008-04-08 04:40:51 +00001204 if (FTI.ArgInfo[i].Param) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattner1ab3b962008-11-18 07:48:38 +00001206 diag::err_param_redefinition)
Chris Lattner6898e332008-11-19 07:51:13 +00001207 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001209 FTI.ArgInfo[i].Param = Param;
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 }
1211 break;
1212 }
1213 }
1214 }
1215
1216 // If we don't have a comma, it is either the end of the list (a ';') or
1217 // an error, bail out.
Chris Lattner00073222007-10-09 17:23:58 +00001218 if (Tok.isNot(tok::comma))
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 break;
Mike Stumpa6f01772008-06-19 19:28:49 +00001220
Richard Smith7984de32012-01-12 23:53:29 +00001221 ParmDeclarator.clear();
1222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 // Consume the comma.
Richard Smith7984de32012-01-12 23:53:29 +00001224 ParmDeclarator.setCommaLoc(ConsumeToken());
Mike Stumpa6f01772008-06-19 19:28:49 +00001225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 // Parse the next declarator.
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 ParseDeclarator(ParmDeclarator);
1228 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001229
Chris Lattner8bb21d32012-04-28 16:12:17 +00001230 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 // Skip to end of block or statement
1232 SkipUntil(tok::semi, true);
Chris Lattner00073222007-10-09 17:23:58 +00001233 if (Tok.is(tok::semi))
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 ConsumeToken();
1235 }
1236 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001237
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 // The actions module must verify that all arguments were declared.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001239 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001240}
1241
1242
1243/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1244/// allowed to be a wide string, and is not subject to character translation.
1245///
1246/// [GNU] asm-string-literal:
1247/// string-literal
1248///
John McCall60d7b3a2010-08-24 06:29:42 +00001249Parser::ExprResult Parser::ParseAsmStringLiteral() {
Ted Kremenek7f422282011-12-02 00:35:46 +00001250 switch (Tok.getKind()) {
1251 case tok::string_literal:
1252 break;
Richard Smith99831e42012-03-06 03:21:47 +00001253 case tok::utf8_string_literal:
1254 case tok::utf16_string_literal:
1255 case tok::utf32_string_literal:
Ted Kremenek7f422282011-12-02 00:35:46 +00001256 case tok::wide_string_literal: {
1257 SourceLocation L = Tok.getLocation();
1258 Diag(Tok, diag::err_asm_operand_wide_string_literal)
Richard Smith99831e42012-03-06 03:21:47 +00001259 << (Tok.getKind() == tok::wide_string_literal)
Ted Kremenek7f422282011-12-02 00:35:46 +00001260 << SourceRange(L, L);
1261 return ExprError();
1262 }
1263 default:
1264 Diag(Tok, diag::err_expected_string_literal);
1265 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001267
Richard Smith99831e42012-03-06 03:21:47 +00001268 return ParseStringLiteralExpression();
Reid Spencer5f016e22007-07-11 17:01:13 +00001269}
1270
1271/// ParseSimpleAsm
1272///
1273/// [GNU] simple-asm-expr:
1274/// 'asm' '(' asm-string-literal ')'
1275///
John McCall60d7b3a2010-08-24 06:29:42 +00001276Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner00073222007-10-09 17:23:58 +00001277 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001278 SourceLocation Loc = ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +00001279
John McCall7a6ae742010-01-25 22:27:48 +00001280 if (Tok.is(tok::kw_volatile)) {
John McCall841d5e62010-01-25 23:12:50 +00001281 // Remove from the end of 'asm' to the end of 'volatile'.
1282 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1283 PP.getLocForEndOfToken(Tok.getLocation()));
1284
1285 Diag(Tok, diag::warn_file_asm_volatile)
Douglas Gregor849b2432010-03-31 17:46:05 +00001286 << FixItHint::CreateRemoval(RemovalRange);
John McCall7a6ae742010-01-25 22:27:48 +00001287 ConsumeToken();
1288 }
1289
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001290 BalancedDelimiterTracker T(*this, tok::l_paren);
1291 if (T.consumeOpen()) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001292 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl61364dd2008-12-11 19:30:53 +00001293 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001295
John McCall60d7b3a2010-08-24 06:29:42 +00001296 ExprResult Result(ParseAsmStringLiteral());
Mike Stumpa6f01772008-06-19 19:28:49 +00001297
Sebastian Redlab197ba2009-02-09 18:23:29 +00001298 if (Result.isInvalid()) {
1299 SkipUntil(tok::r_paren, true, true);
1300 if (EndLoc)
1301 *EndLoc = Tok.getLocation();
1302 ConsumeAnyToken();
1303 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001304 // Close the paren and get the location of the end bracket
1305 T.consumeClose();
Sebastian Redlab197ba2009-02-09 18:23:29 +00001306 if (EndLoc)
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001307 *EndLoc = T.getCloseLocation();
Sebastian Redlab197ba2009-02-09 18:23:29 +00001308 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001309
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001310 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00001311}
1312
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001313/// \brief Get the TemplateIdAnnotation from the token and put it in the
1314/// cleanup pool so that it gets destroyed when parsing the current top level
1315/// declaration is finished.
1316TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1317 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1318 TemplateIdAnnotation *
1319 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001320 return Id;
1321}
1322
Richard Smith05766812012-08-18 00:55:03 +00001323void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1324 // Push the current token back into the token stream (or revert it if it is
1325 // cached) and use an annotation scope token for current token.
1326 if (PP.isBacktrackEnabled())
1327 PP.RevertCachedTokens(1);
1328 else
1329 PP.EnterToken(Tok);
1330 Tok.setKind(tok::annot_cxxscope);
1331 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1332 Tok.setAnnotationRange(SS.getRange());
1333
1334 // In case the tokens were cached, have Preprocessor replace them
1335 // with the annotation token. We don't need to do this if we've
1336 // just reverted back to a prior state.
1337 if (IsNewAnnotation)
1338 PP.AnnotateCachedTokens(Tok);
1339}
1340
1341/// \brief Attempt to classify the name at the current token position. This may
1342/// form a type, scope or primary expression annotation, or replace the token
1343/// with a typo-corrected keyword. This is only appropriate when the current
1344/// name must refer to an entity which has already been declared.
1345///
1346/// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1347/// and might possibly have a dependent nested name specifier.
1348/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1349/// no typo correction will be performed.
1350Parser::AnnotatedNameKind
1351Parser::TryAnnotateName(bool IsAddressOfOperand,
1352 CorrectionCandidateCallback *CCC) {
1353 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1354
1355 const bool EnteringContext = false;
1356 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1357
1358 CXXScopeSpec SS;
1359 if (getLangOpts().CPlusPlus &&
1360 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1361 return ANK_Error;
1362
1363 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1364 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1365 !WasScopeAnnotation))
1366 return ANK_Error;
1367 return ANK_Unresolved;
1368 }
1369
1370 IdentifierInfo *Name = Tok.getIdentifierInfo();
1371 SourceLocation NameLoc = Tok.getLocation();
1372
1373 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1374 // typo-correct to tentatively-declared identifiers.
1375 if (isTentativelyDeclared(Name)) {
1376 // Identifier has been tentatively declared, and thus cannot be resolved as
1377 // an expression. Fall back to annotating it as a type.
1378 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1379 !WasScopeAnnotation))
1380 return ANK_Error;
1381 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1382 }
1383
1384 Token Next = NextToken();
1385
1386 // Look up and classify the identifier. We don't perform any typo-correction
1387 // after a scope specifier, because in general we can't recover from typos
1388 // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1389 // back into scope specifier parsing).
1390 Sema::NameClassification Classification
1391 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1392 IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1393
1394 switch (Classification.getKind()) {
1395 case Sema::NC_Error:
1396 return ANK_Error;
1397
1398 case Sema::NC_Keyword:
1399 // The identifier was typo-corrected to a keyword.
1400 Tok.setIdentifierInfo(Name);
1401 Tok.setKind(Name->getTokenID());
1402 PP.TypoCorrectToken(Tok);
1403 if (SS.isNotEmpty())
1404 AnnotateScopeToken(SS, !WasScopeAnnotation);
1405 // We've "annotated" this as a keyword.
1406 return ANK_Success;
1407
1408 case Sema::NC_Unknown:
1409 // It's not something we know about. Leave it unannotated.
1410 break;
1411
1412 case Sema::NC_Type:
1413 Tok.setKind(tok::annot_typename);
1414 setTypeAnnotation(Tok, Classification.getType());
1415 Tok.setAnnotationEndLoc(NameLoc);
1416 if (SS.isNotEmpty())
1417 Tok.setLocation(SS.getBeginLoc());
1418 PP.AnnotateCachedTokens(Tok);
1419 return ANK_Success;
1420
1421 case Sema::NC_Expression:
1422 Tok.setKind(tok::annot_primary_expr);
1423 setExprAnnotation(Tok, Classification.getExpression());
1424 Tok.setAnnotationEndLoc(NameLoc);
1425 if (SS.isNotEmpty())
1426 Tok.setLocation(SS.getBeginLoc());
1427 PP.AnnotateCachedTokens(Tok);
1428 return ANK_Success;
1429
1430 case Sema::NC_TypeTemplate:
1431 if (Next.isNot(tok::less)) {
1432 // This may be a type template being used as a template template argument.
1433 if (SS.isNotEmpty())
1434 AnnotateScopeToken(SS, !WasScopeAnnotation);
1435 return ANK_TemplateName;
1436 }
1437 // Fall through.
1438 case Sema::NC_FunctionTemplate: {
1439 // We have a type or function template followed by '<'.
1440 ConsumeToken();
1441 UnqualifiedId Id;
1442 Id.setIdentifier(Name, NameLoc);
1443 if (AnnotateTemplateIdToken(
1444 TemplateTy::make(Classification.getTemplateName()),
1445 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1446 return ANK_Error;
1447 return ANK_Success;
1448 }
1449
1450 case Sema::NC_NestedNameSpecifier:
1451 llvm_unreachable("already parsed nested name specifier");
1452 }
1453
1454 // Unable to classify the name, but maybe we can annotate a scope specifier.
1455 if (SS.isNotEmpty())
1456 AnnotateScopeToken(SS, !WasScopeAnnotation);
1457 return ANK_Unresolved;
1458}
1459
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001460/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1461/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1462/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1463/// with a single annotation token representing the typename or C++ scope
1464/// respectively.
1465/// This simplifies handling of C++ scope specifiers and allows efficient
1466/// backtracking without the need to re-parse and resolve nested-names and
1467/// typenames.
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +00001468/// It will mainly be called when we expect to treat identifiers as typenames
1469/// (if they are typenames). For example, in C we do not expect identifiers
1470/// inside expressions to be treated as typenames so it will not be called
1471/// for expressions in C.
1472/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroffb43a50f2009-01-28 19:39:02 +00001473/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +00001474/// will not be called twice, once to check whether we have a declaration
1475/// specifier, and another one to get the actual type inside
1476/// ParseDeclarationSpecifiers).
Chris Lattnera7bc7c82009-01-04 23:23:14 +00001477///
John McCall9ba61662010-02-26 08:45:28 +00001478/// This returns true if an error occurred.
Mike Stump1eb44332009-09-09 15:08:12 +00001479///
Chris Lattner55a7cef2009-01-05 00:13:00 +00001480/// Note that this routine emits an error if you call it with ::new or ::delete
1481/// as the current tokens, so only call it in contexts where these are invalid.
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001482bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001483 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
David Blaikie42d6d0c2011-12-04 05:04:18 +00001484 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
Richard Smith23756772012-05-14 22:43:34 +00001485 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1486 && "Cannot be a type or scope token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Douglas Gregord57959a2009-03-27 23:10:48 +00001488 if (Tok.is(tok::kw_typename)) {
1489 // Parse a C++ typename-specifier, e.g., "typename T::type".
1490 //
1491 // typename-specifier:
1492 // 'typename' '::' [opt] nested-name-specifier identifier
Mike Stump1eb44332009-09-09 15:08:12 +00001493 // 'typename' '::' [opt] nested-name-specifier template [opt]
Douglas Gregor17343172009-04-01 00:28:59 +00001494 // simple-template-id
Douglas Gregord57959a2009-03-27 23:10:48 +00001495 SourceLocation TypenameLoc = ConsumeToken();
1496 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +00001497 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1498 /*EnteringContext=*/false,
Francois Pichet4147d302011-03-27 19:41:34 +00001499 0, /*IsTypename*/true))
John McCall9ba61662010-02-26 08:45:28 +00001500 return true;
1501 if (!SS.isSet()) {
Francois Pichetb67e7fc2012-07-22 15:10:57 +00001502 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1503 Tok.is(tok::annot_decltype)) {
Richard Smith23756772012-05-14 22:43:34 +00001504 // Attempt to recover by skipping the invalid 'typename'
Francois Pichetb67e7fc2012-07-22 15:10:57 +00001505 if (Tok.is(tok::annot_decltype) ||
1506 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1507 Tok.isAnnotation())) {
Richard Smith23756772012-05-14 22:43:34 +00001508 unsigned DiagID = diag::err_expected_qualified_after_typename;
1509 // MS compatibility: MSVC permits using known types with typename.
1510 // e.g. "typedef typename T* pointer_type"
1511 if (getLangOpts().MicrosoftExt)
1512 DiagID = diag::warn_expected_qualified_after_typename;
1513 Diag(Tok.getLocation(), DiagID);
1514 return false;
1515 }
1516 }
1517
1518 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
John McCall9ba61662010-02-26 08:45:28 +00001519 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00001520 }
1521
1522 TypeResult Ty;
1523 if (Tok.is(tok::identifier)) {
1524 // FIXME: check whether the next token is '<', first!
Douglas Gregor23c94db2010-07-02 17:43:08 +00001525 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001526 *Tok.getIdentifierInfo(),
Douglas Gregord57959a2009-03-27 23:10:48 +00001527 Tok.getLocation());
Douglas Gregor17343172009-04-01 00:28:59 +00001528 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001529 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor17343172009-04-01 00:28:59 +00001530 if (TemplateId->Kind == TNK_Function_template) {
1531 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1532 << Tok.getAnnotationRange();
John McCall9ba61662010-02-26 08:45:28 +00001533 return true;
Douglas Gregor17343172009-04-01 00:28:59 +00001534 }
Douglas Gregord57959a2009-03-27 23:10:48 +00001535
Benjamin Kramer5354e772012-08-23 23:38:35 +00001536 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregora02411e2011-02-27 22:46:49 +00001537 TemplateId->NumArgs);
Abramo Bagnara66581d42012-02-06 22:45:07 +00001538
Douglas Gregora02411e2011-02-27 22:46:49 +00001539 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Abramo Bagnara66581d42012-02-06 22:45:07 +00001540 TemplateId->TemplateKWLoc,
Douglas Gregora02411e2011-02-27 22:46:49 +00001541 TemplateId->Template,
1542 TemplateId->TemplateNameLoc,
1543 TemplateId->LAngleLoc,
Abramo Bagnara66581d42012-02-06 22:45:07 +00001544 TemplateArgsPtr,
Douglas Gregora02411e2011-02-27 22:46:49 +00001545 TemplateId->RAngleLoc);
Douglas Gregor17343172009-04-01 00:28:59 +00001546 } else {
1547 Diag(Tok, diag::err_expected_type_name_after_typename)
1548 << SS.getRange();
John McCall9ba61662010-02-26 08:45:28 +00001549 return true;
Douglas Gregor17343172009-04-01 00:28:59 +00001550 }
1551
Sebastian Redl39d67112010-02-08 19:35:18 +00001552 SourceLocation EndLoc = Tok.getLastLoc();
Douglas Gregor17343172009-04-01 00:28:59 +00001553 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +00001554 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
Sebastian Redl39d67112010-02-08 19:35:18 +00001555 Tok.setAnnotationEndLoc(EndLoc);
Douglas Gregor17343172009-04-01 00:28:59 +00001556 Tok.setLocation(TypenameLoc);
1557 PP.AnnotateCachedTokens(Tok);
John McCall9ba61662010-02-26 08:45:28 +00001558 return false;
Douglas Gregord57959a2009-03-27 23:10:48 +00001559 }
1560
John McCallae03cb52009-12-19 00:35:18 +00001561 // Remembers whether the token was originally a scope annotation.
Richard Smith05766812012-08-18 00:55:03 +00001562 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
John McCallae03cb52009-12-19 00:35:18 +00001563
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001564 CXXScopeSpec SS;
David Blaikie4e4d0842012-03-11 07:00:24 +00001565 if (getLangOpts().CPlusPlus)
John McCallb3d87482010-08-24 05:47:05 +00001566 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall9ba61662010-02-26 08:45:28 +00001567 return true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001568
Richard Smith05766812012-08-18 00:55:03 +00001569 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1570 SS, !WasScopeAnnotation);
1571}
1572
1573/// \brief Try to annotate a type or scope token, having already parsed an
1574/// optional scope specifier. \p IsNewScope should be \c true unless the scope
1575/// specifier was extracted from an existing tok::annot_cxxscope annotation.
1576bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1577 bool NeedType,
1578 CXXScopeSpec &SS,
1579 bool IsNewScope) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001580 if (Tok.is(tok::identifier)) {
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001581 IdentifierInfo *CorrectedII = 0;
Chris Lattner608d1fc2009-01-05 01:49:50 +00001582 // Determine whether the identifier is a type name.
John McCallb3d87482010-08-24 05:47:05 +00001583 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1584 Tok.getLocation(), getCurScope(),
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00001585 &SS, false,
Douglas Gregor9e876872011-03-01 18:12:44 +00001586 NextToken().is(tok::period),
1587 ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +00001588 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001589 /*NonTrivialTypeSourceInfo*/true,
1590 NeedType ? &CorrectedII : NULL)) {
1591 // A FixIt was applied as a result of typo correction
1592 if (CorrectedII)
1593 Tok.setIdentifierInfo(CorrectedII);
Chris Lattner608d1fc2009-01-05 01:49:50 +00001594 // This is a typename. Replace the current token in-place with an
1595 // annotation type token.
Chris Lattnerb31757b2009-01-06 05:06:21 +00001596 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +00001597 setTypeAnnotation(Tok, Ty);
Chris Lattner608d1fc2009-01-05 01:49:50 +00001598 Tok.setAnnotationEndLoc(Tok.getLocation());
1599 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1600 Tok.setLocation(SS.getBeginLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattner608d1fc2009-01-05 01:49:50 +00001602 // In case the tokens were cached, have Preprocessor replace
1603 // them with the annotation token.
1604 PP.AnnotateCachedTokens(Tok);
John McCall9ba61662010-02-26 08:45:28 +00001605 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001606 }
Douglas Gregor39a8de12009-02-25 19:37:18 +00001607
David Blaikie4e4d0842012-03-11 07:00:24 +00001608 if (!getLangOpts().CPlusPlus) {
Chris Lattner608d1fc2009-01-05 01:49:50 +00001609 // If we're in C, we can't have :: tokens at all (the lexer won't return
1610 // them). If the identifier is not a type, then it can't be scope either,
Mike Stump1eb44332009-09-09 15:08:12 +00001611 // just early exit.
Chris Lattner608d1fc2009-01-05 01:49:50 +00001612 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregor39a8de12009-02-25 19:37:18 +00001615 // If this is a template-id, annotate with a template-id or type token.
Douglas Gregor55f6b142009-02-09 18:46:07 +00001616 if (NextToken().is(tok::less)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001617 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001618 UnqualifiedId TemplateName;
1619 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001620 bool MemberOfUnknownSpecialization;
Mike Stump1eb44332009-09-09 15:08:12 +00001621 if (TemplateNameKind TNK
Abramo Bagnara7c153532010-08-06 12:11:11 +00001622 = Actions.isTemplateName(getCurScope(), SS,
1623 /*hasTemplateKeyword=*/false, TemplateName,
John McCallb3d87482010-08-24 05:47:05 +00001624 /*ObjectType=*/ ParsedType(),
1625 EnteringContext,
Abramo Bagnara7c153532010-08-06 12:11:11 +00001626 Template, MemberOfUnknownSpecialization)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001627 // Consume the identifier.
1628 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001629 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1630 TemplateName)) {
Chris Lattnerc8e27cc2009-06-26 04:27:47 +00001631 // If an unrecoverable error occurred, we need to return true here,
1632 // because the token stream is in a damaged state. We may not return
1633 // a valid identifier.
John McCall9ba61662010-02-26 08:45:28 +00001634 return true;
Chris Lattnerc8e27cc2009-06-26 04:27:47 +00001635 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001636 }
Douglas Gregor55f6b142009-02-09 18:46:07 +00001637 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001638
Douglas Gregor39a8de12009-02-25 19:37:18 +00001639 // The current token, which is either an identifier or a
1640 // template-id, is not part of the annotation. Fall through to
1641 // push that token back into the stream and complete the C++ scope
1642 // specifier annotation.
Mike Stump1eb44332009-09-09 15:08:12 +00001643 }
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001644
Douglas Gregor39a8de12009-02-25 19:37:18 +00001645 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001646 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001647 if (TemplateId->Kind == TNK_Type_template) {
Douglas Gregor39a8de12009-02-25 19:37:18 +00001648 // A template-id that refers to a type was parsed into a
1649 // template-id annotation in a context where we weren't allowed
1650 // to produce a type annotation token. Update the template-id
1651 // annotation token to a type annotation token now.
Douglas Gregor059101f2011-03-02 00:47:37 +00001652 AnnotateTemplateIdTokenAsType();
John McCall9ba61662010-02-26 08:45:28 +00001653 return false;
Douglas Gregor39a8de12009-02-25 19:37:18 +00001654 }
1655 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001656
Chris Lattner6ec76d42009-01-04 22:32:19 +00001657 if (SS.isEmpty())
John McCall9ba61662010-02-26 08:45:28 +00001658 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Chris Lattner6ec76d42009-01-04 22:32:19 +00001660 // A C++ scope specifier that isn't followed by a typename.
Richard Smith05766812012-08-18 00:55:03 +00001661 AnnotateScopeToken(SS, IsNewScope);
John McCall9ba61662010-02-26 08:45:28 +00001662 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001663}
1664
1665/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Douglas Gregor39a8de12009-02-25 19:37:18 +00001666/// annotates C++ scope specifiers and template-ids. This returns
Richard Smith83a22ec2012-05-09 08:23:23 +00001667/// true if there was an error that could not be recovered from.
Mike Stump1eb44332009-09-09 15:08:12 +00001668///
Chris Lattner55a7cef2009-01-05 00:13:00 +00001669/// Note that this routine emits an error if you call it with ::new or ::delete
1670/// as the current tokens, so only call it in contexts where these are invalid.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001671bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001672 assert(getLangOpts().CPlusPlus &&
Chris Lattner6ec76d42009-01-04 22:32:19 +00001673 "Call sites of this function should be guarded by checking for C++");
Douglas Gregor3b887352011-04-27 04:48:22 +00001674 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
David Blaikie42d6d0c2011-12-04 05:04:18 +00001675 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1676 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001677
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +00001678 CXXScopeSpec SS;
John McCallb3d87482010-08-24 05:47:05 +00001679 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall9ba61662010-02-26 08:45:28 +00001680 return true;
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00001681 if (SS.isEmpty())
John McCall9ba61662010-02-26 08:45:28 +00001682 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001683
Richard Smith05766812012-08-18 00:55:03 +00001684 AnnotateScopeToken(SS, true);
John McCall9ba61662010-02-26 08:45:28 +00001685 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001686}
John McCall6c94a6d2009-11-03 19:33:12 +00001687
Richard Trieufcaf27e2012-01-19 22:01:51 +00001688bool Parser::isTokenEqualOrEqualTypo() {
1689 tok::TokenKind Kind = Tok.getKind();
1690 switch (Kind) {
1691 default:
Richard Trieud6c7c672012-01-18 22:54:52 +00001692 return false;
Richard Trieufcaf27e2012-01-19 22:01:51 +00001693 case tok::ampequal: // &=
1694 case tok::starequal: // *=
1695 case tok::plusequal: // +=
1696 case tok::minusequal: // -=
1697 case tok::exclaimequal: // !=
1698 case tok::slashequal: // /=
1699 case tok::percentequal: // %=
1700 case tok::lessequal: // <=
1701 case tok::lesslessequal: // <<=
1702 case tok::greaterequal: // >=
1703 case tok::greatergreaterequal: // >>=
1704 case tok::caretequal: // ^=
1705 case tok::pipeequal: // |=
1706 case tok::equalequal: // ==
1707 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1708 << getTokenSimpleSpelling(Kind)
1709 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1710 case tok::equal:
1711 return true;
1712 }
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001713}
1714
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001715SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1716 assert(Tok.is(tok::code_completion));
1717 PrevTokLocation = Tok.getLocation();
1718
Douglas Gregor23c94db2010-07-02 17:43:08 +00001719 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregordc845342010-05-25 05:58:43 +00001720 if (S->getFlags() & Scope::FnScope) {
John McCallf312b1e2010-08-26 23:41:50 +00001721 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001722 cutOffParsing();
1723 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001724 }
1725
1726 if (S->getFlags() & Scope::ClassScope) {
John McCallf312b1e2010-08-26 23:41:50 +00001727 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001728 cutOffParsing();
1729 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001730 }
1731 }
1732
John McCallf312b1e2010-08-26 23:41:50 +00001733 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001734 cutOffParsing();
1735 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001736}
1737
John McCall6c94a6d2009-11-03 19:33:12 +00001738// Anchor the Parser::FieldCallback vtable to this translation unit.
1739// We use a spurious method instead of the destructor because
1740// destroying FieldCallbacks can actually be slightly
1741// performance-sensitive.
1742void Parser::FieldCallback::_anchor() {
1743}
Douglas Gregorf44e8542010-08-24 19:08:16 +00001744
1745// Code-completion pass-through functions
1746
1747void Parser::CodeCompleteDirective(bool InConditional) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00001748 Actions.CodeCompletePreprocessorDirective(InConditional);
Douglas Gregorf44e8542010-08-24 19:08:16 +00001749}
1750
1751void Parser::CodeCompleteInConditionalExclusion() {
1752 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1753}
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001754
1755void Parser::CodeCompleteMacroName(bool IsDefinition) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00001756 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1757}
1758
1759void Parser::CodeCompletePreprocessorExpression() {
1760 Actions.CodeCompletePreprocessorExpression();
1761}
1762
1763void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1764 MacroInfo *MacroInfo,
1765 unsigned ArgumentIndex) {
1766 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1767 ArgumentIndex);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001768}
Douglas Gregor55817af2010-08-25 17:04:25 +00001769
1770void Parser::CodeCompleteNaturalLanguage() {
1771 Actions.CodeCompleteNaturalLanguage();
1772}
Francois Pichetf9860382011-05-07 17:30:27 +00001773
Douglas Gregor3896fc52011-10-24 22:31:10 +00001774bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
Francois Pichetf9860382011-05-07 17:30:27 +00001775 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1776 "Expected '__if_exists' or '__if_not_exists'");
Douglas Gregor3896fc52011-10-24 22:31:10 +00001777 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1778 Result.KeywordLoc = ConsumeToken();
Francois Pichetf9860382011-05-07 17:30:27 +00001779
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001780 BalancedDelimiterTracker T(*this, tok::l_paren);
1781 if (T.consumeOpen()) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001782 Diag(Tok, diag::err_expected_lparen_after)
1783 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
Francois Pichetf9860382011-05-07 17:30:27 +00001784 return true;
1785 }
Francois Pichetf9860382011-05-07 17:30:27 +00001786
1787 // Parse nested-name-specifier.
Douglas Gregorefaa93a2011-11-07 17:33:42 +00001788 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1789 /*EnteringContext=*/false);
Francois Pichetf9860382011-05-07 17:30:27 +00001790
1791 // Check nested-name specifier.
Douglas Gregor3896fc52011-10-24 22:31:10 +00001792 if (Result.SS.isInvalid()) {
1793 T.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001794 return true;
1795 }
1796
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001797 // Parse the unqualified-id.
1798 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1799 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1800 TemplateKWLoc, Result.Name)) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001801 T.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001802 return true;
1803 }
1804
Douglas Gregor3896fc52011-10-24 22:31:10 +00001805 if (T.consumeClose())
Francois Pichetf9860382011-05-07 17:30:27 +00001806 return true;
Douglas Gregor3896fc52011-10-24 22:31:10 +00001807
Francois Pichetf9860382011-05-07 17:30:27 +00001808 // Check if the symbol exists.
Douglas Gregor65019ac2011-10-25 03:44:56 +00001809 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1810 Result.IsIfExists, Result.SS,
Douglas Gregor3896fc52011-10-24 22:31:10 +00001811 Result.Name)) {
1812 case Sema::IER_Exists:
1813 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1814 break;
Francois Pichetf9860382011-05-07 17:30:27 +00001815
Douglas Gregor3896fc52011-10-24 22:31:10 +00001816 case Sema::IER_DoesNotExist:
1817 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1818 break;
1819
1820 case Sema::IER_Dependent:
1821 Result.Behavior = IEB_Dependent;
1822 break;
Douglas Gregor65019ac2011-10-25 03:44:56 +00001823
1824 case Sema::IER_Error:
1825 return true;
Douglas Gregor3896fc52011-10-24 22:31:10 +00001826 }
Francois Pichetf9860382011-05-07 17:30:27 +00001827
1828 return false;
1829}
1830
Francois Pichet563a6452011-05-25 10:19:49 +00001831void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001832 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00001833 if (ParseMicrosoftIfExistsCondition(Result))
1834 return;
1835
Douglas Gregor3896fc52011-10-24 22:31:10 +00001836 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1837 if (Braces.consumeOpen()) {
Francois Pichetf9860382011-05-07 17:30:27 +00001838 Diag(Tok, diag::err_expected_lbrace);
1839 return;
1840 }
Francois Pichetf9860382011-05-07 17:30:27 +00001841
Douglas Gregor3896fc52011-10-24 22:31:10 +00001842 switch (Result.Behavior) {
1843 case IEB_Parse:
1844 // Parse declarations below.
1845 break;
1846
1847 case IEB_Dependent:
1848 llvm_unreachable("Cannot have a dependent external declaration");
1849
1850 case IEB_Skip:
1851 Braces.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001852 return;
1853 }
1854
Douglas Gregor3896fc52011-10-24 22:31:10 +00001855 // Parse the declarations.
1856 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Francois Pichetf9860382011-05-07 17:30:27 +00001857 ParsedAttributesWithRange attrs(AttrFactory);
1858 MaybeParseCXX0XAttributes(attrs);
1859 MaybeParseMicrosoftAttributes(attrs);
1860 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1861 if (Result && !getCurScope()->getParent())
1862 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00001863 }
1864 Braces.consumeClose();
Francois Pichetf9860382011-05-07 17:30:27 +00001865}
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001866
Douglas Gregor5948ae12012-01-03 18:04:46 +00001867Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
Ted Kremenek32ad2ee2012-03-01 22:07:04 +00001868 assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&
Douglas Gregor65030af2011-08-31 18:19:09 +00001869 "Improper start to module import");
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001870 SourceLocation ImportLoc = ConsumeToken();
1871
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001872 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001873
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001874 // Parse the module path.
1875 do {
1876 if (!Tok.is(tok::identifier)) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001877 if (Tok.is(tok::code_completion)) {
1878 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1879 ConsumeCodeCompletionToken();
1880 SkipUntil(tok::semi);
1881 return DeclGroupPtrTy();
1882 }
1883
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001884 Diag(Tok, diag::err_module_expected_ident);
1885 SkipUntil(tok::semi);
1886 return DeclGroupPtrTy();
1887 }
1888
1889 // Record this part of the module path.
1890 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1891 ConsumeToken();
1892
1893 if (Tok.is(tok::period)) {
1894 ConsumeToken();
1895 continue;
1896 }
1897
1898 break;
1899 } while (true);
1900
Douglas Gregor5948ae12012-01-03 18:04:46 +00001901 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001902 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1903 if (Import.isInvalid())
1904 return DeclGroupPtrTy();
1905
1906 return Actions.ConvertDeclToDeclGroup(Import.get());
1907}
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001908
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001909bool BalancedDelimiterTracker::diagnoseOverflow() {
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001910 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1911 P.SkipUntil(tok::eof);
1912 return true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001913}
1914
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001915bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001916 const char *Msg,
1917 tok::TokenKind SkipToToc ) {
1918 LOpen = P.Tok.getLocation();
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001919 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1920 return true;
1921
1922 if (getDepth() < MaxDepth)
1923 return false;
1924
1925 return diagnoseOverflow();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001926}
1927
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001928bool BalancedDelimiterTracker::diagnoseMissingClose() {
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001929 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1930
1931 const char *LHSName = "unknown";
David Blaikieb031eab2012-04-06 23:33:59 +00001932 diag::kind DID;
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001933 switch (Close) {
David Blaikieb031eab2012-04-06 23:33:59 +00001934 default: llvm_unreachable("Unexpected balanced token");
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001935 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1936 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1937 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001938 }
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001939 P.Diag(P.Tok, DID);
1940 P.Diag(LOpen, diag::note_matching) << LHSName;
1941 if (P.SkipUntil(Close))
1942 LClose = P.Tok.getLocation();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001943 return true;
1944}
Douglas Gregor3896fc52011-10-24 22:31:10 +00001945
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001946void BalancedDelimiterTracker::skipToEnd() {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001947 P.SkipUntil(Close, false);
Douglas Gregor3896fc52011-10-24 22:31:10 +00001948}