blob: 2b19c973cee176818805be96327b54e5c2381e58 [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
Benjamin Kramer69b5e952012-07-13 13:25:11 +000026namespace {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000027/// \brief A comment handler that passes comments found by the preprocessor
28/// to the parser action.
29class ActionCommentHandler : public CommentHandler {
30 Sema &S;
31
32public:
33 explicit ActionCommentHandler(Sema &S) : S(S) { }
34
35 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
36 S.ActOnComment(Comment);
37 return false;
38 }
39};
Benjamin Kramer69b5e952012-07-13 13:25:11 +000040} // end anonymous namespace
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000041
Douglas Gregorb57791e2011-10-21 03:57:52 +000042IdentifierInfo *Parser::getSEHExceptKeyword() {
43 // __except is accepted as a (contextual) keyword
David Blaikie4e4d0842012-03-11 07:00:24 +000044 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
Douglas Gregorb57791e2011-10-21 03:57:52 +000045 Ident__except = PP.getIdentifierInfo("__except");
46
47 return Ident__except;
48}
49
Erik Verbruggen6a91d382012-04-12 10:11:59 +000050Parser::Parser(Preprocessor &pp, Sema &actions, bool SkipFunctionBodies)
Ted Kremenek614f96a2011-03-22 01:15:17 +000051 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
Douglas Gregor0fbda682010-09-15 14:51:05 +000052 GreaterThanIsOperator(true), ColonIsSacred(false),
Erik Verbruggen6a91d382012-04-12 10:11:59 +000053 InMessageExpression(false), TemplateParameterDepth(0),
Jordan Rose94f29f42012-07-09 16:54:53 +000054 ParsingInObjCContainer(false), SkipFunctionBodies(SkipFunctionBodies) {
Reid Spencer5f016e22007-07-11 17:01:13 +000055 Tok.setKind(tok::eof);
Douglas Gregor23c94db2010-07-02 17:43:08 +000056 Actions.CurScope = 0;
Chris Lattner9e344c62007-07-15 00:04:39 +000057 NumCachedScopes = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000058 ParenCount = BracketCount = BraceCount = 0;
Argyrios Kyrtzidis849639d2012-02-07 16:50:53 +000059 CurParsedObjCImpl = 0;
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +000060
61 // Add #pragma handlers. These are removed and destroyed in the
62 // destructor.
Daniel Dunbarcbb98ed2010-07-31 19:17:07 +000063 AlignHandler.reset(new PragmaAlignHandler(actions));
64 PP.AddPragmaHandler(AlignHandler.get());
65
Eli Friedmanaa8b0d12010-08-05 06:57:20 +000066 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
67 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
68
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000069 OptionsHandler.reset(new PragmaOptionsHandler(actions));
70 PP.AddPragmaHandler(OptionsHandler.get());
Daniel Dunbar861800c2010-05-26 23:29:06 +000071
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000072 PackHandler.reset(new PragmaPackHandler(actions));
73 PP.AddPragmaHandler(PackHandler.get());
Fariborz Jahanian62c92582011-04-25 18:49:15 +000074
75 MSStructHandler.reset(new PragmaMSStructHandler(actions));
76 PP.AddPragmaHandler(MSStructHandler.get());
Mike Stump1eb44332009-09-09 15:08:12 +000077
Benjamin Kramerfacde172012-06-06 17:32:50 +000078 UnusedHandler.reset(new PragmaUnusedHandler(actions));
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000079 PP.AddPragmaHandler(UnusedHandler.get());
Eli Friedman99914792009-06-05 00:49:58 +000080
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000081 WeakHandler.reset(new PragmaWeakHandler(actions));
82 PP.AddPragmaHandler(WeakHandler.get());
Peter Collingbourne321b8172011-02-14 01:42:35 +000083
David Chisnall5f3c1632012-02-18 16:12:34 +000084 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler(actions));
85 PP.AddPragmaHandler(RedefineExtnameHandler.get());
86
Benjamin Kramerfacde172012-06-06 17:32:50 +000087 FPContractHandler.reset(new PragmaFPContractHandler(actions));
Peter Collingbourne321b8172011-02-14 01:42:35 +000088 PP.AddPragmaHandler("STDC", FPContractHandler.get());
Peter Collingbournef315fa82011-02-14 01:42:53 +000089
David Blaikie4e4d0842012-03-11 07:00:24 +000090 if (getLangOpts().OpenCL) {
Benjamin Kramerfacde172012-06-06 17:32:50 +000091 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler(actions));
Peter Collingbournef315fa82011-02-14 01:42:53 +000092 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
93
94 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
95 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000096
Dmitri Gribenko056e2c32012-06-20 01:06:08 +000097 CommentSemaHandler.reset(new ActionCommentHandler(actions));
98 PP.addCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000099
Douglas Gregorf44e8542010-08-24 19:08:16 +0000100 PP.setCodeCompletionHandler(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Chris Lattner0102c302009-03-05 07:24:28 +0000103/// If a crash happens while the parser is active, print out a line indicating
104/// what the current token is.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000105void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
Chris Lattner0102c302009-03-05 07:24:28 +0000106 const Token &Tok = P.getCurToken();
Chris Lattnerddcbc0a2009-03-05 07:27:50 +0000107 if (Tok.is(tok::eof)) {
Chris Lattner0102c302009-03-05 07:24:28 +0000108 OS << "<eof> parser at end of file\n";
109 return;
110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Chris Lattnerddcbc0a2009-03-05 07:27:50 +0000112 if (Tok.getLocation().isInvalid()) {
113 OS << "<unknown> parser at unknown location\n";
114 return;
115 }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattner0102c302009-03-05 07:24:28 +0000117 const Preprocessor &PP = P.getPreprocessor();
118 Tok.getLocation().print(OS, PP.getSourceManager());
Daniel Dunbar9fa31dd2009-10-17 06:13:04 +0000119 if (Tok.isAnnotation())
120 OS << ": at annotation token \n";
121 else
122 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
Douglas Gregorf780abc2008-12-30 03:27:21 +0000123}
Reid Spencer5f016e22007-07-11 17:01:13 +0000124
Chris Lattner0102c302009-03-05 07:24:28 +0000125
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000126DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000127 return Diags.Report(Loc, DiagID);
Chris Lattner1ab3b962008-11-18 07:48:38 +0000128}
129
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000130DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000131 return Diag(Tok.getLocation(), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132}
133
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000134/// \brief Emits a diagnostic suggesting parentheses surrounding a
135/// given range.
136///
137/// \param Loc The location where we'll emit the diagnostic.
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000138/// \param DK The kind of diagnostic to emit.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000139/// \param ParenRange Source range enclosing code that should be parenthesized.
140void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
141 SourceRange ParenRange) {
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000142 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
143 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000144 // We can't display the parentheses, so just dig the
145 // warning/error and return.
146 Diag(Loc, DK);
147 return;
148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
150 Diag(Loc, DK)
Douglas Gregor849b2432010-03-31 17:46:05 +0000151 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
152 << FixItHint::CreateInsertion(EndLoc, ")");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000153}
154
John McCall837b1a32010-09-07 18:31:03 +0000155static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
156 switch (ExpectedTok) {
Richard Smith4b082422012-09-18 00:52:05 +0000157 case tok::semi:
158 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
John McCall837b1a32010-09-07 18:31:03 +0000159 default: return false;
160 }
161}
162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
164/// input. If so, it is consumed and false is returned.
165///
166/// If the input is malformed, this emits the specified diagnostic. Next, if
167/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
168/// returned.
169bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
170 const char *Msg, tok::TokenKind SkipToTok) {
Douglas Gregordc845342010-05-25 05:58:43 +0000171 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 ConsumeAnyToken();
173 return false;
174 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000175
John McCall837b1a32010-09-07 18:31:03 +0000176 // Detect common single-character typos and resume.
177 if (IsCommonTypo(ExpectedTok, Tok)) {
178 SourceLocation Loc = Tok.getLocation();
179 Diag(Loc, DiagID)
180 << Msg
181 << FixItHint::CreateReplacement(SourceRange(Loc),
182 getTokenSimpleSpelling(ExpectedTok));
183 ConsumeAnyToken();
184
185 // Pretend there wasn't a problem.
186 return false;
187 }
188
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000189 const char *Spelling = 0;
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000190 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
Mike Stump1eb44332009-09-09 15:08:12 +0000191 if (EndLoc.isValid() &&
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000192 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000193 // Show what code to insert to fix this problem.
Mike Stump1eb44332009-09-09 15:08:12 +0000194 Diag(EndLoc, DiagID)
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000195 << Msg
Douglas Gregor849b2432010-03-31 17:46:05 +0000196 << FixItHint::CreateInsertion(EndLoc, Spelling);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000197 } else
198 Diag(Tok, DiagID) << Msg;
199
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 if (SkipToTok != tok::unknown)
201 SkipUntil(SkipToTok);
202 return true;
203}
204
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000205bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
206 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
Douglas Gregorfb5825d2012-05-02 14:34:16 +0000207 ConsumeToken();
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000208 return false;
209 }
210
211 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
212 NextToken().is(tok::semi)) {
213 Diag(Tok, diag::err_extraneous_token_before_semi)
214 << PP.getSpelling(Tok)
215 << FixItHint::CreateRemoval(Tok.getLocation());
216 ConsumeAnyToken(); // The ')' or ']'.
217 ConsumeToken(); // The ';'.
218 return false;
219 }
220
221 return ExpectAndConsume(tok::semi, DiagID);
222}
223
Richard Smitheab9d6f2012-07-23 05:45:25 +0000224void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000225 if (!Tok.is(tok::semi)) return;
226
Richard Smitheab9d6f2012-07-23 05:45:25 +0000227 bool HadMultipleSemis = false;
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000228 SourceLocation StartLoc = Tok.getLocation();
229 SourceLocation EndLoc = Tok.getLocation();
230 ConsumeToken();
231
232 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
Richard Smitheab9d6f2012-07-23 05:45:25 +0000233 HadMultipleSemis = true;
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000234 EndLoc = Tok.getLocation();
235 ConsumeToken();
236 }
237
Richard Smitheab9d6f2012-07-23 05:45:25 +0000238 // C++11 allows extra semicolons at namespace scope, but not in any of the
239 // other contexts.
240 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
241 if (getLangOpts().CPlusPlus0x)
242 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
243 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
244 else
245 Diag(StartLoc, diag::ext_extra_semi_cxx11)
246 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000247 return;
248 }
249
Richard Smitheab9d6f2012-07-23 05:45:25 +0000250 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
251 Diag(StartLoc, diag::ext_extra_semi)
252 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
253 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
254 else
255 // A single semicolon is valid after a member function definition.
256 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
257 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000258}
259
Reid Spencer5f016e22007-07-11 17:01:13 +0000260//===----------------------------------------------------------------------===//
261// Error recovery.
262//===----------------------------------------------------------------------===//
263
264/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner012cf462007-07-24 17:03:04 +0000265/// it (unless DontConsume is true). Because we cannot guarantee that the
Reid Spencer5f016e22007-07-11 17:01:13 +0000266/// token will ever occur, this skips to the next token, or to some likely
267/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
268/// character.
Mike Stumpa6f01772008-06-19 19:28:49 +0000269///
Reid Spencer5f016e22007-07-11 17:01:13 +0000270/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stumpa6f01772008-06-19 19:28:49 +0000271/// returns false.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000272bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
273 bool DontConsume, bool StopAtCodeCompletion) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 // We always want this function to skip at least one token if the first token
275 // isn't T and if not at EOF.
276 bool isFirstTokenSkipped = true;
277 while (1) {
278 // If we found one of the tokens, stop and return true.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000279 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
Chris Lattner00073222007-10-09 17:23:58 +0000280 if (Tok.is(Toks[i])) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 if (DontConsume) {
282 // Noop, don't consume the token.
283 } else {
284 ConsumeAnyToken();
285 }
286 return true;
287 }
288 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000289
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 switch (Tok.getKind()) {
291 case tok::eof:
292 // Ran out of tokens.
293 return false;
Douglas Gregordc845342010-05-25 05:58:43 +0000294
295 case tok::code_completion:
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000296 if (!StopAtCodeCompletion)
297 ConsumeToken();
Douglas Gregordc845342010-05-25 05:58:43 +0000298 return false;
299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 case tok::l_paren:
301 // Recursively skip properly-nested parens.
302 ConsumeParen();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000303 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 break;
305 case tok::l_square:
306 // Recursively skip properly-nested square brackets.
307 ConsumeBracket();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000308 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 break;
310 case tok::l_brace:
311 // Recursively skip properly-nested braces.
312 ConsumeBrace();
Argyrios Kyrtzidis3437f1f2011-01-03 19:44:02 +0000313 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000315
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
317 // Since the user wasn't looking for this token (if they were, it would
318 // already be handled), this isn't balanced. If there is a LHS token at a
319 // higher level, we will assume that this matches the unbalanced token
320 // and return it. Otherwise, this is a spurious RHS token, which we skip.
321 case tok::r_paren:
322 if (ParenCount && !isFirstTokenSkipped)
323 return false; // Matches something.
324 ConsumeParen();
325 break;
326 case tok::r_square:
327 if (BracketCount && !isFirstTokenSkipped)
328 return false; // Matches something.
329 ConsumeBracket();
330 break;
331 case tok::r_brace:
332 if (BraceCount && !isFirstTokenSkipped)
333 return false; // Matches something.
334 ConsumeBrace();
335 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 case tok::string_literal:
338 case tok::wide_string_literal:
Douglas Gregor5cee1192011-07-27 05:40:30 +0000339 case tok::utf8_string_literal:
340 case tok::utf16_string_literal:
341 case tok::utf32_string_literal:
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 ConsumeStringToken();
343 break;
Fariborz Jahanian55edca92011-02-23 00:11:21 +0000344
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 case tok::semi:
346 if (StopAtSemi)
347 return false;
348 // FALL THROUGH.
349 default:
350 // Skip this token.
351 ConsumeToken();
352 break;
353 }
354 isFirstTokenSkipped = false;
Mike Stumpa6f01772008-06-19 19:28:49 +0000355 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
358//===----------------------------------------------------------------------===//
359// Scope manipulation
360//===----------------------------------------------------------------------===//
361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362/// EnterScope - Start a new scope.
363void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner9e344c62007-07-15 00:04:39 +0000364 if (NumCachedScopes) {
365 Scope *N = ScopeCache[--NumCachedScopes];
Douglas Gregor23c94db2010-07-02 17:43:08 +0000366 N->Init(getCurScope(), ScopeFlags);
367 Actions.CurScope = N;
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 } else {
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +0000369 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 }
371}
372
373/// ExitScope - Pop a scope off the scope stack.
374void Parser::ExitScope() {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000375 assert(getCurScope() && "Scope imbalance!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000376
Chris Lattner90ae68a2007-10-09 20:37:18 +0000377 // Inform the actions module that this scope is going away if there are any
378 // decls in it.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000379 if (!getCurScope()->decl_empty())
380 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
Mike Stumpa6f01772008-06-19 19:28:49 +0000381
Douglas Gregor23c94db2010-07-02 17:43:08 +0000382 Scope *OldScope = getCurScope();
383 Actions.CurScope = OldScope->getParent();
Mike Stumpa6f01772008-06-19 19:28:49 +0000384
Chris Lattner9e344c62007-07-15 00:04:39 +0000385 if (NumCachedScopes == ScopeCacheSize)
386 delete OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 else
Chris Lattner9e344c62007-07-15 00:04:39 +0000388 ScopeCache[NumCachedScopes++] = OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Richard Smith7a614d82011-06-11 17:19:42 +0000391/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
392/// this object does nothing.
393Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
394 bool ManageFlags)
395 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
396 if (CurScope) {
397 OldFlags = CurScope->getFlags();
398 CurScope->setFlags(ScopeFlags);
399 }
400}
Reid Spencer5f016e22007-07-11 17:01:13 +0000401
Richard Smith7a614d82011-06-11 17:19:42 +0000402/// Restore the flags for the current scope to what they were before this
403/// object overrode them.
404Parser::ParseScopeFlags::~ParseScopeFlags() {
405 if (CurScope)
406 CurScope->setFlags(OldFlags);
407}
Reid Spencer5f016e22007-07-11 17:01:13 +0000408
409
410//===----------------------------------------------------------------------===//
411// C99 6.9: External Definitions.
412//===----------------------------------------------------------------------===//
413
414Parser::~Parser() {
415 // If we still have scopes active, delete the scope tree.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000416 delete getCurScope();
417 Actions.CurScope = 0;
418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // Free the scope cache.
Chris Lattner9e344c62007-07-15 00:04:39 +0000420 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
421 delete ScopeCache[i];
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +0000422
Francois Pichet8387e2a2011-04-22 22:18:13 +0000423 // Free LateParsedTemplatedFunction nodes.
424 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
425 it != LateParsedTemplateMap.end(); ++it)
426 delete it->second;
427
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +0000428 // Remove the pragma handlers we installed.
Daniel Dunbarcbb98ed2010-07-31 19:17:07 +0000429 PP.RemovePragmaHandler(AlignHandler.get());
430 AlignHandler.reset();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000431 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
432 GCCVisibilityHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000433 PP.RemovePragmaHandler(OptionsHandler.get());
Daniel Dunbar861800c2010-05-26 23:29:06 +0000434 OptionsHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000435 PP.RemovePragmaHandler(PackHandler.get());
Ted Kremenek4726d032009-03-23 22:28:25 +0000436 PackHandler.reset();
Fariborz Jahanian62c92582011-04-25 18:49:15 +0000437 PP.RemovePragmaHandler(MSStructHandler.get());
438 MSStructHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000439 PP.RemovePragmaHandler(UnusedHandler.get());
Ted Kremenek4726d032009-03-23 22:28:25 +0000440 UnusedHandler.reset();
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000441 PP.RemovePragmaHandler(WeakHandler.get());
Eli Friedman99914792009-06-05 00:49:58 +0000442 WeakHandler.reset();
David Chisnall5f3c1632012-02-18 16:12:34 +0000443 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
444 RedefineExtnameHandler.reset();
Peter Collingbournef315fa82011-02-14 01:42:53 +0000445
David Blaikie4e4d0842012-03-11 07:00:24 +0000446 if (getLangOpts().OpenCL) {
Peter Collingbournef315fa82011-02-14 01:42:53 +0000447 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
448 OpenCLExtensionHandler.reset();
449 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
450 }
451
Peter Collingbourne321b8172011-02-14 01:42:35 +0000452 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
453 FPContractHandler.reset();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000454
Dmitri Gribenko056e2c32012-06-20 01:06:08 +0000455 PP.removeCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000456
Douglas Gregorf44e8542010-08-24 19:08:16 +0000457 PP.clearCodeCompletionHandler();
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000458
459 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
461
462/// Initialize - Warm up the parser.
463///
464void Parser::Initialize() {
Chris Lattner31e05722007-08-26 06:24:45 +0000465 // Create the translation unit scope. Install it as the current scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000466 assert(getCurScope() == 0 && "A scope is already active?");
Chris Lattner31e05722007-08-26 06:24:45 +0000467 EnterScope(Scope::DeclScope);
Douglas Gregorc1a3e5e2010-08-25 18:07:12 +0000468 Actions.ActOnTranslationUnitScope(getCurScope());
469
470 // Prime the lexer look-ahead.
471 ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +0000472
Chris Lattner34870da2007-08-29 22:54:08 +0000473 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000474 // Referenced in Parser::ParseObjCTypeQualifierList.
David Blaikie4e4d0842012-03-11 07:00:24 +0000475 if (getLangOpts().ObjC1) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000476 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
477 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
478 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
479 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
480 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
481 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner34870da2007-08-29 22:54:08 +0000482 }
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000483
Douglas Gregore97179c2011-09-08 01:46:34 +0000484 Ident_instancetype = 0;
Anders Carlsson7eeb4ec2011-01-20 03:47:08 +0000485 Ident_final = 0;
486 Ident_override = 0;
Anders Carlsson1f3b6fd2011-01-16 23:56:42 +0000487
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000488 Ident_super = &PP.getIdentifierTable().get("super");
John Thompson82287d12010-02-05 00:12:22 +0000489
David Blaikie4e4d0842012-03-11 07:00:24 +0000490 if (getLangOpts().AltiVec) {
John Thompson82287d12010-02-05 00:12:22 +0000491 Ident_vector = &PP.getIdentifierTable().get("vector");
492 Ident_pixel = &PP.getIdentifierTable().get("pixel");
493 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000494
495 Ident_introduced = 0;
496 Ident_deprecated = 0;
497 Ident_obsoleted = 0;
Douglas Gregorb53e4172011-03-26 03:35:55 +0000498 Ident_unavailable = 0;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000499
Douglas Gregorb57791e2011-10-21 03:57:52 +0000500 Ident__except = 0;
501
John Wiegley28bbe4b2011-04-28 01:08:34 +0000502 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
503 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
504 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
505
David Blaikie4e4d0842012-03-11 07:00:24 +0000506 if(getLangOpts().Borland) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000507 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
508 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
509 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
510 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
511 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
512 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
513 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
514 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
515 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
516
517 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
518 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
519 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
520 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
521 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
522 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
523 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
524 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
525 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
526 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000527}
528
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000529namespace {
530 /// \brief RAIIObject to destroy the contents of a SmallVector of
531 /// TemplateIdAnnotation pointers and clear the vector.
532 class DestroyTemplateIdAnnotationsRAIIObj {
533 SmallVectorImpl<TemplateIdAnnotation *> &Container;
534 public:
535 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
536 &Container)
537 : Container(Container) {}
538
539 ~DestroyTemplateIdAnnotationsRAIIObj() {
540 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
541 Container.begin(), E = Container.end();
542 I != E; ++I)
543 (*I)->Destroy();
544 Container.clear();
545 }
546 };
547}
548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
550/// action tells us to. This returns true if the EOF was encountered.
Chris Lattner682bf922009-03-29 16:50:03 +0000551bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000552 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000553
Axel Naumanne55329d2012-03-16 10:40:17 +0000554 // Skip over the EOF token, flagging end of previous input for incremental
555 // processing
556 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
557 ConsumeToken();
558
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000559 while (Tok.is(tok::annot_pragma_unused))
560 HandlePragmaUnused();
561
Chris Lattner682bf922009-03-29 16:50:03 +0000562 Result = DeclGroupPtrTy();
Chris Lattner9299f3f2008-08-23 03:19:52 +0000563 if (Tok.is(tok::eof)) {
Francois Pichet8387e2a2011-04-22 22:18:13 +0000564 // Late template parsing can begin.
David Blaikie4e4d0842012-03-11 07:00:24 +0000565 if (getLangOpts().DelayedTemplateParsing)
Francois Pichet8387e2a2011-04-22 22:18:13 +0000566 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
Axel Naumanne55329d2012-03-16 10:40:17 +0000567 if (!PP.isIncrementalProcessingEnabled())
568 Actions.ActOnEndOfTranslationUnit();
569 //else don't tell Sema that we ended parsing: more input might come.
Francois Pichet8387e2a2011-04-22 22:18:13 +0000570
Chris Lattner9299f3f2008-08-23 03:19:52 +0000571 return true;
572 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000573
John McCall0b7e6782011-03-24 11:26:52 +0000574 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000575 MaybeParseCXX0XAttributes(attrs);
576 MaybeParseMicrosoftAttributes(attrs);
Axel Naumanne55329d2012-03-16 10:40:17 +0000577
John McCall7f040a92010-12-24 02:08:15 +0000578 Result = ParseExternalDeclaration(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 return false;
580}
581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582/// ParseTranslationUnit:
583/// translation-unit: [C99 6.9]
Mike Stumpa6f01772008-06-19 19:28:49 +0000584/// external-declaration
585/// translation-unit external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000586void Parser::ParseTranslationUnit() {
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000587 Initialize();
Mike Stumpa6f01772008-06-19 19:28:49 +0000588
Chris Lattner682bf922009-03-29 16:50:03 +0000589 DeclGroupPtrTy Res;
Steve Naroff89307ff2007-11-29 23:05:20 +0000590 while (!ParseTopLevelDecl(Res))
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 /*parse them all*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner06f54852008-08-23 02:00:52 +0000593 ExitScope();
Douglas Gregor23c94db2010-07-02 17:43:08 +0000594 assert(getCurScope() == 0 && "Scope imbalance!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000595}
596
597/// ParseExternalDeclaration:
Chris Lattner90b93d62008-12-08 21:59:01 +0000598///
Douglas Gregorc19923d2008-11-21 16:10:08 +0000599/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattnerc3018152007-08-10 20:57:02 +0000600/// function-definition
601/// declaration
Douglas Gregora1d71ae2009-08-24 12:17:54 +0000602/// [C++0x] empty-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000603/// [GNU] asm-definition
Chris Lattnerc3018152007-08-10 20:57:02 +0000604/// [GNU] __extension__ external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000605/// [OBJC] objc-class-definition
606/// [OBJC] objc-class-declaration
607/// [OBJC] objc-alias-declaration
608/// [OBJC] objc-protocol-definition
609/// [OBJC] objc-method-definition
610/// [OBJC] @end
Douglas Gregorc19923d2008-11-21 16:10:08 +0000611/// [C++] linkage-specification
Reid Spencer5f016e22007-07-11 17:01:13 +0000612/// [GNU] asm-definition:
613/// simple-asm-expr ';'
614///
Douglas Gregora1d71ae2009-08-24 12:17:54 +0000615/// [C++0x] empty-declaration:
616/// ';'
617///
Douglas Gregor45f96552009-09-04 06:33:52 +0000618/// [C++0x/GNU] 'extern' 'template' declaration
John McCall7f040a92010-12-24 02:08:15 +0000619Parser::DeclGroupPtrTy
620Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
621 ParsingDeclSpec *DS) {
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000622 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +0000623 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000624
625 if (PP.isCodeCompletionReached()) {
626 cutOffParsing();
627 return DeclGroupPtrTy();
628 }
629
John McCalld226f652010-08-21 09:40:31 +0000630 Decl *SingleDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 switch (Tok.getKind()) {
Rafael Espindola426fc942012-01-26 02:02:57 +0000632 case tok::annot_pragma_vis:
633 HandlePragmaVisibility();
634 return DeclGroupPtrTy();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000635 case tok::annot_pragma_pack:
636 HandlePragmaPack();
637 return DeclGroupPtrTy();
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 case tok::semi:
Richard Trieu4b0e6f12012-05-16 19:04:59 +0000639 ConsumeExtraSemi(OutsideFunction);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 // TODO: Invoke action for top-level semicolon.
Chris Lattner682bf922009-03-29 16:50:03 +0000641 return DeclGroupPtrTy();
Chris Lattner90b93d62008-12-08 21:59:01 +0000642 case tok::r_brace:
Nico Weber883692e2012-01-17 01:04:27 +0000643 Diag(Tok, diag::err_extraneous_closing_brace);
Chris Lattner90b93d62008-12-08 21:59:01 +0000644 ConsumeBrace();
Chris Lattner682bf922009-03-29 16:50:03 +0000645 return DeclGroupPtrTy();
Chris Lattner90b93d62008-12-08 21:59:01 +0000646 case tok::eof:
647 Diag(Tok, diag::err_expected_external_declaration);
Chris Lattner682bf922009-03-29 16:50:03 +0000648 return DeclGroupPtrTy();
Chris Lattnerc3018152007-08-10 20:57:02 +0000649 case tok::kw___extension__: {
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000650 // __extension__ silences extension warnings in the subexpression.
651 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner39146d62008-10-20 06:51:33 +0000652 ConsumeToken();
John McCall7f040a92010-12-24 02:08:15 +0000653 return ParseExternalDeclaration(attrs);
Chris Lattnerc3018152007-08-10 20:57:02 +0000654 }
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000655 case tok::kw_asm: {
John McCall7f040a92010-12-24 02:08:15 +0000656 ProhibitAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000657
Abramo Bagnara21e006e2011-03-03 14:20:18 +0000658 SourceLocation StartLoc = Tok.getLocation();
659 SourceLocation EndLoc;
660 ExprResult Result(ParseSimpleAsm(&EndLoc));
Mike Stumpa6f01772008-06-19 19:28:49 +0000661
Anders Carlsson3f9424f2008-02-08 00:23:11 +0000662 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
663 "top-level asm block");
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000664
Chris Lattner682bf922009-03-29 16:50:03 +0000665 if (Result.isInvalid())
666 return DeclGroupPtrTy();
Abramo Bagnara21e006e2011-03-03 14:20:18 +0000667 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
Chris Lattner682bf922009-03-29 16:50:03 +0000668 break;
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000669 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 case tok::at:
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000671 return ParseObjCAtDirectives();
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 case tok::minus:
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 case tok::plus:
David Blaikie4e4d0842012-03-11 07:00:24 +0000674 if (!getLangOpts().ObjC1) {
Chris Lattner682bf922009-03-29 16:50:03 +0000675 Diag(Tok, diag::err_expected_external_declaration);
676 ConsumeToken();
677 return DeclGroupPtrTy();
678 }
679 SingleDecl = ParseObjCMethodDefinition();
680 break;
Douglas Gregor791215b2009-09-21 20:51:25 +0000681 case tok::code_completion:
Douglas Gregor23c94db2010-07-02 17:43:08 +0000682 Actions.CodeCompleteOrdinaryName(getCurScope(),
Argyrios Kyrtzidis849639d2012-02-07 16:50:53 +0000683 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
John McCallf312b1e2010-08-26 23:41:50 +0000684 : Sema::PCC_Namespace);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000685 cutOffParsing();
686 return DeclGroupPtrTy();
Douglas Gregorf780abc2008-12-30 03:27:21 +0000687 case tok::kw_using:
Chris Lattner8f08cb72007-08-25 06:57:03 +0000688 case tok::kw_namespace:
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 case tok::kw_typedef:
Douglas Gregoradcac882008-12-01 23:54:00 +0000690 case tok::kw_template:
691 case tok::kw_export: // As in 'export template'
Anders Carlsson511d7ab2009-03-11 16:27:10 +0000692 case tok::kw_static_assert:
Peter Collingbournec6eb44b2011-04-15 00:35:57 +0000693 case tok::kw__Static_assert:
Chad Rosier26d60232012-04-25 22:51:41 +0000694 // A function definition cannot start with any of these keywords.
Chris Lattner97144fc2009-04-02 04:16:50 +0000695 {
696 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000697 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000698 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000699 }
Sebastian Redld078e642010-08-27 23:12:46 +0000700
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000701 case tok::kw_static:
702 // Parse (then ignore) 'static' prior to a template instantiation. This is
703 // a GCC extension that we intentionally do not support.
David Blaikie4e4d0842012-03-11 07:00:24 +0000704 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000705 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
706 << 0;
Sebastian Redld078e642010-08-27 23:12:46 +0000707 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000708 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000709 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000710 }
711 goto dont_know;
712
713 case tok::kw_inline:
David Blaikie4e4d0842012-03-11 07:00:24 +0000714 if (getLangOpts().CPlusPlus) {
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000715 tok::TokenKind NextKind = NextToken().getKind();
716
717 // Inline namespaces. Allowed as an extension even in C++03.
718 if (NextKind == tok::kw_namespace) {
719 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000720 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000721 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000722 }
723
724 // Parse (then ignore) 'inline' prior to a template instantiation. This is
725 // a GCC extension that we intentionally do not support.
726 if (NextKind == tok::kw_template) {
727 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
728 << 1;
729 SourceLocation DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000730 StmtVector Stmts;
John McCall7f040a92010-12-24 02:08:15 +0000731 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregor7306ebf2010-12-01 20:32:20 +0000732 }
Sebastian Redld078e642010-08-27 23:12:46 +0000733 }
734 goto dont_know;
735
Douglas Gregor45f96552009-09-04 06:33:52 +0000736 case tok::kw_extern:
David Blaikie4e4d0842012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor45f96552009-09-04 06:33:52 +0000738 // Extern templates
739 SourceLocation ExternLoc = ConsumeToken();
740 SourceLocation TemplateLoc = ConsumeToken();
David Blaikie4e4d0842012-03-11 07:00:24 +0000741 Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
Richard Smith93245832011-10-20 18:35:58 +0000742 diag::warn_cxx98_compat_extern_template :
743 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
Douglas Gregor45f96552009-09-04 06:33:52 +0000744 SourceLocation DeclEnd;
745 return Actions.ConvertDeclToDeclGroup(
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +0000746 ParseExplicitInstantiation(Declarator::FileContext,
747 ExternLoc, TemplateLoc, DeclEnd));
Douglas Gregor45f96552009-09-04 06:33:52 +0000748 }
Douglas Gregor45f96552009-09-04 06:33:52 +0000749 // FIXME: Detect C++ linkage specifications here?
Sebastian Redld078e642010-08-27 23:12:46 +0000750 goto dont_know;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Francois Pichetf9860382011-05-07 17:30:27 +0000752 case tok::kw___if_exists:
753 case tok::kw___if_not_exists:
Francois Pichet563a6452011-05-25 10:19:49 +0000754 ParseMicrosoftIfExistsExternalDeclaration();
Francois Pichetf9860382011-05-07 17:30:27 +0000755 return DeclGroupPtrTy();
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 default:
Sebastian Redld078e642010-08-27 23:12:46 +0000758 dont_know:
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 // We can't tell whether this is a function-definition or declaration yet.
John McCall7f040a92010-12-24 02:08:15 +0000760 if (DS) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000761 return ParseDeclarationOrFunctionDefinition(attrs, DS);
John McCall7f040a92010-12-24 02:08:15 +0000762 } else {
763 return ParseDeclarationOrFunctionDefinition(attrs);
764 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner682bf922009-03-29 16:50:03 +0000767 // This routine returns a DeclGroup, if the thing we parsed only contains a
768 // single decl, convert it now.
769 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000770}
771
Douglas Gregor1426e532009-05-12 21:31:51 +0000772/// \brief Determine whether the current token, if it occurs after a
773/// declarator, continues a declaration or declaration list.
Sean Hunte4246a62011-05-12 06:15:49 +0000774bool Parser::isDeclarationAfterDeclarator() {
775 // Check for '= delete' or '= default'
David Blaikie4e4d0842012-03-11 07:00:24 +0000776 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Sean Hunte4246a62011-05-12 06:15:49 +0000777 const Token &KW = NextToken();
778 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
779 return false;
780 }
Fariborz Jahanian6c89eaf2012-07-02 23:37:09 +0000781
Douglas Gregor1426e532009-05-12 21:31:51 +0000782 return Tok.is(tok::equal) || // int X()= -> not a function def
783 Tok.is(tok::comma) || // int X(), -> not a function def
784 Tok.is(tok::semi) || // int X(); -> not a function def
785 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
786 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
David Blaikie4e4d0842012-03-11 07:00:24 +0000787 (getLangOpts().CPlusPlus &&
Fariborz Jahanian39700f82012-07-05 19:34:20 +0000788 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
Douglas Gregor1426e532009-05-12 21:31:51 +0000789}
790
791/// \brief Determine whether the current token, if it occurs after a
792/// declarator, indicates the start of a function definition.
Chris Lattner004659a2010-07-11 22:42:07 +0000793bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000794 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
Chris Lattner5d1c6192009-12-06 18:34:27 +0000795 if (Tok.is(tok::l_brace)) // int X() {}
796 return true;
797
Chris Lattner004659a2010-07-11 22:42:07 +0000798 // Handle K&R C argument lists: int X(f) int f; {}
David Blaikie4e4d0842012-03-11 07:00:24 +0000799 if (!getLangOpts().CPlusPlus &&
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000800 Declarator.getFunctionTypeInfo().isKNRPrototype())
Chris Lattner004659a2010-07-11 22:42:07 +0000801 return isDeclarationSpecifier();
Sean Hunte4246a62011-05-12 06:15:49 +0000802
David Blaikie4e4d0842012-03-11 07:00:24 +0000803 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Sean Hunte4246a62011-05-12 06:15:49 +0000804 const Token &KW = NextToken();
805 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
806 }
Chris Lattner004659a2010-07-11 22:42:07 +0000807
Chris Lattner5d1c6192009-12-06 18:34:27 +0000808 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
809 Tok.is(tok::kw_try); // X() try { ... }
Douglas Gregor1426e532009-05-12 21:31:51 +0000810}
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
813/// a declaration. We can't tell which we have until we read up to the
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000814/// compound-statement in function-definition. TemplateParams, if
815/// non-NULL, provides the template parameters when we're parsing a
Mike Stump1eb44332009-09-09 15:08:12 +0000816/// C++ template-declaration.
Reid Spencer5f016e22007-07-11 17:01:13 +0000817///
818/// function-definition: [C99 6.9.1]
Chris Lattnera798ebc2008-04-05 05:52:15 +0000819/// decl-specs declarator declaration-list[opt] compound-statement
820/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000821/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattnera798ebc2008-04-05 05:52:15 +0000822///
Reid Spencer5f016e22007-07-11 17:01:13 +0000823/// declaration: [C99 6.7]
Chris Lattner697e15f2007-08-22 06:06:56 +0000824/// declaration-specifiers init-declarator-list[opt] ';'
825/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Reid Spencer5f016e22007-07-11 17:01:13 +0000826/// [OMP] threadprivate-directive [TODO]
827///
Chris Lattner682bf922009-03-29 16:50:03 +0000828Parser::DeclGroupPtrTy
Sean Hunt2edf0a22012-06-23 05:07:58 +0000829Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
830 ParsingDeclSpec &DS,
831 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 // Parse the common declaration-specifiers piece.
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000833 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
Mike Stumpa6f01772008-06-19 19:28:49 +0000834
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
836 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner00073222007-10-09 17:23:58 +0000837 if (Tok.is(tok::semi)) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000838 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +0000839 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000840 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000841 DS.complete(TheDecl);
Chris Lattner682bf922009-03-29 16:50:03 +0000842 return Actions.ConvertDeclToDeclGroup(TheDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000844
Sean Hunt2edf0a22012-06-23 05:07:58 +0000845 DS.takeAttributesFrom(attrs);
846
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000847 // ObjC2 allows prefix attributes on class interfaces and protocols.
848 // FIXME: This still needs better diagnostics. We should only accept
849 // attributes here, no types, etc.
David Blaikie4e4d0842012-03-11 07:00:24 +0000850 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
Steve Naroffdac269b2007-08-20 21:31:48 +0000851 SourceLocation AtLoc = ConsumeToken(); // the "@"
Mike Stump1eb44332009-09-09 15:08:12 +0000852 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000853 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
854 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattnercb53b362007-12-27 19:57:00 +0000855 SkipUntil(tok::semi); // FIXME: better skip?
Chris Lattner682bf922009-03-29 16:50:03 +0000856 return DeclGroupPtrTy();
Chris Lattnercb53b362007-12-27 19:57:00 +0000857 }
John McCalld8ac0572009-11-03 19:26:08 +0000858
John McCall54abf7d2009-11-04 02:18:39 +0000859 DS.abort();
860
Fariborz Jahanian0de2ae22008-01-02 19:17:38 +0000861 const char *PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +0000862 unsigned DiagID;
863 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
864 Diag(AtLoc, DiagID) << PrevSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000866 if (Tok.isObjCAtKeyword(tok::objc_protocol))
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000867 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
868
869 return Actions.ConvertDeclToDeclGroup(
870 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
Steve Naroffdac269b2007-08-20 21:31:48 +0000871 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000872
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000873 // If the declspec consisted only of 'extern' and we have a string
874 // literal following it, this must be a C++ linkage specifier like
875 // 'extern "C"'.
David Blaikie4e4d0842012-03-11 07:00:24 +0000876 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000877 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
Chris Lattner682bf922009-03-29 16:50:03 +0000878 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
John McCalld226f652010-08-21 09:40:31 +0000879 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
Chris Lattner682bf922009-03-29 16:50:03 +0000880 return Actions.ConvertDeclToDeclGroup(TheDecl);
881 }
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000882
John McCalld8ac0572009-11-03 19:26:08 +0000883 return ParseDeclGroup(DS, Declarator::FileContext, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884}
885
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000886Parser::DeclGroupPtrTy
Sean Hunt2edf0a22012-06-23 05:07:58 +0000887Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
888 ParsingDeclSpec *DS,
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000889 AccessSpecifier AS) {
Sean Hunt2edf0a22012-06-23 05:07:58 +0000890 if (DS) {
891 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
892 } else {
893 ParsingDeclSpec PDS(*this);
894 // Must temporarily exit the objective-c container scope for
895 // parsing c constructs and re-enter objc container scope
896 // afterwards.
897 ObjCDeclContextSwitch ObjCDC(*this);
898
899 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
900 }
Fariborz Jahanian3acd9aa2009-12-09 21:39:38 +0000901}
902
Reid Spencer5f016e22007-07-11 17:01:13 +0000903/// ParseFunctionDefinition - We parsed and verified that the specified
904/// Declarator is well formed. If this is a K&R-style function, read the
905/// parameters declaration-list, then start the compound-statement.
906///
Chris Lattnera798ebc2008-04-05 05:52:15 +0000907/// function-definition: [C99 6.9.1]
908/// decl-specs declarator declaration-list[opt] compound-statement
909/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000910/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregor7ad83902008-11-05 04:29:56 +0000911/// [C++] function-definition: [C++ 8.4]
Chris Lattner23c4b182009-03-29 17:18:04 +0000912/// decl-specifier-seq[opt] declarator ctor-initializer[opt]
913/// function-body
Douglas Gregor7ad83902008-11-05 04:29:56 +0000914/// [C++] function-definition: [C++ 8.4]
Sebastian Redld3a413d2009-04-26 20:35:05 +0000915/// decl-specifier-seq[opt] declarator function-try-block
Reid Spencer5f016e22007-07-11 17:01:13 +0000916///
John McCalld226f652010-08-21 09:40:31 +0000917Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000918 const ParsedTemplateInfo &TemplateInfo,
919 LateParsedAttrList *LateParsedAttrs) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000920 // Poison the SEH identifiers so they are flagged as illegal in function bodies
921 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000922 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stumpa6f01772008-06-19 19:28:49 +0000923
Chris Lattnera798ebc2008-04-05 05:52:15 +0000924 // If this is C90 and the declspecs were completely missing, fudge in an
925 // implicit int. We do this here because this is the only place where
926 // declaration-specifiers are completely optional in the grammar.
David Blaikie4e4d0842012-03-11 07:00:24 +0000927 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
Chris Lattnera798ebc2008-04-05 05:52:15 +0000928 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +0000929 unsigned DiagID;
Chris Lattner31c28682008-10-20 02:01:34 +0000930 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
931 D.getIdentifierLoc(),
John McCallfec54012009-08-03 20:12:06 +0000932 PrevSpec, DiagID);
Sebastian Redlab197ba2009-02-09 18:23:29 +0000933 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattnera798ebc2008-04-05 05:52:15 +0000934 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000935
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 // If this declaration was formed with a K&R-style identifier list for the
937 // arguments, parse declarations for all of the args next.
938 // int foo(a,b) int a; float b; {}
Chris Lattner004659a2010-07-11 22:42:07 +0000939 if (FTI.isKNRPrototype())
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 ParseKNRParamDeclarations(D);
941
Douglas Gregor7ad83902008-11-05 04:29:56 +0000942 // We should have either an opening brace or, in a C++ constructor,
943 // we may have a colon.
Douglas Gregor758afbc2011-02-04 11:57:16 +0000944 if (Tok.isNot(tok::l_brace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000945 (!getLangOpts().CPlusPlus ||
Sean Huntcd10dec2011-05-23 23:14:04 +0000946 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
947 Tok.isNot(tok::equal)))) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 Diag(Tok, diag::err_expected_fn_body);
949
950 // Skip over garbage, until we get to '{'. Don't eat the '{'.
951 SkipUntil(tok::l_brace, true, true);
Mike Stumpa6f01772008-06-19 19:28:49 +0000952
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 // If we didn't find the '{', bail out.
Chris Lattner00073222007-10-09 17:23:58 +0000954 if (Tok.isNot(tok::l_brace))
John McCalld226f652010-08-21 09:40:31 +0000955 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000957
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000958 // Check to make sure that any normal attributes are allowed to be on
959 // a definition. Late parsed attributes are checked at the end.
960 if (Tok.isNot(tok::equal)) {
961 AttributeList *DtorAttrs = D.getAttributes();
962 while (DtorAttrs) {
963 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
964 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
965 << DtorAttrs->getName()->getName();
966 }
967 DtorAttrs = DtorAttrs->getNext();
968 }
969 }
970
Francois Pichet8387e2a2011-04-22 22:18:13 +0000971 // In delayed template parsing mode, for function template we consume the
972 // tokens and store them for late parsing at the end of the translation unit.
David Blaikie4e4d0842012-03-11 07:00:24 +0000973 if (getLangOpts().DelayedTemplateParsing &&
Douglas Gregor09630172012-06-28 21:43:01 +0000974 Tok.isNot(tok::equal) &&
Francois Pichet8387e2a2011-04-22 22:18:13 +0000975 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
Benjamin Kramer5354e772012-08-23 23:38:35 +0000976 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000977
978 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
979 Scope *ParentScope = getCurScope()->getParent();
980
Douglas Gregor45fa5602011-11-07 20:56:01 +0000981 D.setFunctionDefinitionKind(FDK_Definition);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000982 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000983 TemplateParameterLists);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000984 D.complete(DP);
985 D.getMutableDeclSpec().abort();
986
987 if (DP) {
Francois Pichete1fca502011-12-08 09:11:52 +0000988 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000989
990 FunctionDecl *FnD = 0;
991 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
992 FnD = FunTmpl->getTemplatedDecl();
993 else
994 FnD = cast<FunctionDecl>(DP);
Francois Pichetd4a0caf2011-04-22 23:20:44 +0000995 Actions.CheckForFunctionRedefinition(FnD);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000996
997 LateParsedTemplateMap[FnD] = LPT;
998 Actions.MarkAsLateParsedTemplate(FnD);
999 LexTemplateFunctionForLateParsing(LPT->Toks);
1000 } else {
1001 CachedTokens Toks;
1002 LexTemplateFunctionForLateParsing(Toks);
1003 }
1004 return DP;
1005 }
Fariborz Jahanian2eb362b2012-08-10 18:10:56 +00001006 else if (CurParsedObjCImpl &&
Fariborz Jahanian9e5df312012-08-10 21:15:06 +00001007 !TemplateInfo.TemplateParams &&
1008 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1009 Tok.is(tok::colon)) &&
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001010 Actions.CurContext->isTranslationUnit()) {
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001011 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1012 Scope *ParentScope = getCurScope()->getParent();
1013
1014 D.setFunctionDefinitionKind(FDK_Definition);
1015 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
Benjamin Kramer5354e772012-08-23 23:38:35 +00001016 MultiTemplateParamsArg());
Fariborz Jahanianbe1d4ec2012-08-10 15:54:40 +00001017 D.complete(FuncDecl);
1018 D.getMutableDeclSpec().abort();
1019 if (FuncDecl) {
1020 // Consume the tokens and store them for later parsing.
1021 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1022 CurParsedObjCImpl->HasCFunction = true;
1023 return FuncDecl;
1024 }
1025 }
1026
Chris Lattnerb652cea2007-10-09 17:14:05 +00001027 // Enter a scope for the function body.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001028 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stumpa6f01772008-06-19 19:28:49 +00001029
Chris Lattnerb652cea2007-10-09 17:14:05 +00001030 // Tell the actions module that we have entered a function definition with the
1031 // specified Declarator for the function.
John McCalld226f652010-08-21 09:40:31 +00001032 Decl *Res = TemplateInfo.TemplateParams?
Douglas Gregor23c94db2010-07-02 17:43:08 +00001033 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00001034 *TemplateInfo.TemplateParams, D)
Douglas Gregor23c94db2010-07-02 17:43:08 +00001035 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
Mike Stumpa6f01772008-06-19 19:28:49 +00001036
John McCall54abf7d2009-11-04 02:18:39 +00001037 // Break out of the ParsingDeclarator context before we parse the body.
1038 D.complete(Res);
1039
1040 // Break out of the ParsingDeclSpec context, too. This const_cast is
1041 // safe because we're always the sole owner.
1042 D.getMutableDeclSpec().abort();
1043
Sean Huntcd10dec2011-05-23 23:14:04 +00001044 if (Tok.is(tok::equal)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001045 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
Sean Huntcd10dec2011-05-23 23:14:04 +00001046 ConsumeToken();
1047
1048 Actions.ActOnFinishFunctionBody(Res, 0, false);
1049
1050 bool Delete = false;
1051 SourceLocation KWLoc;
1052 if (Tok.is(tok::kw_delete)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001053 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001054 diag::warn_cxx98_compat_deleted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +00001055 diag::ext_deleted_function);
Sean Huntcd10dec2011-05-23 23:14:04 +00001056
1057 KWLoc = ConsumeToken();
1058 Actions.SetDeclDeleted(Res, KWLoc);
1059 Delete = true;
1060 } else if (Tok.is(tok::kw_default)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001061 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001062 diag::warn_cxx98_compat_defaulted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +00001063 diag::ext_defaulted_function);
Sean Huntcd10dec2011-05-23 23:14:04 +00001064
1065 KWLoc = ConsumeToken();
1066 Actions.SetDeclDefaulted(Res, KWLoc);
1067 } else {
1068 llvm_unreachable("function definition after = not 'delete' or 'default'");
1069 }
1070
1071 if (Tok.is(tok::comma)) {
1072 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1073 << Delete;
1074 SkipUntil(tok::semi);
1075 } else {
1076 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1077 Delete ? "delete" : "default", tok::semi);
1078 }
1079
1080 return Res;
1081 }
1082
Sebastian Redld3a413d2009-04-26 20:35:05 +00001083 if (Tok.is(tok::kw_try))
Douglas Gregorc9977d02011-03-16 17:05:57 +00001084 return ParseFunctionTryBlock(Res, BodyScope);
Sebastian Redld3a413d2009-04-26 20:35:05 +00001085
Douglas Gregor7ad83902008-11-05 04:29:56 +00001086 // If we have a colon, then we're probably parsing a C++
1087 // ctor-initializer.
John McCalld6ca8da2010-04-10 07:37:23 +00001088 if (Tok.is(tok::colon)) {
Douglas Gregor7ad83902008-11-05 04:29:56 +00001089 ParseConstructorInitializer(Res);
John McCalld6ca8da2010-04-10 07:37:23 +00001090
1091 // Recover from error.
1092 if (!Tok.is(tok::l_brace)) {
Douglas Gregorc9977d02011-03-16 17:05:57 +00001093 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001094 Actions.ActOnFinishFunctionBody(Res, 0);
John McCalld6ca8da2010-04-10 07:37:23 +00001095 return Res;
1096 }
1097 } else
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001098 Actions.ActOnDefaultCtorInitializers(Res);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001099
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +00001100 // Late attributes are parsed in the same scope as the function body.
1101 if (LateParsedAttrs)
1102 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1103
Douglas Gregorc9977d02011-03-16 17:05:57 +00001104 return ParseFunctionStatementBody(Res, BodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001105}
1106
1107/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1108/// types for a function with a K&R-style identifier list for arguments.
1109void Parser::ParseKNRParamDeclarations(Declarator &D) {
1110 // We know that the top-level of this declarator is a function.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001111 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001112
Chris Lattner04421082008-04-08 04:40:51 +00001113 // Enter function-declaration scope, limiting any declarators to the
1114 // function prototype scope, including parameter declarators.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00001115 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattner04421082008-04-08 04:40:51 +00001116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 // Read all the argument declarations.
1118 while (isDeclarationSpecifier()) {
1119 SourceLocation DSStart = Tok.getLocation();
Mike Stumpa6f01772008-06-19 19:28:49 +00001120
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 // Parse the common declaration-specifiers piece.
John McCall0b7e6782011-03-24 11:26:52 +00001122 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 ParseDeclarationSpecifiers(DS);
Mike Stumpa6f01772008-06-19 19:28:49 +00001124
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1126 // least one declarator'.
1127 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1128 // the declarations though. It's trivial to ignore them, really hard to do
1129 // anything else with them.
Chris Lattner00073222007-10-09 17:23:58 +00001130 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1132 ConsumeToken();
1133 continue;
1134 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1137 // than register.
1138 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1139 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1140 Diag(DS.getStorageClassSpecLoc(),
1141 diag::err_invalid_storage_class_in_func_decl);
1142 DS.ClearStorageClassSpecs();
1143 }
1144 if (DS.isThreadSpecified()) {
1145 Diag(DS.getThreadSpecLoc(),
1146 diag::err_invalid_storage_class_in_func_decl);
1147 DS.ClearStorageClassSpecs();
1148 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // Parse the first declarator attached to this declspec.
1151 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1152 ParseDeclarator(ParmDeclarator);
1153
1154 // Handle the full declarator list.
1155 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001157 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stumpa6f01772008-06-19 19:28:49 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 // Ask the actions module to compute the type for this declarator.
John McCalld226f652010-08-21 09:40:31 +00001160 Decl *Param =
Douglas Gregor23c94db2010-07-02 17:43:08 +00001161 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Steve Naroff2bd42fa2007-09-10 20:51:04 +00001162
Mike Stumpa6f01772008-06-19 19:28:49 +00001163 if (Param &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 // A missing identifier has already been diagnosed.
1165 ParmDeclarator.getIdentifier()) {
1166
1167 // Scan the argument list looking for the correct param to apply this
1168 // type.
1169 for (unsigned i = 0; ; ++i) {
1170 // C99 6.9.1p6: those declarators shall declare only identifiers from
1171 // the identifier list.
1172 if (i == FTI.NumArgs) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001173 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattner6898e332008-11-19 07:51:13 +00001174 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 break;
1176 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001177
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1179 // Reject redefinitions of parameters.
Chris Lattner04421082008-04-08 04:40:51 +00001180 if (FTI.ArgInfo[i].Param) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattner1ab3b962008-11-18 07:48:38 +00001182 diag::err_param_redefinition)
Chris Lattner6898e332008-11-19 07:51:13 +00001183 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001185 FTI.ArgInfo[i].Param = Param;
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 }
1187 break;
1188 }
1189 }
1190 }
1191
1192 // If we don't have a comma, it is either the end of the list (a ';') or
1193 // an error, bail out.
Chris Lattner00073222007-10-09 17:23:58 +00001194 if (Tok.isNot(tok::comma))
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 break;
Mike Stumpa6f01772008-06-19 19:28:49 +00001196
Richard Smith7984de32012-01-12 23:53:29 +00001197 ParmDeclarator.clear();
1198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // Consume the comma.
Richard Smith7984de32012-01-12 23:53:29 +00001200 ParmDeclarator.setCommaLoc(ConsumeToken());
Mike Stumpa6f01772008-06-19 19:28:49 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // Parse the next declarator.
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 ParseDeclarator(ParmDeclarator);
1204 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001205
Chris Lattner8bb21d32012-04-28 16:12:17 +00001206 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 // Skip to end of block or statement
1208 SkipUntil(tok::semi, true);
Chris Lattner00073222007-10-09 17:23:58 +00001209 if (Tok.is(tok::semi))
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 ConsumeToken();
1211 }
1212 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 // The actions module must verify that all arguments were declared.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001215 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001216}
1217
1218
1219/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1220/// allowed to be a wide string, and is not subject to character translation.
1221///
1222/// [GNU] asm-string-literal:
1223/// string-literal
1224///
John McCall60d7b3a2010-08-24 06:29:42 +00001225Parser::ExprResult Parser::ParseAsmStringLiteral() {
Ted Kremenek7f422282011-12-02 00:35:46 +00001226 switch (Tok.getKind()) {
1227 case tok::string_literal:
1228 break;
Richard Smith99831e42012-03-06 03:21:47 +00001229 case tok::utf8_string_literal:
1230 case tok::utf16_string_literal:
1231 case tok::utf32_string_literal:
Ted Kremenek7f422282011-12-02 00:35:46 +00001232 case tok::wide_string_literal: {
1233 SourceLocation L = Tok.getLocation();
1234 Diag(Tok, diag::err_asm_operand_wide_string_literal)
Richard Smith99831e42012-03-06 03:21:47 +00001235 << (Tok.getKind() == tok::wide_string_literal)
Ted Kremenek7f422282011-12-02 00:35:46 +00001236 << SourceRange(L, L);
1237 return ExprError();
1238 }
1239 default:
1240 Diag(Tok, diag::err_expected_string_literal);
1241 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001243
Richard Smith99831e42012-03-06 03:21:47 +00001244 return ParseStringLiteralExpression();
Reid Spencer5f016e22007-07-11 17:01:13 +00001245}
1246
1247/// ParseSimpleAsm
1248///
1249/// [GNU] simple-asm-expr:
1250/// 'asm' '(' asm-string-literal ')'
1251///
John McCall60d7b3a2010-08-24 06:29:42 +00001252Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner00073222007-10-09 17:23:58 +00001253 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001254 SourceLocation Loc = ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +00001255
John McCall7a6ae742010-01-25 22:27:48 +00001256 if (Tok.is(tok::kw_volatile)) {
John McCall841d5e62010-01-25 23:12:50 +00001257 // Remove from the end of 'asm' to the end of 'volatile'.
1258 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1259 PP.getLocForEndOfToken(Tok.getLocation()));
1260
1261 Diag(Tok, diag::warn_file_asm_volatile)
Douglas Gregor849b2432010-03-31 17:46:05 +00001262 << FixItHint::CreateRemoval(RemovalRange);
John McCall7a6ae742010-01-25 22:27:48 +00001263 ConsumeToken();
1264 }
1265
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001266 BalancedDelimiterTracker T(*this, tok::l_paren);
1267 if (T.consumeOpen()) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001268 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl61364dd2008-12-11 19:30:53 +00001269 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001271
John McCall60d7b3a2010-08-24 06:29:42 +00001272 ExprResult Result(ParseAsmStringLiteral());
Mike Stumpa6f01772008-06-19 19:28:49 +00001273
Sebastian Redlab197ba2009-02-09 18:23:29 +00001274 if (Result.isInvalid()) {
1275 SkipUntil(tok::r_paren, true, true);
1276 if (EndLoc)
1277 *EndLoc = Tok.getLocation();
1278 ConsumeAnyToken();
1279 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001280 // Close the paren and get the location of the end bracket
1281 T.consumeClose();
Sebastian Redlab197ba2009-02-09 18:23:29 +00001282 if (EndLoc)
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001283 *EndLoc = T.getCloseLocation();
Sebastian Redlab197ba2009-02-09 18:23:29 +00001284 }
Mike Stumpa6f01772008-06-19 19:28:49 +00001285
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001286 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00001287}
1288
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001289/// \brief Get the TemplateIdAnnotation from the token and put it in the
1290/// cleanup pool so that it gets destroyed when parsing the current top level
1291/// declaration is finished.
1292TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1293 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1294 TemplateIdAnnotation *
1295 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001296 return Id;
1297}
1298
Richard Smith05766812012-08-18 00:55:03 +00001299void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1300 // Push the current token back into the token stream (or revert it if it is
1301 // cached) and use an annotation scope token for current token.
1302 if (PP.isBacktrackEnabled())
1303 PP.RevertCachedTokens(1);
1304 else
1305 PP.EnterToken(Tok);
1306 Tok.setKind(tok::annot_cxxscope);
1307 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1308 Tok.setAnnotationRange(SS.getRange());
1309
1310 // In case the tokens were cached, have Preprocessor replace them
1311 // with the annotation token. We don't need to do this if we've
1312 // just reverted back to a prior state.
1313 if (IsNewAnnotation)
1314 PP.AnnotateCachedTokens(Tok);
1315}
1316
1317/// \brief Attempt to classify the name at the current token position. This may
1318/// form a type, scope or primary expression annotation, or replace the token
1319/// with a typo-corrected keyword. This is only appropriate when the current
1320/// name must refer to an entity which has already been declared.
1321///
1322/// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1323/// and might possibly have a dependent nested name specifier.
1324/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1325/// no typo correction will be performed.
1326Parser::AnnotatedNameKind
1327Parser::TryAnnotateName(bool IsAddressOfOperand,
1328 CorrectionCandidateCallback *CCC) {
1329 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1330
1331 const bool EnteringContext = false;
1332 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1333
1334 CXXScopeSpec SS;
1335 if (getLangOpts().CPlusPlus &&
1336 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1337 return ANK_Error;
1338
1339 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1340 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1341 !WasScopeAnnotation))
1342 return ANK_Error;
1343 return ANK_Unresolved;
1344 }
1345
1346 IdentifierInfo *Name = Tok.getIdentifierInfo();
1347 SourceLocation NameLoc = Tok.getLocation();
1348
1349 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1350 // typo-correct to tentatively-declared identifiers.
1351 if (isTentativelyDeclared(Name)) {
1352 // Identifier has been tentatively declared, and thus cannot be resolved as
1353 // an expression. Fall back to annotating it as a type.
1354 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1355 !WasScopeAnnotation))
1356 return ANK_Error;
1357 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1358 }
1359
1360 Token Next = NextToken();
1361
1362 // Look up and classify the identifier. We don't perform any typo-correction
1363 // after a scope specifier, because in general we can't recover from typos
1364 // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1365 // back into scope specifier parsing).
1366 Sema::NameClassification Classification
1367 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1368 IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1369
1370 switch (Classification.getKind()) {
1371 case Sema::NC_Error:
1372 return ANK_Error;
1373
1374 case Sema::NC_Keyword:
1375 // The identifier was typo-corrected to a keyword.
1376 Tok.setIdentifierInfo(Name);
1377 Tok.setKind(Name->getTokenID());
1378 PP.TypoCorrectToken(Tok);
1379 if (SS.isNotEmpty())
1380 AnnotateScopeToken(SS, !WasScopeAnnotation);
1381 // We've "annotated" this as a keyword.
1382 return ANK_Success;
1383
1384 case Sema::NC_Unknown:
1385 // It's not something we know about. Leave it unannotated.
1386 break;
1387
1388 case Sema::NC_Type:
1389 Tok.setKind(tok::annot_typename);
1390 setTypeAnnotation(Tok, Classification.getType());
1391 Tok.setAnnotationEndLoc(NameLoc);
1392 if (SS.isNotEmpty())
1393 Tok.setLocation(SS.getBeginLoc());
1394 PP.AnnotateCachedTokens(Tok);
1395 return ANK_Success;
1396
1397 case Sema::NC_Expression:
1398 Tok.setKind(tok::annot_primary_expr);
1399 setExprAnnotation(Tok, Classification.getExpression());
1400 Tok.setAnnotationEndLoc(NameLoc);
1401 if (SS.isNotEmpty())
1402 Tok.setLocation(SS.getBeginLoc());
1403 PP.AnnotateCachedTokens(Tok);
1404 return ANK_Success;
1405
1406 case Sema::NC_TypeTemplate:
1407 if (Next.isNot(tok::less)) {
1408 // This may be a type template being used as a template template argument.
1409 if (SS.isNotEmpty())
1410 AnnotateScopeToken(SS, !WasScopeAnnotation);
1411 return ANK_TemplateName;
1412 }
1413 // Fall through.
1414 case Sema::NC_FunctionTemplate: {
1415 // We have a type or function template followed by '<'.
1416 ConsumeToken();
1417 UnqualifiedId Id;
1418 Id.setIdentifier(Name, NameLoc);
1419 if (AnnotateTemplateIdToken(
1420 TemplateTy::make(Classification.getTemplateName()),
1421 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1422 return ANK_Error;
1423 return ANK_Success;
1424 }
1425
1426 case Sema::NC_NestedNameSpecifier:
1427 llvm_unreachable("already parsed nested name specifier");
1428 }
1429
1430 // Unable to classify the name, but maybe we can annotate a scope specifier.
1431 if (SS.isNotEmpty())
1432 AnnotateScopeToken(SS, !WasScopeAnnotation);
1433 return ANK_Unresolved;
1434}
1435
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001436/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1437/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1438/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1439/// with a single annotation token representing the typename or C++ scope
1440/// respectively.
1441/// This simplifies handling of C++ scope specifiers and allows efficient
1442/// backtracking without the need to re-parse and resolve nested-names and
1443/// typenames.
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +00001444/// It will mainly be called when we expect to treat identifiers as typenames
1445/// (if they are typenames). For example, in C we do not expect identifiers
1446/// inside expressions to be treated as typenames so it will not be called
1447/// for expressions in C.
1448/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroffb43a50f2009-01-28 19:39:02 +00001449/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +00001450/// will not be called twice, once to check whether we have a declaration
1451/// specifier, and another one to get the actual type inside
1452/// ParseDeclarationSpecifiers).
Chris Lattnera7bc7c82009-01-04 23:23:14 +00001453///
John McCall9ba61662010-02-26 08:45:28 +00001454/// This returns true if an error occurred.
Mike Stump1eb44332009-09-09 15:08:12 +00001455///
Chris Lattner55a7cef2009-01-05 00:13:00 +00001456/// Note that this routine emits an error if you call it with ::new or ::delete
1457/// as the current tokens, so only call it in contexts where these are invalid.
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001458bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001459 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
David Blaikie42d6d0c2011-12-04 05:04:18 +00001460 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
Richard Smith23756772012-05-14 22:43:34 +00001461 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1462 && "Cannot be a type or scope token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregord57959a2009-03-27 23:10:48 +00001464 if (Tok.is(tok::kw_typename)) {
1465 // Parse a C++ typename-specifier, e.g., "typename T::type".
1466 //
1467 // typename-specifier:
1468 // 'typename' '::' [opt] nested-name-specifier identifier
Mike Stump1eb44332009-09-09 15:08:12 +00001469 // 'typename' '::' [opt] nested-name-specifier template [opt]
Douglas Gregor17343172009-04-01 00:28:59 +00001470 // simple-template-id
Douglas Gregord57959a2009-03-27 23:10:48 +00001471 SourceLocation TypenameLoc = ConsumeToken();
1472 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +00001473 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1474 /*EnteringContext=*/false,
Francois Pichet4147d302011-03-27 19:41:34 +00001475 0, /*IsTypename*/true))
John McCall9ba61662010-02-26 08:45:28 +00001476 return true;
1477 if (!SS.isSet()) {
Francois Pichetb67e7fc2012-07-22 15:10:57 +00001478 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1479 Tok.is(tok::annot_decltype)) {
Richard Smith23756772012-05-14 22:43:34 +00001480 // Attempt to recover by skipping the invalid 'typename'
Francois Pichetb67e7fc2012-07-22 15:10:57 +00001481 if (Tok.is(tok::annot_decltype) ||
1482 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1483 Tok.isAnnotation())) {
Richard Smith23756772012-05-14 22:43:34 +00001484 unsigned DiagID = diag::err_expected_qualified_after_typename;
1485 // MS compatibility: MSVC permits using known types with typename.
1486 // e.g. "typedef typename T* pointer_type"
1487 if (getLangOpts().MicrosoftExt)
1488 DiagID = diag::warn_expected_qualified_after_typename;
1489 Diag(Tok.getLocation(), DiagID);
1490 return false;
1491 }
1492 }
1493
1494 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
John McCall9ba61662010-02-26 08:45:28 +00001495 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00001496 }
1497
1498 TypeResult Ty;
1499 if (Tok.is(tok::identifier)) {
1500 // FIXME: check whether the next token is '<', first!
Douglas Gregor23c94db2010-07-02 17:43:08 +00001501 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001502 *Tok.getIdentifierInfo(),
Douglas Gregord57959a2009-03-27 23:10:48 +00001503 Tok.getLocation());
Douglas Gregor17343172009-04-01 00:28:59 +00001504 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001505 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor17343172009-04-01 00:28:59 +00001506 if (TemplateId->Kind == TNK_Function_template) {
1507 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1508 << Tok.getAnnotationRange();
John McCall9ba61662010-02-26 08:45:28 +00001509 return true;
Douglas Gregor17343172009-04-01 00:28:59 +00001510 }
Douglas Gregord57959a2009-03-27 23:10:48 +00001511
Benjamin Kramer5354e772012-08-23 23:38:35 +00001512 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregora02411e2011-02-27 22:46:49 +00001513 TemplateId->NumArgs);
Abramo Bagnara66581d42012-02-06 22:45:07 +00001514
Douglas Gregora02411e2011-02-27 22:46:49 +00001515 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Abramo Bagnara66581d42012-02-06 22:45:07 +00001516 TemplateId->TemplateKWLoc,
Douglas Gregora02411e2011-02-27 22:46:49 +00001517 TemplateId->Template,
1518 TemplateId->TemplateNameLoc,
1519 TemplateId->LAngleLoc,
Abramo Bagnara66581d42012-02-06 22:45:07 +00001520 TemplateArgsPtr,
Douglas Gregora02411e2011-02-27 22:46:49 +00001521 TemplateId->RAngleLoc);
Douglas Gregor17343172009-04-01 00:28:59 +00001522 } else {
1523 Diag(Tok, diag::err_expected_type_name_after_typename)
1524 << SS.getRange();
John McCall9ba61662010-02-26 08:45:28 +00001525 return true;
Douglas Gregor17343172009-04-01 00:28:59 +00001526 }
1527
Sebastian Redl39d67112010-02-08 19:35:18 +00001528 SourceLocation EndLoc = Tok.getLastLoc();
Douglas Gregor17343172009-04-01 00:28:59 +00001529 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +00001530 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
Sebastian Redl39d67112010-02-08 19:35:18 +00001531 Tok.setAnnotationEndLoc(EndLoc);
Douglas Gregor17343172009-04-01 00:28:59 +00001532 Tok.setLocation(TypenameLoc);
1533 PP.AnnotateCachedTokens(Tok);
John McCall9ba61662010-02-26 08:45:28 +00001534 return false;
Douglas Gregord57959a2009-03-27 23:10:48 +00001535 }
1536
John McCallae03cb52009-12-19 00:35:18 +00001537 // Remembers whether the token was originally a scope annotation.
Richard Smith05766812012-08-18 00:55:03 +00001538 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
John McCallae03cb52009-12-19 00:35:18 +00001539
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001540 CXXScopeSpec SS;
David Blaikie4e4d0842012-03-11 07:00:24 +00001541 if (getLangOpts().CPlusPlus)
John McCallb3d87482010-08-24 05:47:05 +00001542 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall9ba61662010-02-26 08:45:28 +00001543 return true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001544
Richard Smith05766812012-08-18 00:55:03 +00001545 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1546 SS, !WasScopeAnnotation);
1547}
1548
1549/// \brief Try to annotate a type or scope token, having already parsed an
1550/// optional scope specifier. \p IsNewScope should be \c true unless the scope
1551/// specifier was extracted from an existing tok::annot_cxxscope annotation.
1552bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1553 bool NeedType,
1554 CXXScopeSpec &SS,
1555 bool IsNewScope) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001556 if (Tok.is(tok::identifier)) {
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001557 IdentifierInfo *CorrectedII = 0;
Chris Lattner608d1fc2009-01-05 01:49:50 +00001558 // Determine whether the identifier is a type name.
John McCallb3d87482010-08-24 05:47:05 +00001559 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1560 Tok.getLocation(), getCurScope(),
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00001561 &SS, false,
Douglas Gregor9e876872011-03-01 18:12:44 +00001562 NextToken().is(tok::period),
1563 ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +00001564 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +00001565 /*NonTrivialTypeSourceInfo*/true,
1566 NeedType ? &CorrectedII : NULL)) {
1567 // A FixIt was applied as a result of typo correction
1568 if (CorrectedII)
1569 Tok.setIdentifierInfo(CorrectedII);
Chris Lattner608d1fc2009-01-05 01:49:50 +00001570 // This is a typename. Replace the current token in-place with an
1571 // annotation type token.
Chris Lattnerb31757b2009-01-06 05:06:21 +00001572 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +00001573 setTypeAnnotation(Tok, Ty);
Chris Lattner608d1fc2009-01-05 01:49:50 +00001574 Tok.setAnnotationEndLoc(Tok.getLocation());
1575 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1576 Tok.setLocation(SS.getBeginLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner608d1fc2009-01-05 01:49:50 +00001578 // In case the tokens were cached, have Preprocessor replace
1579 // them with the annotation token.
1580 PP.AnnotateCachedTokens(Tok);
John McCall9ba61662010-02-26 08:45:28 +00001581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001582 }
Douglas Gregor39a8de12009-02-25 19:37:18 +00001583
David Blaikie4e4d0842012-03-11 07:00:24 +00001584 if (!getLangOpts().CPlusPlus) {
Chris Lattner608d1fc2009-01-05 01:49:50 +00001585 // If we're in C, we can't have :: tokens at all (the lexer won't return
1586 // them). If the identifier is not a type, then it can't be scope either,
Mike Stump1eb44332009-09-09 15:08:12 +00001587 // just early exit.
Chris Lattner608d1fc2009-01-05 01:49:50 +00001588 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor39a8de12009-02-25 19:37:18 +00001591 // If this is a template-id, annotate with a template-id or type token.
Douglas Gregor55f6b142009-02-09 18:46:07 +00001592 if (NextToken().is(tok::less)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001593 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001594 UnqualifiedId TemplateName;
1595 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001596 bool MemberOfUnknownSpecialization;
Mike Stump1eb44332009-09-09 15:08:12 +00001597 if (TemplateNameKind TNK
Abramo Bagnara7c153532010-08-06 12:11:11 +00001598 = Actions.isTemplateName(getCurScope(), SS,
1599 /*hasTemplateKeyword=*/false, TemplateName,
John McCallb3d87482010-08-24 05:47:05 +00001600 /*ObjectType=*/ ParsedType(),
1601 EnteringContext,
Abramo Bagnara7c153532010-08-06 12:11:11 +00001602 Template, MemberOfUnknownSpecialization)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001603 // Consume the identifier.
1604 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001605 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1606 TemplateName)) {
Chris Lattnerc8e27cc2009-06-26 04:27:47 +00001607 // If an unrecoverable error occurred, we need to return true here,
1608 // because the token stream is in a damaged state. We may not return
1609 // a valid identifier.
John McCall9ba61662010-02-26 08:45:28 +00001610 return true;
Chris Lattnerc8e27cc2009-06-26 04:27:47 +00001611 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001612 }
Douglas Gregor55f6b142009-02-09 18:46:07 +00001613 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001614
Douglas Gregor39a8de12009-02-25 19:37:18 +00001615 // The current token, which is either an identifier or a
1616 // template-id, is not part of the annotation. Fall through to
1617 // push that token back into the stream and complete the C++ scope
1618 // specifier annotation.
Mike Stump1eb44332009-09-09 15:08:12 +00001619 }
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001620
Douglas Gregor39a8de12009-02-25 19:37:18 +00001621 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00001622 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001623 if (TemplateId->Kind == TNK_Type_template) {
Douglas Gregor39a8de12009-02-25 19:37:18 +00001624 // A template-id that refers to a type was parsed into a
1625 // template-id annotation in a context where we weren't allowed
1626 // to produce a type annotation token. Update the template-id
1627 // annotation token to a type annotation token now.
Douglas Gregor059101f2011-03-02 00:47:37 +00001628 AnnotateTemplateIdTokenAsType();
John McCall9ba61662010-02-26 08:45:28 +00001629 return false;
Douglas Gregor39a8de12009-02-25 19:37:18 +00001630 }
1631 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001632
Chris Lattner6ec76d42009-01-04 22:32:19 +00001633 if (SS.isEmpty())
John McCall9ba61662010-02-26 08:45:28 +00001634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Chris Lattner6ec76d42009-01-04 22:32:19 +00001636 // A C++ scope specifier that isn't followed by a typename.
Richard Smith05766812012-08-18 00:55:03 +00001637 AnnotateScopeToken(SS, IsNewScope);
John McCall9ba61662010-02-26 08:45:28 +00001638 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001639}
1640
1641/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Douglas Gregor39a8de12009-02-25 19:37:18 +00001642/// annotates C++ scope specifiers and template-ids. This returns
Richard Smith83a22ec2012-05-09 08:23:23 +00001643/// true if there was an error that could not be recovered from.
Mike Stump1eb44332009-09-09 15:08:12 +00001644///
Chris Lattner55a7cef2009-01-05 00:13:00 +00001645/// Note that this routine emits an error if you call it with ::new or ::delete
1646/// as the current tokens, so only call it in contexts where these are invalid.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001647bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001648 assert(getLangOpts().CPlusPlus &&
Chris Lattner6ec76d42009-01-04 22:32:19 +00001649 "Call sites of this function should be guarded by checking for C++");
Douglas Gregor3b887352011-04-27 04:48:22 +00001650 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
David Blaikie42d6d0c2011-12-04 05:04:18 +00001651 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1652 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001653
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +00001654 CXXScopeSpec SS;
John McCallb3d87482010-08-24 05:47:05 +00001655 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall9ba61662010-02-26 08:45:28 +00001656 return true;
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00001657 if (SS.isEmpty())
John McCall9ba61662010-02-26 08:45:28 +00001658 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001659
Richard Smith05766812012-08-18 00:55:03 +00001660 AnnotateScopeToken(SS, true);
John McCall9ba61662010-02-26 08:45:28 +00001661 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001662}
John McCall6c94a6d2009-11-03 19:33:12 +00001663
Richard Trieufcaf27e2012-01-19 22:01:51 +00001664bool Parser::isTokenEqualOrEqualTypo() {
1665 tok::TokenKind Kind = Tok.getKind();
1666 switch (Kind) {
1667 default:
Richard Trieud6c7c672012-01-18 22:54:52 +00001668 return false;
Richard Trieufcaf27e2012-01-19 22:01:51 +00001669 case tok::ampequal: // &=
1670 case tok::starequal: // *=
1671 case tok::plusequal: // +=
1672 case tok::minusequal: // -=
1673 case tok::exclaimequal: // !=
1674 case tok::slashequal: // /=
1675 case tok::percentequal: // %=
1676 case tok::lessequal: // <=
1677 case tok::lesslessequal: // <<=
1678 case tok::greaterequal: // >=
1679 case tok::greatergreaterequal: // >>=
1680 case tok::caretequal: // ^=
1681 case tok::pipeequal: // |=
1682 case tok::equalequal: // ==
1683 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1684 << getTokenSimpleSpelling(Kind)
1685 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1686 case tok::equal:
1687 return true;
1688 }
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001689}
1690
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001691SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1692 assert(Tok.is(tok::code_completion));
1693 PrevTokLocation = Tok.getLocation();
1694
Douglas Gregor23c94db2010-07-02 17:43:08 +00001695 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregordc845342010-05-25 05:58:43 +00001696 if (S->getFlags() & Scope::FnScope) {
John McCallf312b1e2010-08-26 23:41:50 +00001697 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001698 cutOffParsing();
1699 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001700 }
1701
1702 if (S->getFlags() & Scope::ClassScope) {
John McCallf312b1e2010-08-26 23:41:50 +00001703 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001704 cutOffParsing();
1705 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001706 }
1707 }
1708
John McCallf312b1e2010-08-26 23:41:50 +00001709 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001710 cutOffParsing();
1711 return PrevTokLocation;
Douglas Gregordc845342010-05-25 05:58:43 +00001712}
1713
John McCall6c94a6d2009-11-03 19:33:12 +00001714// Anchor the Parser::FieldCallback vtable to this translation unit.
1715// We use a spurious method instead of the destructor because
1716// destroying FieldCallbacks can actually be slightly
1717// performance-sensitive.
1718void Parser::FieldCallback::_anchor() {
1719}
Douglas Gregorf44e8542010-08-24 19:08:16 +00001720
1721// Code-completion pass-through functions
1722
1723void Parser::CodeCompleteDirective(bool InConditional) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00001724 Actions.CodeCompletePreprocessorDirective(InConditional);
Douglas Gregorf44e8542010-08-24 19:08:16 +00001725}
1726
1727void Parser::CodeCompleteInConditionalExclusion() {
1728 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1729}
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001730
1731void Parser::CodeCompleteMacroName(bool IsDefinition) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00001732 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1733}
1734
1735void Parser::CodeCompletePreprocessorExpression() {
1736 Actions.CodeCompletePreprocessorExpression();
1737}
1738
1739void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1740 MacroInfo *MacroInfo,
1741 unsigned ArgumentIndex) {
1742 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1743 ArgumentIndex);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001744}
Douglas Gregor55817af2010-08-25 17:04:25 +00001745
1746void Parser::CodeCompleteNaturalLanguage() {
1747 Actions.CodeCompleteNaturalLanguage();
1748}
Francois Pichetf9860382011-05-07 17:30:27 +00001749
Douglas Gregor3896fc52011-10-24 22:31:10 +00001750bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
Francois Pichetf9860382011-05-07 17:30:27 +00001751 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1752 "Expected '__if_exists' or '__if_not_exists'");
Douglas Gregor3896fc52011-10-24 22:31:10 +00001753 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1754 Result.KeywordLoc = ConsumeToken();
Francois Pichetf9860382011-05-07 17:30:27 +00001755
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001756 BalancedDelimiterTracker T(*this, tok::l_paren);
1757 if (T.consumeOpen()) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001758 Diag(Tok, diag::err_expected_lparen_after)
1759 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
Francois Pichetf9860382011-05-07 17:30:27 +00001760 return true;
1761 }
Francois Pichetf9860382011-05-07 17:30:27 +00001762
1763 // Parse nested-name-specifier.
Douglas Gregorefaa93a2011-11-07 17:33:42 +00001764 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1765 /*EnteringContext=*/false);
Francois Pichetf9860382011-05-07 17:30:27 +00001766
1767 // Check nested-name specifier.
Douglas Gregor3896fc52011-10-24 22:31:10 +00001768 if (Result.SS.isInvalid()) {
1769 T.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001770 return true;
1771 }
1772
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001773 // Parse the unqualified-id.
1774 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1775 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1776 TemplateKWLoc, Result.Name)) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001777 T.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001778 return true;
1779 }
1780
Douglas Gregor3896fc52011-10-24 22:31:10 +00001781 if (T.consumeClose())
Francois Pichetf9860382011-05-07 17:30:27 +00001782 return true;
Douglas Gregor3896fc52011-10-24 22:31:10 +00001783
Francois Pichetf9860382011-05-07 17:30:27 +00001784 // Check if the symbol exists.
Douglas Gregor65019ac2011-10-25 03:44:56 +00001785 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1786 Result.IsIfExists, Result.SS,
Douglas Gregor3896fc52011-10-24 22:31:10 +00001787 Result.Name)) {
1788 case Sema::IER_Exists:
1789 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1790 break;
Francois Pichetf9860382011-05-07 17:30:27 +00001791
Douglas Gregor3896fc52011-10-24 22:31:10 +00001792 case Sema::IER_DoesNotExist:
1793 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1794 break;
1795
1796 case Sema::IER_Dependent:
1797 Result.Behavior = IEB_Dependent;
1798 break;
Douglas Gregor65019ac2011-10-25 03:44:56 +00001799
1800 case Sema::IER_Error:
1801 return true;
Douglas Gregor3896fc52011-10-24 22:31:10 +00001802 }
Francois Pichetf9860382011-05-07 17:30:27 +00001803
1804 return false;
1805}
1806
Francois Pichet563a6452011-05-25 10:19:49 +00001807void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001808 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00001809 if (ParseMicrosoftIfExistsCondition(Result))
1810 return;
1811
Douglas Gregor3896fc52011-10-24 22:31:10 +00001812 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1813 if (Braces.consumeOpen()) {
Francois Pichetf9860382011-05-07 17:30:27 +00001814 Diag(Tok, diag::err_expected_lbrace);
1815 return;
1816 }
Francois Pichetf9860382011-05-07 17:30:27 +00001817
Douglas Gregor3896fc52011-10-24 22:31:10 +00001818 switch (Result.Behavior) {
1819 case IEB_Parse:
1820 // Parse declarations below.
1821 break;
1822
1823 case IEB_Dependent:
1824 llvm_unreachable("Cannot have a dependent external declaration");
1825
1826 case IEB_Skip:
1827 Braces.skipToEnd();
Francois Pichetf9860382011-05-07 17:30:27 +00001828 return;
1829 }
1830
Douglas Gregor3896fc52011-10-24 22:31:10 +00001831 // Parse the declarations.
1832 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Francois Pichetf9860382011-05-07 17:30:27 +00001833 ParsedAttributesWithRange attrs(AttrFactory);
1834 MaybeParseCXX0XAttributes(attrs);
1835 MaybeParseMicrosoftAttributes(attrs);
1836 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1837 if (Result && !getCurScope()->getParent())
1838 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00001839 }
1840 Braces.consumeClose();
Francois Pichetf9860382011-05-07 17:30:27 +00001841}
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001842
Douglas Gregor5948ae12012-01-03 18:04:46 +00001843Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
Ted Kremenek32ad2ee2012-03-01 22:07:04 +00001844 assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&
Douglas Gregor65030af2011-08-31 18:19:09 +00001845 "Improper start to module import");
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001846 SourceLocation ImportLoc = ConsumeToken();
1847
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001848 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001849
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001850 // Parse the module path.
1851 do {
1852 if (!Tok.is(tok::identifier)) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001853 if (Tok.is(tok::code_completion)) {
1854 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1855 ConsumeCodeCompletionToken();
1856 SkipUntil(tok::semi);
1857 return DeclGroupPtrTy();
1858 }
1859
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001860 Diag(Tok, diag::err_module_expected_ident);
1861 SkipUntil(tok::semi);
1862 return DeclGroupPtrTy();
1863 }
1864
1865 // Record this part of the module path.
1866 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1867 ConsumeToken();
1868
1869 if (Tok.is(tok::period)) {
1870 ConsumeToken();
1871 continue;
1872 }
1873
1874 break;
1875 } while (true);
1876
Douglas Gregor5948ae12012-01-03 18:04:46 +00001877 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001878 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1879 if (Import.isInvalid())
1880 return DeclGroupPtrTy();
1881
1882 return Actions.ConvertDeclToDeclGroup(Import.get());
1883}
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001884
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001885bool BalancedDelimiterTracker::diagnoseOverflow() {
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001886 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1887 P.SkipUntil(tok::eof);
1888 return true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001889}
1890
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001891bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001892 const char *Msg,
1893 tok::TokenKind SkipToToc ) {
1894 LOpen = P.Tok.getLocation();
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001895 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1896 return true;
1897
1898 if (getDepth() < MaxDepth)
1899 return false;
1900
1901 return diagnoseOverflow();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001902}
1903
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001904bool BalancedDelimiterTracker::diagnoseMissingClose() {
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001905 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1906
1907 const char *LHSName = "unknown";
David Blaikieb031eab2012-04-06 23:33:59 +00001908 diag::kind DID;
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001909 switch (Close) {
David Blaikieb031eab2012-04-06 23:33:59 +00001910 default: llvm_unreachable("Unexpected balanced token");
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001911 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1912 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1913 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001914 }
Douglas Gregord78ef5b2012-03-08 01:00:17 +00001915 P.Diag(P.Tok, DID);
1916 P.Diag(LOpen, diag::note_matching) << LHSName;
1917 if (P.SkipUntil(Close))
1918 LClose = P.Tok.getLocation();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001919 return true;
1920}
Douglas Gregor3896fc52011-10-24 22:31:10 +00001921
Douglas Gregorc86c40b2012-06-06 21:18:07 +00001922void BalancedDelimiterTracker::skipToEnd() {
Douglas Gregor3896fc52011-10-24 22:31:10 +00001923 P.SkipUntil(Close, false);
Douglas Gregor3896fc52011-10-24 22:31:10 +00001924}