blob: e95af05411185f59781eb2fa54feb3f5a135c41f [file] [log] [blame]
Chris Lattnereb8a28f2006-08-10 18:43:39 +00001//===--- Parser.cpp - C Language Family Parser ----------------------------===//
Chris Lattner0bb5f832006-07-31 01:59:18 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner0bb5f832006-07-31 01:59:18 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner60f36222009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
Chris Lattnerbcfe4f72009-03-05 07:24:28 +000019#include "llvm/Support/raw_ostream.h"
Chris Lattner8a9a97a2009-12-10 00:21:05 +000020#include "RAIIObjectsForParser.h"
Daniel Dunbar921b9682008-10-04 19:21:03 +000021#include "ParsePragma.h"
Francois Pichet1c229c02011-04-22 22:18:13 +000022#include "clang/AST/DeclTemplate.h"
Francois Picheta5b3fcb2011-05-07 17:30:27 +000023#include "clang/AST/ASTConsumer.h"
Chris Lattner0bb5f832006-07-31 01:59:18 +000024using namespace clang;
25
Benjamin Kramer7ca3b7c2012-07-13 13:25:11 +000026namespace {
Dmitri Gribenkoaab83832012-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 Kramer7ca3b7c2012-07-13 13:25:11 +000040} // end anonymous namespace
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000041
Douglas Gregor60060d62011-10-21 03:57:52 +000042IdentifierInfo *Parser::getSEHExceptKeyword() {
43 // __except is accepted as a (contextual) keyword
David Blaikiebbafb8a2012-03-11 07:00:24 +000044 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
Douglas Gregor60060d62011-10-21 03:57:52 +000045 Ident__except = PP.getIdentifierInfo("__except");
46
47 return Ident__except;
48}
49
Erik Verbruggen6e922512012-04-12 10:11:59 +000050Parser::Parser(Preprocessor &pp, Sema &actions, bool SkipFunctionBodies)
Ted Kremenek4c9d46b2011-03-22 01:15:17 +000051 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
Douglas Gregore9bba4f2010-09-15 14:51:05 +000052 GreaterThanIsOperator(true), ColonIsSacred(false),
Erik Verbruggen6e922512012-04-12 10:11:59 +000053 InMessageExpression(false), TemplateParameterDepth(0),
Jordan Rose12e730c2012-07-09 16:54:53 +000054 ParsingInObjCContainer(false), SkipFunctionBodies(SkipFunctionBodies) {
Chris Lattner8c204872006-10-14 05:19:21 +000055 Tok.setKind(tok::eof);
Douglas Gregor0be31a22010-07-02 17:43:08 +000056 Actions.CurScope = 0;
Chris Lattner03928c72007-07-15 00:04:39 +000057 NumCachedScopes = 0;
Chris Lattnereec40f92006-08-06 21:55:29 +000058 ParenCount = BracketCount = BraceCount = 0;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +000059 CurParsedObjCImpl = 0;
Daniel Dunbar921b9682008-10-04 19:21:03 +000060
61 // Add #pragma handlers. These are removed and destroyed in the
62 // destructor.
Daniel Dunbarcb82acb2010-07-31 19:17:07 +000063 AlignHandler.reset(new PragmaAlignHandler(actions));
64 PP.AddPragmaHandler(AlignHandler.get());
65
Eli Friedman570024a2010-08-05 06:57:20 +000066 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
67 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
68
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000069 OptionsHandler.reset(new PragmaOptionsHandler(actions));
70 PP.AddPragmaHandler(OptionsHandler.get());
Daniel Dunbar75c9be72010-05-26 23:29:06 +000071
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000072 PackHandler.reset(new PragmaPackHandler(actions));
73 PP.AddPragmaHandler(PackHandler.get());
Fariborz Jahanian743dda42011-04-25 18:49:15 +000074
75 MSStructHandler.reset(new PragmaMSStructHandler(actions));
76 PP.AddPragmaHandler(MSStructHandler.get());
Mike Stump11289f42009-09-09 15:08:12 +000077
Benjamin Kramerd1d76b22012-06-06 17:32:50 +000078 UnusedHandler.reset(new PragmaUnusedHandler(actions));
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000079 PP.AddPragmaHandler(UnusedHandler.get());
Eli Friedmanf5867dd2009-06-05 00:49:58 +000080
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000081 WeakHandler.reset(new PragmaWeakHandler(actions));
82 PP.AddPragmaHandler(WeakHandler.get());
Peter Collingbourne564c0fa2011-02-14 01:42:35 +000083
David Chisnall0867d9c2012-02-18 16:12:34 +000084 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler(actions));
85 PP.AddPragmaHandler(RedefineExtnameHandler.get());
86
Benjamin Kramerd1d76b22012-06-06 17:32:50 +000087 FPContractHandler.reset(new PragmaFPContractHandler(actions));
Peter Collingbourne564c0fa2011-02-14 01:42:35 +000088 PP.AddPragmaHandler("STDC", FPContractHandler.get());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +000089
David Blaikiebbafb8a2012-03-11 07:00:24 +000090 if (getLangOpts().OpenCL) {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +000091 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler(actions));
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +000092 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
93
94 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
95 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000096
Dmitri Gribenko17e147f2012-06-20 01:06:08 +000097 CommentSemaHandler.reset(new ActionCommentHandler(actions));
98 PP.addCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000099
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000100 PP.setCodeCompletionHandler(*this);
Chris Lattner971c6b62006-08-05 22:46:42 +0000101}
102
Chris Lattnerbcfe4f72009-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 Lattner0e62c1c2011-07-23 10:55:15 +0000105void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000106 const Token &Tok = P.getCurToken();
Chris Lattnerf02db352009-03-05 07:27:50 +0000107 if (Tok.is(tok::eof)) {
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000108 OS << "<eof> parser at end of file\n";
109 return;
110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Chris Lattnerf02db352009-03-05 07:27:50 +0000112 if (Tok.getLocation().isInvalid()) {
113 OS << "<unknown> parser at unknown location\n";
114 return;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000117 const Preprocessor &PP = P.getPreprocessor();
118 Tok.getLocation().print(OS, PP.getSourceManager());
Daniel Dunbar68d9d7b2009-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 Gregord7c4d982008-12-30 03:27:21 +0000123}
Chris Lattner0bb5f832006-07-31 01:59:18 +0000124
Chris Lattnerbcfe4f72009-03-05 07:24:28 +0000125
Chris Lattner427c9c12008-11-22 00:59:29 +0000126DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000127 return Diags.Report(Loc, DiagID);
Chris Lattner6d29c102008-11-18 07:48:38 +0000128}
129
Chris Lattner427c9c12008-11-22 00:59:29 +0000130DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000131 return Diag(Tok.getLocation(), DiagID);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000132}
133
Douglas Gregor87f95b02009-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.
138/// \param Loc The kind of diagnostic to emit.
139/// \param ParenRange Source range enclosing code that should be parenthesized.
140void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
141 SourceRange ParenRange) {
Douglas Gregor96977da2009-02-27 17:53:17 +0000142 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
143 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
Douglas Gregor87f95b02009-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 Stump11289f42009-09-09 15:08:12 +0000149
150 Diag(Loc, DK)
Douglas Gregora771f462010-03-31 17:46:05 +0000151 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
152 << FixItHint::CreateInsertion(EndLoc, ")");
Douglas Gregor87f95b02009-02-26 21:00:50 +0000153}
154
John McCall1ca73da2010-09-07 18:31:03 +0000155static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
156 switch (ExpectedTok) {
157 case tok::semi: return Tok.is(tok::colon); // : for ;
158 default: return false;
159 }
160}
161
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000162/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
163/// input. If so, it is consumed and false is returned.
164///
165/// If the input is malformed, this emits the specified diagnostic. Next, if
166/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
167/// returned.
168bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
Chris Lattner6d7e6342006-08-15 03:41:14 +0000169 const char *Msg, tok::TokenKind SkipToTok) {
Douglas Gregor6da3db42010-05-25 05:58:43 +0000170 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
Chris Lattner15a00da2006-08-15 04:10:31 +0000171 ConsumeAnyToken();
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000172 return false;
173 }
Mike Stump01e07652008-06-19 19:28:49 +0000174
John McCall1ca73da2010-09-07 18:31:03 +0000175 // Detect common single-character typos and resume.
176 if (IsCommonTypo(ExpectedTok, Tok)) {
177 SourceLocation Loc = Tok.getLocation();
178 Diag(Loc, DiagID)
179 << Msg
180 << FixItHint::CreateReplacement(SourceRange(Loc),
181 getTokenSimpleSpelling(ExpectedTok));
182 ConsumeAnyToken();
183
184 // Pretend there wasn't a problem.
185 return false;
186 }
187
Douglas Gregor87f95b02009-02-26 21:00:50 +0000188 const char *Spelling = 0;
Douglas Gregor96977da2009-02-27 17:53:17 +0000189 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
Mike Stump11289f42009-09-09 15:08:12 +0000190 if (EndLoc.isValid() &&
Douglas Gregor96977da2009-02-27 17:53:17 +0000191 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
Douglas Gregor87f95b02009-02-26 21:00:50 +0000192 // Show what code to insert to fix this problem.
Mike Stump11289f42009-09-09 15:08:12 +0000193 Diag(EndLoc, DiagID)
Douglas Gregor87f95b02009-02-26 21:00:50 +0000194 << Msg
Douglas Gregora771f462010-03-31 17:46:05 +0000195 << FixItHint::CreateInsertion(EndLoc, Spelling);
Douglas Gregor87f95b02009-02-26 21:00:50 +0000196 } else
197 Diag(Tok, DiagID) << Msg;
198
Chris Lattnerdbb2a462006-08-12 19:26:13 +0000199 if (SkipToTok != tok::unknown)
200 SkipUntil(SkipToTok);
201 return true;
202}
203
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000204bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
205 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
Douglas Gregor25c16092012-05-02 14:34:16 +0000206 ConsumeToken();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000207 return false;
208 }
209
210 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
211 NextToken().is(tok::semi)) {
212 Diag(Tok, diag::err_extraneous_token_before_semi)
213 << PP.getSpelling(Tok)
214 << FixItHint::CreateRemoval(Tok.getLocation());
215 ConsumeAnyToken(); // The ')' or ']'.
216 ConsumeToken(); // The ';'.
217 return false;
218 }
219
220 return ExpectAndConsume(tok::semi, DiagID);
221}
222
Richard Trieu2f7dc462012-05-16 19:04:59 +0000223void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, const char* DiagMsg) {
224 if (!Tok.is(tok::semi)) return;
225
226 // AfterDefinition should only warn when placed on the same line as the
227 // definition. Otherwise, defer to another semi warning.
228 if (Kind == AfterDefinition && Tok.isAtStartOfLine()) return;
229
230 SourceLocation StartLoc = Tok.getLocation();
231 SourceLocation EndLoc = Tok.getLocation();
232 ConsumeToken();
233
234 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
235 EndLoc = Tok.getLocation();
236 ConsumeToken();
237 }
238
239 if (Kind == OutsideFunction && getLangOpts().CPlusPlus0x) {
240 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
241 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
242 return;
243 }
244
245 Diag(StartLoc, diag::ext_extra_semi)
246 << Kind << DiagMsg << FixItHint::CreateRemoval(SourceRange(StartLoc,
247 EndLoc));
248}
249
Chris Lattner70f32b72006-07-31 05:09:04 +0000250//===----------------------------------------------------------------------===//
Chris Lattnereec40f92006-08-06 21:55:29 +0000251// Error recovery.
252//===----------------------------------------------------------------------===//
253
254/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner01e4b242007-07-24 17:03:04 +0000255/// it (unless DontConsume is true). Because we cannot guarantee that the
Chris Lattnereec40f92006-08-06 21:55:29 +0000256/// token will ever occur, this skips to the next token, or to some likely
257/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
258/// character.
Mike Stump01e07652008-06-19 19:28:49 +0000259///
Chris Lattnereec40f92006-08-06 21:55:29 +0000260/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stump01e07652008-06-19 19:28:49 +0000261/// returns false.
David Blaikie80cdddc2012-04-09 16:37:11 +0000262bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
263 bool DontConsume, bool StopAtCodeCompletion) {
Chris Lattner5bd57e02006-08-11 06:40:25 +0000264 // We always want this function to skip at least one token if the first token
265 // isn't T and if not at EOF.
266 bool isFirstTokenSkipped = true;
Chris Lattnereec40f92006-08-06 21:55:29 +0000267 while (1) {
Chris Lattner83b94e02007-04-27 19:12:15 +0000268 // If we found one of the tokens, stop and return true.
David Blaikie80cdddc2012-04-09 16:37:11 +0000269 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
Chris Lattner0ab032a2007-10-09 17:23:58 +0000270 if (Tok.is(Toks[i])) {
Chris Lattner83b94e02007-04-27 19:12:15 +0000271 if (DontConsume) {
272 // Noop, don't consume the token.
273 } else {
274 ConsumeAnyToken();
275 }
276 return true;
Chris Lattnereec40f92006-08-06 21:55:29 +0000277 }
Chris Lattnereec40f92006-08-06 21:55:29 +0000278 }
Mike Stump01e07652008-06-19 19:28:49 +0000279
Chris Lattnereec40f92006-08-06 21:55:29 +0000280 switch (Tok.getKind()) {
281 case tok::eof:
282 // Ran out of tokens.
283 return false;
Douglas Gregor6da3db42010-05-25 05:58:43 +0000284
285 case tok::code_completion:
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000286 if (!StopAtCodeCompletion)
287 ConsumeToken();
Douglas Gregor6da3db42010-05-25 05:58:43 +0000288 return false;
289
Chris Lattnereec40f92006-08-06 21:55:29 +0000290 case tok::l_paren:
291 // Recursively skip properly-nested parens.
292 ConsumeParen();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000293 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000294 break;
295 case tok::l_square:
296 // Recursively skip properly-nested square brackets.
297 ConsumeBracket();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000298 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000299 break;
300 case tok::l_brace:
301 // Recursively skip properly-nested braces.
302 ConsumeBrace();
Argyrios Kyrtzidis76dbe8c2011-01-03 19:44:02 +0000303 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
Chris Lattnereec40f92006-08-06 21:55:29 +0000304 break;
Mike Stump01e07652008-06-19 19:28:49 +0000305
Chris Lattnereec40f92006-08-06 21:55:29 +0000306 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
307 // Since the user wasn't looking for this token (if they were, it would
308 // already be handled), this isn't balanced. If there is a LHS token at a
309 // higher level, we will assume that this matches the unbalanced token
310 // and return it. Otherwise, this is a spurious RHS token, which we skip.
311 case tok::r_paren:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000312 if (ParenCount && !isFirstTokenSkipped)
313 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000314 ConsumeParen();
315 break;
316 case tok::r_square:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000317 if (BracketCount && !isFirstTokenSkipped)
318 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000319 ConsumeBracket();
320 break;
321 case tok::r_brace:
Chris Lattner5bd57e02006-08-11 06:40:25 +0000322 if (BraceCount && !isFirstTokenSkipped)
323 return false; // Matches something.
Chris Lattnereec40f92006-08-06 21:55:29 +0000324 ConsumeBrace();
325 break;
Mike Stump01e07652008-06-19 19:28:49 +0000326
Chris Lattnereec40f92006-08-06 21:55:29 +0000327 case tok::string_literal:
Chris Lattnerd3e98952006-10-06 05:22:26 +0000328 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000329 case tok::utf8_string_literal:
330 case tok::utf16_string_literal:
331 case tok::utf32_string_literal:
Chris Lattnereec40f92006-08-06 21:55:29 +0000332 ConsumeStringToken();
333 break;
Fariborz Jahanian82ff1e52011-02-23 00:11:21 +0000334
Chris Lattnereec40f92006-08-06 21:55:29 +0000335 case tok::semi:
336 if (StopAtSemi)
337 return false;
338 // FALL THROUGH.
339 default:
340 // Skip this token.
341 ConsumeToken();
342 break;
343 }
Chris Lattner5bd57e02006-08-11 06:40:25 +0000344 isFirstTokenSkipped = false;
Mike Stump01e07652008-06-19 19:28:49 +0000345 }
Chris Lattnereec40f92006-08-06 21:55:29 +0000346}
347
348//===----------------------------------------------------------------------===//
Chris Lattnere4e38592006-08-14 00:15:05 +0000349// Scope manipulation
350//===----------------------------------------------------------------------===//
351
352/// EnterScope - Start a new scope.
Chris Lattner33ad2ca2006-11-05 23:47:55 +0000353void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner03928c72007-07-15 00:04:39 +0000354 if (NumCachedScopes) {
355 Scope *N = ScopeCache[--NumCachedScopes];
Douglas Gregor0be31a22010-07-02 17:43:08 +0000356 N->Init(getCurScope(), ScopeFlags);
357 Actions.CurScope = N;
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000358 } else {
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +0000359 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000360 }
Chris Lattnere4e38592006-08-14 00:15:05 +0000361}
362
363/// ExitScope - Pop a scope off the scope stack.
364void Parser::ExitScope() {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000365 assert(getCurScope() && "Scope imbalance!");
Chris Lattnere4e38592006-08-14 00:15:05 +0000366
Chris Lattner87547e62007-10-09 20:37:18 +0000367 // Inform the actions module that this scope is going away if there are any
368 // decls in it.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000369 if (!getCurScope()->decl_empty())
370 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
Mike Stump01e07652008-06-19 19:28:49 +0000371
Douglas Gregor0be31a22010-07-02 17:43:08 +0000372 Scope *OldScope = getCurScope();
373 Actions.CurScope = OldScope->getParent();
Mike Stump01e07652008-06-19 19:28:49 +0000374
Chris Lattner03928c72007-07-15 00:04:39 +0000375 if (NumCachedScopes == ScopeCacheSize)
376 delete OldScope;
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000377 else
Chris Lattner03928c72007-07-15 00:04:39 +0000378 ScopeCache[NumCachedScopes++] = OldScope;
Chris Lattnere4e38592006-08-14 00:15:05 +0000379}
380
Richard Smith938f40b2011-06-11 17:19:42 +0000381/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
382/// this object does nothing.
383Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
384 bool ManageFlags)
385 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
386 if (CurScope) {
387 OldFlags = CurScope->getFlags();
388 CurScope->setFlags(ScopeFlags);
389 }
390}
Chris Lattnere4e38592006-08-14 00:15:05 +0000391
Richard Smith938f40b2011-06-11 17:19:42 +0000392/// Restore the flags for the current scope to what they were before this
393/// object overrode them.
394Parser::ParseScopeFlags::~ParseScopeFlags() {
395 if (CurScope)
396 CurScope->setFlags(OldFlags);
397}
Chris Lattnere4e38592006-08-14 00:15:05 +0000398
399
400//===----------------------------------------------------------------------===//
Chris Lattner70f32b72006-07-31 05:09:04 +0000401// C99 6.9: External Definitions.
402//===----------------------------------------------------------------------===//
Chris Lattner0bb5f832006-07-31 01:59:18 +0000403
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000404Parser::~Parser() {
405 // If we still have scopes active, delete the scope tree.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000406 delete getCurScope();
407 Actions.CurScope = 0;
408
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000409 // Free the scope cache.
Chris Lattner03928c72007-07-15 00:04:39 +0000410 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
411 delete ScopeCache[i];
Daniel Dunbar921b9682008-10-04 19:21:03 +0000412
Francois Pichet1c229c02011-04-22 22:18:13 +0000413 // Free LateParsedTemplatedFunction nodes.
414 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
415 it != LateParsedTemplateMap.end(); ++it)
416 delete it->second;
417
Daniel Dunbar921b9682008-10-04 19:21:03 +0000418 // Remove the pragma handlers we installed.
Daniel Dunbarcb82acb2010-07-31 19:17:07 +0000419 PP.RemovePragmaHandler(AlignHandler.get());
420 AlignHandler.reset();
Eli Friedman570024a2010-08-05 06:57:20 +0000421 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
422 GCCVisibilityHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000423 PP.RemovePragmaHandler(OptionsHandler.get());
Daniel Dunbar75c9be72010-05-26 23:29:06 +0000424 OptionsHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000425 PP.RemovePragmaHandler(PackHandler.get());
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000426 PackHandler.reset();
Fariborz Jahanian743dda42011-04-25 18:49:15 +0000427 PP.RemovePragmaHandler(MSStructHandler.get());
428 MSStructHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000429 PP.RemovePragmaHandler(UnusedHandler.get());
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000430 UnusedHandler.reset();
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000431 PP.RemovePragmaHandler(WeakHandler.get());
Eli Friedmanf5867dd2009-06-05 00:49:58 +0000432 WeakHandler.reset();
David Chisnall0867d9c2012-02-18 16:12:34 +0000433 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
434 RedefineExtnameHandler.reset();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000435
David Blaikiebbafb8a2012-03-11 07:00:24 +0000436 if (getLangOpts().OpenCL) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000437 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
438 OpenCLExtensionHandler.reset();
439 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
440 }
441
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000442 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
443 FPContractHandler.reset();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000444
Dmitri Gribenko17e147f2012-06-20 01:06:08 +0000445 PP.removeCommentHandler(CommentSemaHandler.get());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000446
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000447 PP.clearCodeCompletionHandler();
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000448
449 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
Chris Lattnerb6a0e172006-11-06 00:22:42 +0000450}
451
Chris Lattner38ba3362006-08-17 07:04:37 +0000452/// Initialize - Warm up the parser.
453///
454void Parser::Initialize() {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000455 // Create the translation unit scope. Install it as the current scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000456 assert(getCurScope() == 0 && "A scope is already active?");
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000457 EnterScope(Scope::DeclScope);
Douglas Gregorf11096c2010-08-25 18:07:12 +0000458 Actions.ActOnTranslationUnitScope(getCurScope());
459
460 // Prime the lexer look-ahead.
461 ConsumeToken();
Mike Stump01e07652008-06-19 19:28:49 +0000462
Chris Lattner66782842007-08-29 22:54:08 +0000463 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000464 // Referenced in Parser::ParseObjCTypeQualifierList.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000465 if (getLangOpts().ObjC1) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000466 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
467 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
468 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
469 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
470 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
471 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner66782842007-08-29 22:54:08 +0000472 }
Daniel Dunbar12c9ddc2008-08-14 22:04:54 +0000473
Douglas Gregorbab8a962011-09-08 01:46:34 +0000474 Ident_instancetype = 0;
Anders Carlsson428803b2011-01-20 03:47:08 +0000475 Ident_final = 0;
476 Ident_override = 0;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +0000477
Daniel Dunbar12c9ddc2008-08-14 22:04:54 +0000478 Ident_super = &PP.getIdentifierTable().get("super");
John Thompson22334602010-02-05 00:12:22 +0000479
David Blaikiebbafb8a2012-03-11 07:00:24 +0000480 if (getLangOpts().AltiVec) {
John Thompson22334602010-02-05 00:12:22 +0000481 Ident_vector = &PP.getIdentifierTable().get("vector");
482 Ident_pixel = &PP.getIdentifierTable().get("pixel");
483 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000484
485 Ident_introduced = 0;
486 Ident_deprecated = 0;
487 Ident_obsoleted = 0;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000488 Ident_unavailable = 0;
John Wiegley1c0675e2011-04-28 01:08:34 +0000489
Douglas Gregor60060d62011-10-21 03:57:52 +0000490 Ident__except = 0;
491
John Wiegley1c0675e2011-04-28 01:08:34 +0000492 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
493 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
494 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
495
David Blaikiebbafb8a2012-03-11 07:00:24 +0000496 if(getLangOpts().Borland) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000497 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
498 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
499 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
500 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
501 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
502 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
503 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
504 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
505 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
506
507 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
508 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
509 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
510 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
511 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
512 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
513 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
514 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
515 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
516 }
Chris Lattner38ba3362006-08-17 07:04:37 +0000517}
518
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000519namespace {
520 /// \brief RAIIObject to destroy the contents of a SmallVector of
521 /// TemplateIdAnnotation pointers and clear the vector.
522 class DestroyTemplateIdAnnotationsRAIIObj {
523 SmallVectorImpl<TemplateIdAnnotation *> &Container;
524 public:
525 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
526 &Container)
527 : Container(Container) {}
528
529 ~DestroyTemplateIdAnnotationsRAIIObj() {
530 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
531 Container.begin(), E = Container.end();
532 I != E; ++I)
533 (*I)->Destroy();
534 Container.clear();
535 }
536 };
537}
538
Chris Lattner38ba3362006-08-17 07:04:37 +0000539/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
540/// action tells us to. This returns true if the EOF was encountered.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000541bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000542 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000543
Axel Naumann2eb1d902012-03-16 10:40:17 +0000544 // Skip over the EOF token, flagging end of previous input for incremental
545 // processing
546 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
547 ConsumeToken();
548
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000549 while (Tok.is(tok::annot_pragma_unused))
550 HandlePragmaUnused();
551
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000552 Result = DeclGroupPtrTy();
Chris Lattnerf4404402008-08-23 03:19:52 +0000553 if (Tok.is(tok::eof)) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000554 // Late template parsing can begin.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000555 if (getLangOpts().DelayedTemplateParsing)
Francois Pichet1c229c02011-04-22 22:18:13 +0000556 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
Axel Naumann2eb1d902012-03-16 10:40:17 +0000557 if (!PP.isIncrementalProcessingEnabled())
558 Actions.ActOnEndOfTranslationUnit();
559 //else don't tell Sema that we ended parsing: more input might come.
Francois Pichet1c229c02011-04-22 22:18:13 +0000560
Chris Lattnerf4404402008-08-23 03:19:52 +0000561 return true;
562 }
Mike Stump01e07652008-06-19 19:28:49 +0000563
John McCall084e83d2011-03-24 11:26:52 +0000564 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +0000565 MaybeParseCXX0XAttributes(attrs);
566 MaybeParseMicrosoftAttributes(attrs);
Axel Naumann2eb1d902012-03-16 10:40:17 +0000567
John McCall53fa7142010-12-24 02:08:15 +0000568 Result = ParseExternalDeclaration(attrs);
Chris Lattner38ba3362006-08-17 07:04:37 +0000569 return false;
570}
571
Chris Lattner38ba3362006-08-17 07:04:37 +0000572/// ParseTranslationUnit:
573/// translation-unit: [C99 6.9]
Mike Stump01e07652008-06-19 19:28:49 +0000574/// external-declaration
575/// translation-unit external-declaration
Chris Lattner38ba3362006-08-17 07:04:37 +0000576void Parser::ParseTranslationUnit() {
Douglas Gregor7307d6c2008-12-10 06:34:36 +0000577 Initialize();
Mike Stump01e07652008-06-19 19:28:49 +0000578
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000579 DeclGroupPtrTy Res;
Steve Naroff205ec3d2007-11-29 23:05:20 +0000580 while (!ParseTopLevelDecl(Res))
Chris Lattner38ba3362006-08-17 07:04:37 +0000581 /*parse them all*/;
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattner2cc35ae2008-08-23 02:00:52 +0000583 ExitScope();
Douglas Gregor0be31a22010-07-02 17:43:08 +0000584 assert(getCurScope() == 0 && "Scope imbalance!");
Chris Lattner38ba3362006-08-17 07:04:37 +0000585}
586
Chris Lattner0bb5f832006-07-31 01:59:18 +0000587/// ParseExternalDeclaration:
Chris Lattner46415262008-12-08 21:59:01 +0000588///
Douglas Gregor15799fd2008-11-21 16:10:08 +0000589/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattnercccc3112007-08-10 20:57:02 +0000590/// function-definition
591/// declaration
Douglas Gregor8b9575f2009-08-24 12:17:54 +0000592/// [C++0x] empty-declaration
Chris Lattner6d7e6342006-08-15 03:41:14 +0000593/// [GNU] asm-definition
Chris Lattnercccc3112007-08-10 20:57:02 +0000594/// [GNU] __extension__ external-declaration
Chris Lattner40f16b52006-11-05 02:05:37 +0000595/// [OBJC] objc-class-definition
596/// [OBJC] objc-class-declaration
597/// [OBJC] objc-alias-declaration
598/// [OBJC] objc-protocol-definition
599/// [OBJC] objc-method-definition
600/// [OBJC] @end
Douglas Gregor15799fd2008-11-21 16:10:08 +0000601/// [C++] linkage-specification
Chris Lattner6d7e6342006-08-15 03:41:14 +0000602/// [GNU] asm-definition:
603/// simple-asm-expr ';'
604///
Douglas Gregor8b9575f2009-08-24 12:17:54 +0000605/// [C++0x] empty-declaration:
606/// ';'
607///
Douglas Gregor43e75172009-09-04 06:33:52 +0000608/// [C++0x/GNU] 'extern' 'template' declaration
John McCall53fa7142010-12-24 02:08:15 +0000609Parser::DeclGroupPtrTy
610Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
611 ParsingDeclSpec *DS) {
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000612 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000613 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000614
615 if (PP.isCodeCompletionReached()) {
616 cutOffParsing();
617 return DeclGroupPtrTy();
618 }
619
John McCall48871652010-08-21 09:40:31 +0000620 Decl *SingleDecl = 0;
Chris Lattner0bb5f832006-07-31 01:59:18 +0000621 switch (Tok.getKind()) {
Rafael Espindola273fd772012-01-26 02:02:57 +0000622 case tok::annot_pragma_vis:
623 HandlePragmaVisibility();
624 return DeclGroupPtrTy();
Eli Friedmanec52f922012-02-23 23:47:16 +0000625 case tok::annot_pragma_pack:
626 HandlePragmaPack();
627 return DeclGroupPtrTy();
Chris Lattner0bb5f832006-07-31 01:59:18 +0000628 case tok::semi:
Richard Trieu2f7dc462012-05-16 19:04:59 +0000629 ConsumeExtraSemi(OutsideFunction);
Chris Lattner2dacc3f2006-10-16 00:33:54 +0000630 // TODO: Invoke action for top-level semicolon.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000631 return DeclGroupPtrTy();
Chris Lattner46415262008-12-08 21:59:01 +0000632 case tok::r_brace:
Nico Webere1df10a2012-01-17 01:04:27 +0000633 Diag(Tok, diag::err_extraneous_closing_brace);
Chris Lattner46415262008-12-08 21:59:01 +0000634 ConsumeBrace();
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000635 return DeclGroupPtrTy();
Chris Lattner46415262008-12-08 21:59:01 +0000636 case tok::eof:
637 Diag(Tok, diag::err_expected_external_declaration);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000638 return DeclGroupPtrTy();
Chris Lattnercccc3112007-08-10 20:57:02 +0000639 case tok::kw___extension__: {
Chris Lattnerf02ef3e2008-10-20 06:45:43 +0000640 // __extension__ silences extension warnings in the subexpression.
641 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner1ff6e732008-10-20 06:51:33 +0000642 ConsumeToken();
John McCall53fa7142010-12-24 02:08:15 +0000643 return ParseExternalDeclaration(attrs);
Chris Lattnercccc3112007-08-10 20:57:02 +0000644 }
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000645 case tok::kw_asm: {
John McCall53fa7142010-12-24 02:08:15 +0000646 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000647
Abramo Bagnara348823a2011-03-03 14:20:18 +0000648 SourceLocation StartLoc = Tok.getLocation();
649 SourceLocation EndLoc;
650 ExprResult Result(ParseSimpleAsm(&EndLoc));
Mike Stump01e07652008-06-19 19:28:49 +0000651
Anders Carlsson0fae4f52008-02-08 00:23:11 +0000652 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
653 "top-level asm block");
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000654
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000655 if (Result.isInvalid())
656 return DeclGroupPtrTy();
Abramo Bagnara348823a2011-03-03 14:20:18 +0000657 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000658 break;
Anders Carlsson5c6c0592008-02-08 00:33:21 +0000659 }
Steve Naroffb419d3a2006-10-27 23:18:49 +0000660 case tok::at:
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000661 return ParseObjCAtDirectives();
Steve Naroffb419d3a2006-10-27 23:18:49 +0000662 case tok::minus:
Steve Naroffb419d3a2006-10-27 23:18:49 +0000663 case tok::plus:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000664 if (!getLangOpts().ObjC1) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000665 Diag(Tok, diag::err_expected_external_declaration);
666 ConsumeToken();
667 return DeclGroupPtrTy();
668 }
669 SingleDecl = ParseObjCMethodDefinition();
670 break;
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000671 case tok::code_completion:
Douglas Gregor0be31a22010-07-02 17:43:08 +0000672 Actions.CodeCompleteOrdinaryName(getCurScope(),
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +0000673 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
John McCallfaf5fb42010-08-26 23:41:50 +0000674 : Sema::PCC_Namespace);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000675 cutOffParsing();
676 return DeclGroupPtrTy();
Douglas Gregord7c4d982008-12-30 03:27:21 +0000677 case tok::kw_using:
Chris Lattnera5235172007-08-25 06:57:03 +0000678 case tok::kw_namespace:
Chris Lattner302b4be2006-11-19 02:31:38 +0000679 case tok::kw_typedef:
Douglas Gregoreb31f392008-12-01 23:54:00 +0000680 case tok::kw_template:
681 case tok::kw_export: // As in 'export template'
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000682 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000683 case tok::kw__Static_assert:
Chad Rosiere38c0062012-04-25 22:51:41 +0000684 // A function definition cannot start with any of these keywords.
Chris Lattner49836b42009-04-02 04:16:50 +0000685 {
686 SourceLocation DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000687 StmtVector Stmts(Actions);
John McCall53fa7142010-12-24 02:08:15 +0000688 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000689 }
Sebastian Redl67667942010-08-27 23:12:46 +0000690
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000691 case tok::kw_static:
692 // Parse (then ignore) 'static' prior to a template instantiation. This is
693 // a GCC extension that we intentionally do not support.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000694 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000695 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
696 << 0;
Sebastian Redl67667942010-08-27 23:12:46 +0000697 SourceLocation DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000698 StmtVector Stmts(Actions);
John McCall53fa7142010-12-24 02:08:15 +0000699 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000700 }
701 goto dont_know;
702
703 case tok::kw_inline:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000704 if (getLangOpts().CPlusPlus) {
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000705 tok::TokenKind NextKind = NextToken().getKind();
706
707 // Inline namespaces. Allowed as an extension even in C++03.
708 if (NextKind == tok::kw_namespace) {
709 SourceLocation DeclEnd;
710 StmtVector Stmts(Actions);
John McCall53fa7142010-12-24 02:08:15 +0000711 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000712 }
713
714 // Parse (then ignore) 'inline' prior to a template instantiation. This is
715 // a GCC extension that we intentionally do not support.
716 if (NextKind == tok::kw_template) {
717 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
718 << 1;
719 SourceLocation DeclEnd;
720 StmtVector Stmts(Actions);
John McCall53fa7142010-12-24 02:08:15 +0000721 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
Douglas Gregoraa49ecc2010-12-01 20:32:20 +0000722 }
Sebastian Redl67667942010-08-27 23:12:46 +0000723 }
724 goto dont_know;
725
Douglas Gregor43e75172009-09-04 06:33:52 +0000726 case tok::kw_extern:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000727 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
Douglas Gregor43e75172009-09-04 06:33:52 +0000728 // Extern templates
729 SourceLocation ExternLoc = ConsumeToken();
730 SourceLocation TemplateLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
Richard Smithf4111962011-10-20 18:35:58 +0000732 diag::warn_cxx98_compat_extern_template :
733 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
Douglas Gregor43e75172009-09-04 06:33:52 +0000734 SourceLocation DeclEnd;
735 return Actions.ConvertDeclToDeclGroup(
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +0000736 ParseExplicitInstantiation(Declarator::FileContext,
737 ExternLoc, TemplateLoc, DeclEnd));
Douglas Gregor43e75172009-09-04 06:33:52 +0000738 }
Douglas Gregor43e75172009-09-04 06:33:52 +0000739 // FIXME: Detect C++ linkage specifications here?
Sebastian Redl67667942010-08-27 23:12:46 +0000740 goto dont_know;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Francois Picheta5b3fcb2011-05-07 17:30:27 +0000742 case tok::kw___if_exists:
743 case tok::kw___if_not_exists:
Francois Pichet8f981d52011-05-25 10:19:49 +0000744 ParseMicrosoftIfExistsExternalDeclaration();
Francois Picheta5b3fcb2011-05-07 17:30:27 +0000745 return DeclGroupPtrTy();
Douglas Gregor08142532011-08-26 23:56:07 +0000746
Chris Lattner0bb5f832006-07-31 01:59:18 +0000747 default:
Sebastian Redl67667942010-08-27 23:12:46 +0000748 dont_know:
Chris Lattner0bb5f832006-07-31 01:59:18 +0000749 // We can't tell whether this is a function-definition or declaration yet.
John McCall53fa7142010-12-24 02:08:15 +0000750 if (DS) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000751 return ParseDeclarationOrFunctionDefinition(attrs, DS);
John McCall53fa7142010-12-24 02:08:15 +0000752 } else {
753 return ParseDeclarationOrFunctionDefinition(attrs);
754 }
Chris Lattner0bb5f832006-07-31 01:59:18 +0000755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000757 // This routine returns a DeclGroup, if the thing we parsed only contains a
758 // single decl, convert it now.
759 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattner0bb5f832006-07-31 01:59:18 +0000760}
761
Douglas Gregor23996282009-05-12 21:31:51 +0000762/// \brief Determine whether the current token, if it occurs after a
763/// declarator, continues a declaration or declaration list.
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000764bool Parser::isDeclarationAfterDeclarator() {
765 // Check for '= delete' or '= default'
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000767 const Token &KW = NextToken();
768 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
769 return false;
770 }
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000771
Douglas Gregor23996282009-05-12 21:31:51 +0000772 return Tok.is(tok::equal) || // int X()= -> not a function def
773 Tok.is(tok::comma) || // int X(), -> not a function def
774 Tok.is(tok::semi) || // int X(); -> not a function def
775 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
776 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
David Blaikiebbafb8a2012-03-11 07:00:24 +0000777 (getLangOpts().CPlusPlus &&
Fariborz Jahanian8de79552012-07-05 19:34:20 +0000778 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
Douglas Gregor23996282009-05-12 21:31:51 +0000779}
780
781/// \brief Determine whether the current token, if it occurs after a
782/// declarator, indicates the start of a function definition.
Chris Lattner13901342010-07-11 22:42:07 +0000783bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000784 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
Chris Lattner8c56c492009-12-06 18:34:27 +0000785 if (Tok.is(tok::l_brace)) // int X() {}
786 return true;
787
Chris Lattner13901342010-07-11 22:42:07 +0000788 // Handle K&R C argument lists: int X(f) int f; {}
David Blaikiebbafb8a2012-03-11 07:00:24 +0000789 if (!getLangOpts().CPlusPlus &&
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000790 Declarator.getFunctionTypeInfo().isKNRPrototype())
Chris Lattner13901342010-07-11 22:42:07 +0000791 return isDeclarationSpecifier();
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000792
David Blaikiebbafb8a2012-03-11 07:00:24 +0000793 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000794 const Token &KW = NextToken();
795 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
796 }
Chris Lattner13901342010-07-11 22:42:07 +0000797
Chris Lattner8c56c492009-12-06 18:34:27 +0000798 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
799 Tok.is(tok::kw_try); // X() try { ... }
Douglas Gregor23996282009-05-12 21:31:51 +0000800}
801
Fariborz Jahanian97920392012-07-06 00:42:20 +0000802/// \brief Determine whether the current token, if it occurs after a
803/// a function declarator, indicates the start of a function definition
804/// inside an objective-C class implementation and thus can be delay parsed.
805bool Parser::isStartOfDelayParsedFunctionDefinition(
806 const ParsingDeclarator &Declarator) {
807 if (!CurParsedObjCImpl ||
808 !Declarator.isFunctionDeclarator())
809 return false;
810 if (Tok.is(tok::l_brace)) // int X() {}
811 return true;
812
813 // Handle K&R C argument lists: int X(f) int f; {}
814 if (!getLangOpts().CPlusPlus &&
815 Declarator.getFunctionTypeInfo().isKNRPrototype())
816 return isDeclarationSpecifier();
817
818 return getLangOpts().CPlusPlus &&
819 (Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
820 Tok.is(tok::kw_try)); // X() try { ... }
821}
822
Chris Lattner0bb5f832006-07-31 01:59:18 +0000823/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
Chris Lattner70f32b72006-07-31 05:09:04 +0000824/// a declaration. We can't tell which we have until we read up to the
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000825/// compound-statement in function-definition. TemplateParams, if
826/// non-NULL, provides the template parameters when we're parsing a
Mike Stump11289f42009-09-09 15:08:12 +0000827/// C++ template-declaration.
Chris Lattner0bb5f832006-07-31 01:59:18 +0000828///
Chris Lattner70f32b72006-07-31 05:09:04 +0000829/// function-definition: [C99 6.9.1]
Chris Lattner94fc8062008-04-05 05:52:15 +0000830/// decl-specs declarator declaration-list[opt] compound-statement
831/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stump01e07652008-06-19 19:28:49 +0000832/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattner94fc8062008-04-05 05:52:15 +0000833///
Chris Lattner70f32b72006-07-31 05:09:04 +0000834/// declaration: [C99 6.7]
Chris Lattnerf2659392007-08-22 06:06:56 +0000835/// declaration-specifiers init-declarator-list[opt] ';'
836/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Chris Lattner70f32b72006-07-31 05:09:04 +0000837/// [OMP] threadprivate-directive [TODO]
838///
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000839Parser::DeclGroupPtrTy
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000840Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
841 ParsingDeclSpec &DS,
842 AccessSpecifier AS) {
Chris Lattner70f32b72006-07-31 05:09:04 +0000843 // Parse the common declaration-specifiers piece.
Douglas Gregor9de54ea2010-01-13 17:31:36 +0000844 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
Mike Stump01e07652008-06-19 19:28:49 +0000845
Chris Lattnerd2864882006-08-05 08:09:44 +0000846 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
Chris Lattner53361ac2006-08-10 05:19:57 +0000847 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner0ab032a2007-10-09 17:23:58 +0000848 if (Tok.is(tok::semi)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000849 ProhibitAttributes(attrs);
Chris Lattner0e894622006-08-13 19:58:17 +0000850 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000851 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall28a6aea2009-11-04 02:18:39 +0000852 DS.complete(TheDecl);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000853 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +0000854 }
Mike Stump01e07652008-06-19 19:28:49 +0000855
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000856 DS.takeAttributesFrom(attrs);
857
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000858 // ObjC2 allows prefix attributes on class interfaces and protocols.
859 // FIXME: This still needs better diagnostics. We should only accept
860 // attributes here, no types, etc.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
Steve Naroff1eb1ad62007-08-20 21:31:48 +0000862 SourceLocation AtLoc = ConsumeToken(); // the "@"
Mike Stump11289f42009-09-09 15:08:12 +0000863 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000864 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
865 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattner5e530bc2007-12-27 19:57:00 +0000866 SkipUntil(tok::semi); // FIXME: better skip?
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000867 return DeclGroupPtrTy();
Chris Lattner5e530bc2007-12-27 19:57:00 +0000868 }
John McCalld5a36322009-11-03 19:26:08 +0000869
John McCall28a6aea2009-11-04 02:18:39 +0000870 DS.abort();
871
Fariborz Jahanian056e3a42008-01-02 19:17:38 +0000872 const char *PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +0000873 unsigned DiagID;
874 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
875 Diag(AtLoc, DiagID) << PrevSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000876
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000877 if (Tok.isObjCAtKeyword(tok::objc_protocol))
Douglas Gregorf6102672012-01-01 21:23:57 +0000878 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
879
880 return Actions.ConvertDeclToDeclGroup(
881 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
Steve Naroff1eb1ad62007-08-20 21:31:48 +0000882 }
Mike Stump01e07652008-06-19 19:28:49 +0000883
Chris Lattner38376f12008-01-12 07:05:38 +0000884 // If the declspec consisted only of 'extern' and we have a string
885 // literal following it, this must be a C++ linkage specifier like
886 // 'extern "C"'.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000887 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
Chris Lattner38376f12008-01-12 07:05:38 +0000888 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000889 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
John McCall48871652010-08-21 09:40:31 +0000890 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000891 return Actions.ConvertDeclToDeclGroup(TheDecl);
892 }
Chris Lattner38376f12008-01-12 07:05:38 +0000893
John McCalld5a36322009-11-03 19:26:08 +0000894 return ParseDeclGroup(DS, Declarator::FileContext, true);
Chris Lattner70f32b72006-07-31 05:09:04 +0000895}
896
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000897Parser::DeclGroupPtrTy
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000898Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
899 ParsingDeclSpec *DS,
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000900 AccessSpecifier AS) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000901 if (DS) {
902 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
903 } else {
904 ParsingDeclSpec PDS(*this);
905 // Must temporarily exit the objective-c container scope for
906 // parsing c constructs and re-enter objc container scope
907 // afterwards.
908 ObjCDeclContextSwitch ObjCDC(*this);
909
910 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
911 }
Fariborz Jahanian26de2e52009-12-09 21:39:38 +0000912}
913
Chris Lattnerfff824f2006-08-07 06:31:38 +0000914/// ParseFunctionDefinition - We parsed and verified that the specified
915/// Declarator is well formed. If this is a K&R-style function, read the
916/// parameters declaration-list, then start the compound-statement.
917///
Chris Lattner94fc8062008-04-05 05:52:15 +0000918/// function-definition: [C99 6.9.1]
919/// decl-specs declarator declaration-list[opt] compound-statement
920/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stump01e07652008-06-19 19:28:49 +0000921/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregore8381c02008-11-05 04:29:56 +0000922/// [C++] function-definition: [C++ 8.4]
Chris Lattnerefb0f112009-03-29 17:18:04 +0000923/// decl-specifier-seq[opt] declarator ctor-initializer[opt]
924/// function-body
Douglas Gregore8381c02008-11-05 04:29:56 +0000925/// [C++] function-definition: [C++ 8.4]
Sebastian Redla7b98a72009-04-26 20:35:05 +0000926/// decl-specifier-seq[opt] declarator function-try-block
Chris Lattnerfff824f2006-08-07 06:31:38 +0000927///
John McCall48871652010-08-21 09:40:31 +0000928Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000929 const ParsedTemplateInfo &TemplateInfo,
930 LateParsedAttrList *LateParsedAttrs) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000931 // Poison the SEH identifiers so they are flagged as illegal in function bodies
932 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000933 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump01e07652008-06-19 19:28:49 +0000934
Chris Lattner94fc8062008-04-05 05:52:15 +0000935 // If this is C90 and the declspecs were completely missing, fudge in an
936 // implicit int. We do this here because this is the only place where
937 // declaration-specifiers are completely optional in the grammar.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000938 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
Chris Lattner94fc8062008-04-05 05:52:15 +0000939 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +0000940 unsigned DiagID;
Chris Lattnerfcc390a2008-10-20 02:01:34 +0000941 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
942 D.getIdentifierLoc(),
John McCall49bfce42009-08-03 20:12:06 +0000943 PrevSpec, DiagID);
Sebastian Redlf6591ca2009-02-09 18:23:29 +0000944 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattner94fc8062008-04-05 05:52:15 +0000945 }
Mike Stump01e07652008-06-19 19:28:49 +0000946
Chris Lattnerfff824f2006-08-07 06:31:38 +0000947 // If this declaration was formed with a K&R-style identifier list for the
948 // arguments, parse declarations for all of the args next.
949 // int foo(a,b) int a; float b; {}
Chris Lattner13901342010-07-11 22:42:07 +0000950 if (FTI.isKNRPrototype())
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000951 ParseKNRParamDeclarations(D);
Chris Lattnerfff824f2006-08-07 06:31:38 +0000952
Douglas Gregore8381c02008-11-05 04:29:56 +0000953 // We should have either an opening brace or, in a C++ constructor,
954 // we may have a colon.
Douglas Gregor0fcaac92011-02-04 11:57:16 +0000955 if (Tok.isNot(tok::l_brace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000956 (!getLangOpts().CPlusPlus ||
Alexis Hunt61ae8d32011-05-23 23:14:04 +0000957 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
958 Tok.isNot(tok::equal)))) {
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000959 Diag(Tok, diag::err_expected_fn_body);
960
961 // Skip over garbage, until we get to '{'. Don't eat the '{'.
962 SkipUntil(tok::l_brace, true, true);
Mike Stump01e07652008-06-19 19:28:49 +0000963
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000964 // If we didn't find the '{', bail out.
Chris Lattner0ab032a2007-10-09 17:23:58 +0000965 if (Tok.isNot(tok::l_brace))
John McCall48871652010-08-21 09:40:31 +0000966 return 0;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000967 }
Mike Stump01e07652008-06-19 19:28:49 +0000968
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000969 // Check to make sure that any normal attributes are allowed to be on
970 // a definition. Late parsed attributes are checked at the end.
971 if (Tok.isNot(tok::equal)) {
972 AttributeList *DtorAttrs = D.getAttributes();
973 while (DtorAttrs) {
974 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
975 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
976 << DtorAttrs->getName()->getName();
977 }
978 DtorAttrs = DtorAttrs->getNext();
979 }
980 }
981
Francois Pichet1c229c02011-04-22 22:18:13 +0000982 // In delayed template parsing mode, for function template we consume the
983 // tokens and store them for late parsing at the end of the translation unit.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000984 if (getLangOpts().DelayedTemplateParsing &&
Douglas Gregor1edf5762012-06-28 21:43:01 +0000985 Tok.isNot(tok::equal) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000986 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
987 MultiTemplateParamsArg TemplateParameterLists(Actions,
988 TemplateInfo.TemplateParams->data(),
989 TemplateInfo.TemplateParams->size());
990
991 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
992 Scope *ParentScope = getCurScope()->getParent();
993
Douglas Gregor5d1b4e32011-11-07 20:56:01 +0000994 D.setFunctionDefinitionKind(FDK_Definition);
Francois Pichet1c229c02011-04-22 22:18:13 +0000995 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +0000996 move(TemplateParameterLists));
Francois Pichet1c229c02011-04-22 22:18:13 +0000997 D.complete(DP);
998 D.getMutableDeclSpec().abort();
999
1000 if (DP) {
Francois Pichet33786cb2011-12-08 09:11:52 +00001001 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
Francois Pichet1c229c02011-04-22 22:18:13 +00001002
1003 FunctionDecl *FnD = 0;
1004 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1005 FnD = FunTmpl->getTemplatedDecl();
1006 else
1007 FnD = cast<FunctionDecl>(DP);
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00001008 Actions.CheckForFunctionRedefinition(FnD);
Francois Pichet1c229c02011-04-22 22:18:13 +00001009
1010 LateParsedTemplateMap[FnD] = LPT;
1011 Actions.MarkAsLateParsedTemplate(FnD);
1012 LexTemplateFunctionForLateParsing(LPT->Toks);
1013 } else {
1014 CachedTokens Toks;
1015 LexTemplateFunctionForLateParsing(Toks);
1016 }
1017 return DP;
1018 }
1019
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001020 // Enter a scope for the function body.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001021 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stump01e07652008-06-19 19:28:49 +00001022
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001023 // Tell the actions module that we have entered a function definition with the
1024 // specified Declarator for the function.
John McCall48871652010-08-21 09:40:31 +00001025 Decl *Res = TemplateInfo.TemplateParams?
Douglas Gregor0be31a22010-07-02 17:43:08 +00001026 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001027 MultiTemplateParamsArg(Actions,
Douglas Gregor17a7c122009-06-24 00:54:41 +00001028 TemplateInfo.TemplateParams->data(),
1029 TemplateInfo.TemplateParams->size()),
1030 D)
Douglas Gregor0be31a22010-07-02 17:43:08 +00001031 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
Mike Stump01e07652008-06-19 19:28:49 +00001032
John McCall28a6aea2009-11-04 02:18:39 +00001033 // Break out of the ParsingDeclarator context before we parse the body.
1034 D.complete(Res);
1035
1036 // Break out of the ParsingDeclSpec context, too. This const_cast is
1037 // safe because we're always the sole owner.
1038 D.getMutableDeclSpec().abort();
1039
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001040 if (Tok.is(tok::equal)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001041 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001042 ConsumeToken();
1043
1044 Actions.ActOnFinishFunctionBody(Res, 0, false);
1045
1046 bool Delete = false;
1047 SourceLocation KWLoc;
1048 if (Tok.is(tok::kw_delete)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001049 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001050 diag::warn_cxx98_compat_deleted_function :
Richard Smithe4345902011-12-29 21:57:33 +00001051 diag::ext_deleted_function);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001052
1053 KWLoc = ConsumeToken();
1054 Actions.SetDeclDeleted(Res, KWLoc);
1055 Delete = true;
1056 } else if (Tok.is(tok::kw_default)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001057 Diag(Tok, getLangOpts().CPlusPlus0x ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001058 diag::warn_cxx98_compat_defaulted_function :
Richard Smithe4345902011-12-29 21:57:33 +00001059 diag::ext_defaulted_function);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001060
1061 KWLoc = ConsumeToken();
1062 Actions.SetDeclDefaulted(Res, KWLoc);
1063 } else {
1064 llvm_unreachable("function definition after = not 'delete' or 'default'");
1065 }
1066
1067 if (Tok.is(tok::comma)) {
1068 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1069 << Delete;
1070 SkipUntil(tok::semi);
1071 } else {
1072 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1073 Delete ? "delete" : "default", tok::semi);
1074 }
1075
1076 return Res;
1077 }
1078
Sebastian Redla7b98a72009-04-26 20:35:05 +00001079 if (Tok.is(tok::kw_try))
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001080 return ParseFunctionTryBlock(Res, BodyScope);
Sebastian Redla7b98a72009-04-26 20:35:05 +00001081
Douglas Gregore8381c02008-11-05 04:29:56 +00001082 // If we have a colon, then we're probably parsing a C++
1083 // ctor-initializer.
John McCallbb7b6582010-04-10 07:37:23 +00001084 if (Tok.is(tok::colon)) {
Douglas Gregore8381c02008-11-05 04:29:56 +00001085 ParseConstructorInitializer(Res);
John McCallbb7b6582010-04-10 07:37:23 +00001086
1087 // Recover from error.
1088 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001089 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00001090 Actions.ActOnFinishFunctionBody(Res, 0);
John McCallbb7b6582010-04-10 07:37:23 +00001091 return Res;
1092 }
1093 } else
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001094 Actions.ActOnDefaultCtorInitializers(Res);
Douglas Gregore8381c02008-11-05 04:29:56 +00001095
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001096 // Late attributes are parsed in the same scope as the function body.
1097 if (LateParsedAttrs)
1098 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1099
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001100 return ParseFunctionStatementBody(Res, BodyScope);
Chris Lattnerfff824f2006-08-07 06:31:38 +00001101}
1102
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001103/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1104/// types for a function with a K&R-style identifier list for arguments.
1105void Parser::ParseKNRParamDeclarations(Declarator &D) {
1106 // We know that the top-level of this declarator is a function.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001107 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001108
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001109 // Enter function-declaration scope, limiting any declarators to the
1110 // function prototype scope, including parameter declarators.
Douglas Gregor658b9552009-01-09 22:42:13 +00001111 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001112
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001113 // Read all the argument declarations.
1114 while (isDeclarationSpecifier()) {
1115 SourceLocation DSStart = Tok.getLocation();
Mike Stump01e07652008-06-19 19:28:49 +00001116
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001117 // Parse the common declaration-specifiers piece.
John McCall084e83d2011-03-24 11:26:52 +00001118 DeclSpec DS(AttrFactory);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001119 ParseDeclarationSpecifiers(DS);
Mike Stump01e07652008-06-19 19:28:49 +00001120
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001121 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1122 // least one declarator'.
1123 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1124 // the declarations though. It's trivial to ignore them, really hard to do
1125 // anything else with them.
Chris Lattner0ab032a2007-10-09 17:23:58 +00001126 if (Tok.is(tok::semi)) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001127 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1128 ConsumeToken();
1129 continue;
1130 }
Mike Stump01e07652008-06-19 19:28:49 +00001131
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001132 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1133 // than register.
1134 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1135 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1136 Diag(DS.getStorageClassSpecLoc(),
1137 diag::err_invalid_storage_class_in_func_decl);
1138 DS.ClearStorageClassSpecs();
1139 }
1140 if (DS.isThreadSpecified()) {
1141 Diag(DS.getThreadSpecLoc(),
1142 diag::err_invalid_storage_class_in_func_decl);
1143 DS.ClearStorageClassSpecs();
1144 }
Mike Stump01e07652008-06-19 19:28:49 +00001145
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001146 // Parse the first declarator attached to this declspec.
1147 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1148 ParseDeclarator(ParmDeclarator);
1149
1150 // Handle the full declarator list.
1151 while (1) {
1152 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001153 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump01e07652008-06-19 19:28:49 +00001154
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001155 // Ask the actions module to compute the type for this declarator.
John McCall48871652010-08-21 09:40:31 +00001156 Decl *Param =
Douglas Gregor0be31a22010-07-02 17:43:08 +00001157 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Steve Naroffacb1e742007-09-10 20:51:04 +00001158
Mike Stump01e07652008-06-19 19:28:49 +00001159 if (Param &&
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001160 // A missing identifier has already been diagnosed.
1161 ParmDeclarator.getIdentifier()) {
1162
1163 // Scan the argument list looking for the correct param to apply this
1164 // type.
1165 for (unsigned i = 0; ; ++i) {
1166 // C99 6.9.1p6: those declarators shall declare only identifiers from
1167 // the identifier list.
1168 if (i == FTI.NumArgs) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001169 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattner760d19ad2008-11-19 07:51:13 +00001170 << ParmDeclarator.getIdentifier();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001171 break;
1172 }
Mike Stump01e07652008-06-19 19:28:49 +00001173
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001174 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1175 // Reject redefinitions of parameters.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001176 if (FTI.ArgInfo[i].Param) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001177 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00001178 diag::err_param_redefinition)
Chris Lattner760d19ad2008-11-19 07:51:13 +00001179 << ParmDeclarator.getIdentifier();
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001180 } else {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001181 FTI.ArgInfo[i].Param = Param;
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001182 }
1183 break;
1184 }
1185 }
1186 }
1187
1188 // If we don't have a comma, it is either the end of the list (a ';') or
1189 // an error, bail out.
Chris Lattner0ab032a2007-10-09 17:23:58 +00001190 if (Tok.isNot(tok::comma))
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001191 break;
Mike Stump01e07652008-06-19 19:28:49 +00001192
Richard Smith8d06f422012-01-12 23:53:29 +00001193 ParmDeclarator.clear();
1194
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001195 // Consume the comma.
Richard Smith8d06f422012-01-12 23:53:29 +00001196 ParmDeclarator.setCommaLoc(ConsumeToken());
Mike Stump01e07652008-06-19 19:28:49 +00001197
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001198 // Parse the next declarator.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001199 ParseDeclarator(ParmDeclarator);
1200 }
Mike Stump01e07652008-06-19 19:28:49 +00001201
Chris Lattner02f1b612012-04-28 16:12:17 +00001202 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001203 // Skip to end of block or statement
1204 SkipUntil(tok::semi, true);
Chris Lattner0ab032a2007-10-09 17:23:58 +00001205 if (Tok.is(tok::semi))
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001206 ConsumeToken();
1207 }
1208 }
Mike Stump01e07652008-06-19 19:28:49 +00001209
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001210 // The actions module must verify that all arguments were declared.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001211 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001212}
1213
1214
Chris Lattner0116c472006-08-15 06:03:28 +00001215/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1216/// allowed to be a wide string, and is not subject to character translation.
1217///
1218/// [GNU] asm-string-literal:
1219/// string-literal
1220///
John McCalldadc5752010-08-24 06:29:42 +00001221Parser::ExprResult Parser::ParseAsmStringLiteral() {
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001222 switch (Tok.getKind()) {
1223 case tok::string_literal:
1224 break;
Richard Smithd67aea22012-03-06 03:21:47 +00001225 case tok::utf8_string_literal:
1226 case tok::utf16_string_literal:
1227 case tok::utf32_string_literal:
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001228 case tok::wide_string_literal: {
1229 SourceLocation L = Tok.getLocation();
1230 Diag(Tok, diag::err_asm_operand_wide_string_literal)
Richard Smithd67aea22012-03-06 03:21:47 +00001231 << (Tok.getKind() == tok::wide_string_literal)
Ted Kremenek65cdbf52011-12-02 00:35:46 +00001232 << SourceRange(L, L);
1233 return ExprError();
1234 }
1235 default:
1236 Diag(Tok, diag::err_expected_string_literal);
1237 return ExprError();
Chris Lattner0116c472006-08-15 06:03:28 +00001238 }
Mike Stump01e07652008-06-19 19:28:49 +00001239
Richard Smithd67aea22012-03-06 03:21:47 +00001240 return ParseStringLiteralExpression();
Chris Lattner0116c472006-08-15 06:03:28 +00001241}
1242
Chris Lattner6d7e6342006-08-15 03:41:14 +00001243/// ParseSimpleAsm
1244///
1245/// [GNU] simple-asm-expr:
1246/// 'asm' '(' asm-string-literal ')'
Chris Lattner6d7e6342006-08-15 03:41:14 +00001247///
John McCalldadc5752010-08-24 06:29:42 +00001248Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner0ab032a2007-10-09 17:23:58 +00001249 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlsson5c6c0592008-02-08 00:33:21 +00001250 SourceLocation Loc = ConsumeToken();
Mike Stump01e07652008-06-19 19:28:49 +00001251
John McCall9dfb1622010-01-25 22:27:48 +00001252 if (Tok.is(tok::kw_volatile)) {
John McCall5cb52872010-01-25 23:12:50 +00001253 // Remove from the end of 'asm' to the end of 'volatile'.
1254 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1255 PP.getLocForEndOfToken(Tok.getLocation()));
1256
1257 Diag(Tok, diag::warn_file_asm_volatile)
Douglas Gregora771f462010-03-31 17:46:05 +00001258 << FixItHint::CreateRemoval(RemovalRange);
John McCall9dfb1622010-01-25 22:27:48 +00001259 ConsumeToken();
1260 }
1261
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001262 BalancedDelimiterTracker T(*this, tok::l_paren);
1263 if (T.consumeOpen()) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001264 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl042ad952008-12-11 19:30:53 +00001265 return ExprError();
Chris Lattner6d7e6342006-08-15 03:41:14 +00001266 }
Mike Stump01e07652008-06-19 19:28:49 +00001267
John McCalldadc5752010-08-24 06:29:42 +00001268 ExprResult Result(ParseAsmStringLiteral());
Mike Stump01e07652008-06-19 19:28:49 +00001269
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001270 if (Result.isInvalid()) {
1271 SkipUntil(tok::r_paren, true, true);
1272 if (EndLoc)
1273 *EndLoc = Tok.getLocation();
1274 ConsumeAnyToken();
1275 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001276 // Close the paren and get the location of the end bracket
1277 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001278 if (EndLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001279 *EndLoc = T.getCloseLocation();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001280 }
Mike Stump01e07652008-06-19 19:28:49 +00001281
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001282 return move(Result);
Chris Lattner6d7e6342006-08-15 03:41:14 +00001283}
Steve Naroffb419d3a2006-10-27 23:18:49 +00001284
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001285/// \brief Get the TemplateIdAnnotation from the token and put it in the
1286/// cleanup pool so that it gets destroyed when parsing the current top level
1287/// declaration is finished.
1288TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1289 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1290 TemplateIdAnnotation *
1291 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001292 return Id;
1293}
1294
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001295/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1296/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1297/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1298/// with a single annotation token representing the typename or C++ scope
1299/// respectively.
1300/// This simplifies handling of C++ scope specifiers and allows efficient
1301/// backtracking without the need to re-parse and resolve nested-names and
1302/// typenames.
Argyrios Kyrtzidis0c4162a2008-11-26 21:51:07 +00001303/// It will mainly be called when we expect to treat identifiers as typenames
1304/// (if they are typenames). For example, in C we do not expect identifiers
1305/// inside expressions to be treated as typenames so it will not be called
1306/// for expressions in C.
1307/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroff16c8e592009-01-28 19:39:02 +00001308/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argyrios Kyrtzidis0c4162a2008-11-26 21:51:07 +00001309/// will not be called twice, once to check whether we have a declaration
1310/// specifier, and another one to get the actual type inside
1311/// ParseDeclarationSpecifiers).
Chris Lattner9a8968b2009-01-04 23:23:14 +00001312///
John McCall1f476a12010-02-26 08:45:28 +00001313/// This returns true if an error occurred.
Mike Stump11289f42009-09-09 15:08:12 +00001314///
Chris Lattner45ddec32009-01-05 00:13:00 +00001315/// Note that this routine emits an error if you call it with ::new or ::delete
1316/// as the current tokens, so only call it in contexts where these are invalid.
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001317bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
Mike Stump11289f42009-09-09 15:08:12 +00001318 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
David Blaikie15a430a2011-12-04 05:04:18 +00001319 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
Richard Smithb71e7322012-05-14 22:43:34 +00001320 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1321 && "Cannot be a type or scope token!");
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregor333489b2009-03-27 23:10:48 +00001323 if (Tok.is(tok::kw_typename)) {
1324 // Parse a C++ typename-specifier, e.g., "typename T::type".
1325 //
1326 // typename-specifier:
1327 // 'typename' '::' [opt] nested-name-specifier identifier
Mike Stump11289f42009-09-09 15:08:12 +00001328 // 'typename' '::' [opt] nested-name-specifier template [opt]
Douglas Gregordce2b622009-04-01 00:28:59 +00001329 // simple-template-id
Douglas Gregor333489b2009-03-27 23:10:48 +00001330 SourceLocation TypenameLoc = ConsumeToken();
1331 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +00001332 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1333 /*EnteringContext=*/false,
Francois Pichet4e7a2c02011-03-27 19:41:34 +00001334 0, /*IsTypename*/true))
John McCall1f476a12010-02-26 08:45:28 +00001335 return true;
1336 if (!SS.isSet()) {
Richard Smithb71e7322012-05-14 22:43:34 +00001337 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
1338 // Attempt to recover by skipping the invalid 'typename'
1339 if (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1340 Tok.isAnnotation()) {
1341 unsigned DiagID = diag::err_expected_qualified_after_typename;
1342 // MS compatibility: MSVC permits using known types with typename.
1343 // e.g. "typedef typename T* pointer_type"
1344 if (getLangOpts().MicrosoftExt)
1345 DiagID = diag::warn_expected_qualified_after_typename;
1346 Diag(Tok.getLocation(), DiagID);
1347 return false;
1348 }
1349 }
1350
1351 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
John McCall1f476a12010-02-26 08:45:28 +00001352 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00001353 }
1354
1355 TypeResult Ty;
1356 if (Tok.is(tok::identifier)) {
1357 // FIXME: check whether the next token is '<', first!
Douglas Gregor0be31a22010-07-02 17:43:08 +00001358 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Douglas Gregorf7d77712010-06-16 22:31:08 +00001359 *Tok.getIdentifierInfo(),
Douglas Gregor333489b2009-03-27 23:10:48 +00001360 Tok.getLocation());
Douglas Gregordce2b622009-04-01 00:28:59 +00001361 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001362 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregordce2b622009-04-01 00:28:59 +00001363 if (TemplateId->Kind == TNK_Function_template) {
1364 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1365 << Tok.getAnnotationRange();
John McCall1f476a12010-02-26 08:45:28 +00001366 return true;
Douglas Gregordce2b622009-04-01 00:28:59 +00001367 }
Douglas Gregor333489b2009-03-27 23:10:48 +00001368
Douglas Gregorb09518c2011-02-27 22:46:49 +00001369 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
1370 TemplateId->getTemplateArgs(),
1371 TemplateId->NumArgs);
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001372
Douglas Gregorb09518c2011-02-27 22:46:49 +00001373 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001374 TemplateId->TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00001375 TemplateId->Template,
1376 TemplateId->TemplateNameLoc,
1377 TemplateId->LAngleLoc,
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00001378 TemplateArgsPtr,
Douglas Gregorb09518c2011-02-27 22:46:49 +00001379 TemplateId->RAngleLoc);
Douglas Gregordce2b622009-04-01 00:28:59 +00001380 } else {
1381 Diag(Tok, diag::err_expected_type_name_after_typename)
1382 << SS.getRange();
John McCall1f476a12010-02-26 08:45:28 +00001383 return true;
Douglas Gregordce2b622009-04-01 00:28:59 +00001384 }
1385
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +00001386 SourceLocation EndLoc = Tok.getLastLoc();
Douglas Gregordce2b622009-04-01 00:28:59 +00001387 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +00001388 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +00001389 Tok.setAnnotationEndLoc(EndLoc);
Douglas Gregordce2b622009-04-01 00:28:59 +00001390 Tok.setLocation(TypenameLoc);
1391 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001392 return false;
Douglas Gregor333489b2009-03-27 23:10:48 +00001393 }
1394
John McCalle2ade282009-12-19 00:35:18 +00001395 // Remembers whether the token was originally a scope annotation.
1396 bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1397
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001398 CXXScopeSpec SS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001399 if (getLangOpts().CPlusPlus)
John McCallba7bf592010-08-24 05:47:05 +00001400 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall1f476a12010-02-26 08:45:28 +00001401 return true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001402
1403 if (Tok.is(tok::identifier)) {
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001404 IdentifierInfo *CorrectedII = 0;
Chris Lattnerda030082009-01-05 01:49:50 +00001405 // Determine whether the identifier is a type name.
John McCallba7bf592010-08-24 05:47:05 +00001406 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1407 Tok.getLocation(), getCurScope(),
Fariborz Jahanian87967422011-02-08 18:05:59 +00001408 &SS, false,
Douglas Gregor844cb502011-03-01 18:12:44 +00001409 NextToken().is(tok::period),
1410 ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +00001411 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +00001412 /*NonTrivialTypeSourceInfo*/true,
1413 NeedType ? &CorrectedII : NULL)) {
1414 // A FixIt was applied as a result of typo correction
1415 if (CorrectedII)
1416 Tok.setIdentifierInfo(CorrectedII);
Chris Lattnerda030082009-01-05 01:49:50 +00001417 // This is a typename. Replace the current token in-place with an
1418 // annotation type token.
Chris Lattnera8a3f732009-01-06 05:06:21 +00001419 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +00001420 setTypeAnnotation(Tok, Ty);
Chris Lattnerda030082009-01-05 01:49:50 +00001421 Tok.setAnnotationEndLoc(Tok.getLocation());
1422 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1423 Tok.setLocation(SS.getBeginLoc());
Mike Stump11289f42009-09-09 15:08:12 +00001424
Chris Lattnerda030082009-01-05 01:49:50 +00001425 // In case the tokens were cached, have Preprocessor replace
1426 // them with the annotation token.
1427 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001428 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001429 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001430
David Blaikiebbafb8a2012-03-11 07:00:24 +00001431 if (!getLangOpts().CPlusPlus) {
Chris Lattnerda030082009-01-05 01:49:50 +00001432 // If we're in C, we can't have :: tokens at all (the lexer won't return
1433 // them). If the identifier is not a type, then it can't be scope either,
Mike Stump11289f42009-09-09 15:08:12 +00001434 // just early exit.
Chris Lattnerda030082009-01-05 01:49:50 +00001435 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437
Douglas Gregor7f741122009-02-25 19:37:18 +00001438 // If this is a template-id, annotate with a template-id or type token.
Douglas Gregor8bf42052009-02-09 18:46:07 +00001439 if (NextToken().is(tok::less)) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001440 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001441 UnqualifiedId TemplateName;
1442 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +00001443 bool MemberOfUnknownSpecialization;
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (TemplateNameKind TNK
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001445 = Actions.isTemplateName(getCurScope(), SS,
1446 /*hasTemplateKeyword=*/false, TemplateName,
John McCallba7bf592010-08-24 05:47:05 +00001447 /*ObjectType=*/ ParsedType(),
1448 EnteringContext,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001449 Template, MemberOfUnknownSpecialization)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00001450 // Consume the identifier.
1451 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001452 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1453 TemplateName)) {
Chris Lattner5558e9f2009-06-26 04:27:47 +00001454 // If an unrecoverable error occurred, we need to return true here,
1455 // because the token stream is in a damaged state. We may not return
1456 // a valid identifier.
John McCall1f476a12010-02-26 08:45:28 +00001457 return true;
Chris Lattner5558e9f2009-06-26 04:27:47 +00001458 }
Douglas Gregor71395fa2009-11-04 00:56:37 +00001459 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00001460 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001461
Douglas Gregor7f741122009-02-25 19:37:18 +00001462 // The current token, which is either an identifier or a
1463 // template-id, is not part of the annotation. Fall through to
1464 // push that token back into the stream and complete the C++ scope
1465 // specifier annotation.
Mike Stump11289f42009-09-09 15:08:12 +00001466 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001467
Douglas Gregor7f741122009-02-25 19:37:18 +00001468 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001469 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001470 if (TemplateId->Kind == TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001471 // A template-id that refers to a type was parsed into a
1472 // template-id annotation in a context where we weren't allowed
1473 // to produce a type annotation token. Update the template-id
1474 // annotation token to a type annotation token now.
Douglas Gregore7c20652011-03-02 00:47:37 +00001475 AnnotateTemplateIdTokenAsType();
John McCall1f476a12010-02-26 08:45:28 +00001476 return false;
Douglas Gregor7f741122009-02-25 19:37:18 +00001477 }
1478 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001479
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001480 if (SS.isEmpty())
John McCall1f476a12010-02-26 08:45:28 +00001481 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001483 // A C++ scope specifier that isn't followed by a typename.
1484 // Push the current token back into the token stream (or revert it if it is
1485 // cached) and use an annotation scope token for current token.
1486 if (PP.isBacktrackEnabled())
1487 PP.RevertCachedTokens(1);
1488 else
1489 PP.EnterToken(Tok);
1490 Tok.setKind(tok::annot_cxxscope);
Douglas Gregor869ad452011-02-24 17:54:50 +00001491 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001492 Tok.setAnnotationRange(SS.getRange());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001493
John McCalle2ade282009-12-19 00:35:18 +00001494 // In case the tokens were cached, have Preprocessor replace them
1495 // with the annotation token. We don't need to do this if we've
1496 // just reverted back to the state we were in before being called.
1497 if (!wasScopeAnnotation)
1498 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001499 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001500}
1501
1502/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Douglas Gregor7f741122009-02-25 19:37:18 +00001503/// annotates C++ scope specifiers and template-ids. This returns
Richard Smith45855df2012-05-09 08:23:23 +00001504/// true if there was an error that could not be recovered from.
Mike Stump11289f42009-09-09 15:08:12 +00001505///
Chris Lattner45ddec32009-01-05 00:13:00 +00001506/// Note that this routine emits an error if you call it with ::new or ::delete
1507/// as the current tokens, so only call it in contexts where these are invalid.
Douglas Gregore861bac2009-08-25 22:51:20 +00001508bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001509 assert(getLangOpts().CPlusPlus &&
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001510 "Call sites of this function should be guarded by checking for C++");
Douglas Gregor8b02cd02011-04-27 04:48:22 +00001511 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
David Blaikie15a430a2011-12-04 05:04:18 +00001512 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1513 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001514
Argyrios Kyrtzidisace521a2008-11-26 21:41:52 +00001515 CXXScopeSpec SS;
John McCallba7bf592010-08-24 05:47:05 +00001516 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
John McCall1f476a12010-02-26 08:45:28 +00001517 return true;
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00001518 if (SS.isEmpty())
John McCall1f476a12010-02-26 08:45:28 +00001519 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001520
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001521 // Push the current token back into the token stream (or revert it if it is
1522 // cached) and use an annotation scope token for current token.
1523 if (PP.isBacktrackEnabled())
1524 PP.RevertCachedTokens(1);
1525 else
1526 PP.EnterToken(Tok);
1527 Tok.setKind(tok::annot_cxxscope);
Douglas Gregor869ad452011-02-24 17:54:50 +00001528 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001529 Tok.setAnnotationRange(SS.getRange());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001530
Chris Lattnerdfa1a452009-01-04 22:32:19 +00001531 // In case the tokens were cached, have Preprocessor replace them with the
1532 // annotation token.
1533 PP.AnnotateCachedTokens(Tok);
John McCall1f476a12010-02-26 08:45:28 +00001534 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001535}
John McCall37958aa2009-11-03 19:33:12 +00001536
Richard Trieu4972a6d2012-01-19 22:01:51 +00001537bool Parser::isTokenEqualOrEqualTypo() {
1538 tok::TokenKind Kind = Tok.getKind();
1539 switch (Kind) {
1540 default:
Richard Trieuc64d3232012-01-18 22:54:52 +00001541 return false;
Richard Trieu4972a6d2012-01-19 22:01:51 +00001542 case tok::ampequal: // &=
1543 case tok::starequal: // *=
1544 case tok::plusequal: // +=
1545 case tok::minusequal: // -=
1546 case tok::exclaimequal: // !=
1547 case tok::slashequal: // /=
1548 case tok::percentequal: // %=
1549 case tok::lessequal: // <=
1550 case tok::lesslessequal: // <<=
1551 case tok::greaterequal: // >=
1552 case tok::greatergreaterequal: // >>=
1553 case tok::caretequal: // ^=
1554 case tok::pipeequal: // |=
1555 case tok::equalequal: // ==
1556 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1557 << getTokenSimpleSpelling(Kind)
1558 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1559 case tok::equal:
1560 return true;
1561 }
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001562}
1563
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001564SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1565 assert(Tok.is(tok::code_completion));
1566 PrevTokLocation = Tok.getLocation();
1567
Douglas Gregor0be31a22010-07-02 17:43:08 +00001568 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregor6da3db42010-05-25 05:58:43 +00001569 if (S->getFlags() & Scope::FnScope) {
John McCallfaf5fb42010-08-26 23:41:50 +00001570 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001571 cutOffParsing();
1572 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001573 }
1574
1575 if (S->getFlags() & Scope::ClassScope) {
John McCallfaf5fb42010-08-26 23:41:50 +00001576 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001577 cutOffParsing();
1578 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001579 }
1580 }
1581
John McCallfaf5fb42010-08-26 23:41:50 +00001582 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001583 cutOffParsing();
1584 return PrevTokLocation;
Douglas Gregor6da3db42010-05-25 05:58:43 +00001585}
1586
John McCall37958aa2009-11-03 19:33:12 +00001587// Anchor the Parser::FieldCallback vtable to this translation unit.
1588// We use a spurious method instead of the destructor because
1589// destroying FieldCallbacks can actually be slightly
1590// performance-sensitive.
1591void Parser::FieldCallback::_anchor() {
1592}
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001593
1594// Code-completion pass-through functions
1595
1596void Parser::CodeCompleteDirective(bool InConditional) {
Douglas Gregorec00a262010-08-24 22:20:20 +00001597 Actions.CodeCompletePreprocessorDirective(InConditional);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001598}
1599
1600void Parser::CodeCompleteInConditionalExclusion() {
1601 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1602}
Douglas Gregor12785102010-08-24 20:21:13 +00001603
1604void Parser::CodeCompleteMacroName(bool IsDefinition) {
Douglas Gregorec00a262010-08-24 22:20:20 +00001605 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1606}
1607
1608void Parser::CodeCompletePreprocessorExpression() {
1609 Actions.CodeCompletePreprocessorExpression();
1610}
1611
1612void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1613 MacroInfo *MacroInfo,
1614 unsigned ArgumentIndex) {
1615 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1616 ArgumentIndex);
Douglas Gregor12785102010-08-24 20:21:13 +00001617}
Douglas Gregor11583702010-08-25 17:04:25 +00001618
1619void Parser::CodeCompleteNaturalLanguage() {
1620 Actions.CodeCompleteNaturalLanguage();
1621}
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001622
Douglas Gregor43edb322011-10-24 22:31:10 +00001623bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001624 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1625 "Expected '__if_exists' or '__if_not_exists'");
Douglas Gregor43edb322011-10-24 22:31:10 +00001626 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1627 Result.KeywordLoc = ConsumeToken();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001628
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001629 BalancedDelimiterTracker T(*this, tok::l_paren);
1630 if (T.consumeOpen()) {
Douglas Gregor43edb322011-10-24 22:31:10 +00001631 Diag(Tok, diag::err_expected_lparen_after)
1632 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001633 return true;
1634 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001635
1636 // Parse nested-name-specifier.
Douglas Gregordf593fb2011-11-07 17:33:42 +00001637 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1638 /*EnteringContext=*/false);
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001639
1640 // Check nested-name specifier.
Douglas Gregor43edb322011-10-24 22:31:10 +00001641 if (Result.SS.isInvalid()) {
1642 T.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001643 return true;
1644 }
1645
Abramo Bagnara7945c982012-01-27 09:46:47 +00001646 // Parse the unqualified-id.
1647 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1648 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1649 TemplateKWLoc, Result.Name)) {
Douglas Gregor43edb322011-10-24 22:31:10 +00001650 T.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001651 return true;
1652 }
1653
Douglas Gregor43edb322011-10-24 22:31:10 +00001654 if (T.consumeClose())
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001655 return true;
Douglas Gregor43edb322011-10-24 22:31:10 +00001656
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001657 // Check if the symbol exists.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001658 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1659 Result.IsIfExists, Result.SS,
Douglas Gregor43edb322011-10-24 22:31:10 +00001660 Result.Name)) {
1661 case Sema::IER_Exists:
1662 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1663 break;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001664
Douglas Gregor43edb322011-10-24 22:31:10 +00001665 case Sema::IER_DoesNotExist:
1666 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1667 break;
1668
1669 case Sema::IER_Dependent:
1670 Result.Behavior = IEB_Dependent;
1671 break;
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001672
1673 case Sema::IER_Error:
1674 return true;
Douglas Gregor43edb322011-10-24 22:31:10 +00001675 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001676
1677 return false;
1678}
1679
Francois Pichet8f981d52011-05-25 10:19:49 +00001680void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
Douglas Gregor43edb322011-10-24 22:31:10 +00001681 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001682 if (ParseMicrosoftIfExistsCondition(Result))
1683 return;
1684
Douglas Gregor43edb322011-10-24 22:31:10 +00001685 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1686 if (Braces.consumeOpen()) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001687 Diag(Tok, diag::err_expected_lbrace);
1688 return;
1689 }
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001690
Douglas Gregor43edb322011-10-24 22:31:10 +00001691 switch (Result.Behavior) {
1692 case IEB_Parse:
1693 // Parse declarations below.
1694 break;
1695
1696 case IEB_Dependent:
1697 llvm_unreachable("Cannot have a dependent external declaration");
1698
1699 case IEB_Skip:
1700 Braces.skipToEnd();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001701 return;
1702 }
1703
Douglas Gregor43edb322011-10-24 22:31:10 +00001704 // Parse the declarations.
1705 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001706 ParsedAttributesWithRange attrs(AttrFactory);
1707 MaybeParseCXX0XAttributes(attrs);
1708 MaybeParseMicrosoftAttributes(attrs);
1709 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1710 if (Result && !getCurScope()->getParent())
1711 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00001712 }
1713 Braces.consumeClose();
Francois Picheta5b3fcb2011-05-07 17:30:27 +00001714}
Douglas Gregor08142532011-08-26 23:56:07 +00001715
Douglas Gregor22d09742012-01-03 18:04:46 +00001716Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001717 assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&
Douglas Gregorca975892011-08-31 18:19:09 +00001718 "Improper start to module import");
Douglas Gregor08142532011-08-26 23:56:07 +00001719 SourceLocation ImportLoc = ConsumeToken();
1720
Douglas Gregor71944202011-11-30 00:36:36 +00001721 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor08142532011-08-26 23:56:07 +00001722
Douglas Gregor71944202011-11-30 00:36:36 +00001723 // Parse the module path.
1724 do {
1725 if (!Tok.is(tok::identifier)) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001726 if (Tok.is(tok::code_completion)) {
1727 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1728 ConsumeCodeCompletionToken();
1729 SkipUntil(tok::semi);
1730 return DeclGroupPtrTy();
1731 }
1732
Douglas Gregor71944202011-11-30 00:36:36 +00001733 Diag(Tok, diag::err_module_expected_ident);
1734 SkipUntil(tok::semi);
1735 return DeclGroupPtrTy();
1736 }
1737
1738 // Record this part of the module path.
1739 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1740 ConsumeToken();
1741
1742 if (Tok.is(tok::period)) {
1743 ConsumeToken();
1744 continue;
1745 }
1746
1747 break;
1748 } while (true);
1749
Douglas Gregor22d09742012-01-03 18:04:46 +00001750 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
Douglas Gregor08142532011-08-26 23:56:07 +00001751 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1752 if (Import.isInvalid())
1753 return DeclGroupPtrTy();
1754
1755 return Actions.ConvertDeclToDeclGroup(Import.get());
1756}
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001757
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001758bool BalancedDelimiterTracker::diagnoseOverflow() {
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001759 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1760 P.SkipUntil(tok::eof);
1761 return true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001762}
1763
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001764bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001765 const char *Msg,
1766 tok::TokenKind SkipToToc ) {
1767 LOpen = P.Tok.getLocation();
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001768 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1769 return true;
1770
1771 if (getDepth() < MaxDepth)
1772 return false;
1773
1774 return diagnoseOverflow();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001775}
1776
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001777bool BalancedDelimiterTracker::diagnoseMissingClose() {
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001778 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1779
1780 const char *LHSName = "unknown";
David Blaikie89f13cb2012-04-06 23:33:59 +00001781 diag::kind DID;
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001782 switch (Close) {
David Blaikie89f13cb2012-04-06 23:33:59 +00001783 default: llvm_unreachable("Unexpected balanced token");
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001784 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1785 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1786 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001787 }
Douglas Gregor0cf55e92012-03-08 01:00:17 +00001788 P.Diag(P.Tok, DID);
1789 P.Diag(LOpen, diag::note_matching) << LHSName;
1790 if (P.SkipUntil(Close))
1791 LClose = P.Tok.getLocation();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001792 return true;
1793}
Douglas Gregor43edb322011-10-24 22:31:10 +00001794
Douglas Gregor91c25ea2012-06-06 21:18:07 +00001795void BalancedDelimiterTracker::skipToEnd() {
Douglas Gregor43edb322011-10-24 22:31:10 +00001796 P.SkipUntil(Close, false);
Douglas Gregor43edb322011-10-24 22:31:10 +00001797}