1193326Sed//===--- Parser.cpp - C Language Family Parser ----------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements the Parser interfaces.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "clang/Parse/Parser.h"
15249423Sdim#include "ParsePragma.h"
16249423Sdim#include "RAIIObjectsForParser.h"
17249423Sdim#include "clang/AST/ASTConsumer.h"
18249423Sdim#include "clang/AST/DeclTemplate.h"
19193326Sed#include "clang/Parse/ParseDiagnostic.h"
20212904Sdim#include "clang/Sema/DeclSpec.h"
21249423Sdim#include "clang/Sema/ParsedTemplate.h"
22212904Sdim#include "clang/Sema/Scope.h"
23193326Sed#include "llvm/Support/raw_ostream.h"
24193326Sedusing namespace clang;
25193326Sed
26243830Sdim
27239462Sdimnamespace {
28239462Sdim/// \brief A comment handler that passes comments found by the preprocessor
29239462Sdim/// to the parser action.
30239462Sdimclass ActionCommentHandler : public CommentHandler {
31239462Sdim  Sema &S;
32239462Sdim
33239462Sdimpublic:
34239462Sdim  explicit ActionCommentHandler(Sema &S) : S(S) { }
35239462Sdim
36239462Sdim  virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37239462Sdim    S.ActOnComment(Comment);
38239462Sdim    return false;
39239462Sdim  }
40239462Sdim};
41239462Sdim} // end anonymous namespace
42239462Sdim
43234353SdimIdentifierInfo *Parser::getSEHExceptKeyword() {
44234353Sdim  // __except is accepted as a (contextual) keyword
45234353Sdim  if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46234353Sdim    Ident__except = PP.getIdentifierInfo("__except");
47234353Sdim
48234353Sdim  return Ident__except;
49234353Sdim}
50234353Sdim
51243830SdimParser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52221345Sdim  : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53218893Sdim    GreaterThanIsOperator(true), ColonIsSacred(false),
54234353Sdim    InMessageExpression(false), TemplateParameterDepth(0),
55243830Sdim    ParsingInObjCContainer(false) {
56243830Sdim  SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57243830Sdim  Tok.startToken();
58193326Sed  Tok.setKind(tok::eof);
59210299Sed  Actions.CurScope = 0;
60193326Sed  NumCachedScopes = 0;
61193326Sed  ParenCount = BracketCount = BraceCount = 0;
62234353Sdim  CurParsedObjCImpl = 0;
63193326Sed
64193326Sed  // Add #pragma handlers. These are removed and destroyed in the
65193326Sed  // destructor.
66243830Sdim  AlignHandler.reset(new PragmaAlignHandler());
67212904Sdim  PP.AddPragmaHandler(AlignHandler.get());
68212904Sdim
69243830Sdim  GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
70212904Sdim  PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
71212904Sdim
72243830Sdim  OptionsHandler.reset(new PragmaOptionsHandler());
73210299Sed  PP.AddPragmaHandler(OptionsHandler.get());
74208600Srdivacky
75243830Sdim  PackHandler.reset(new PragmaPackHandler());
76210299Sed  PP.AddPragmaHandler(PackHandler.get());
77221345Sdim
78243830Sdim  MSStructHandler.reset(new PragmaMSStructHandler());
79221345Sdim  PP.AddPragmaHandler(MSStructHandler.get());
80198092Srdivacky
81243830Sdim  UnusedHandler.reset(new PragmaUnusedHandler());
82210299Sed  PP.AddPragmaHandler(UnusedHandler.get());
83193576Sed
84243830Sdim  WeakHandler.reset(new PragmaWeakHandler());
85210299Sed  PP.AddPragmaHandler(WeakHandler.get());
86218893Sdim
87243830Sdim  RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
88234353Sdim  PP.AddPragmaHandler(RedefineExtnameHandler.get());
89234353Sdim
90243830Sdim  FPContractHandler.reset(new PragmaFPContractHandler());
91218893Sdim  PP.AddPragmaHandler("STDC", FPContractHandler.get());
92218893Sdim
93234353Sdim  if (getLangOpts().OpenCL) {
94243830Sdim    OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
95218893Sdim    PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
96218893Sdim
97218893Sdim    PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
98218893Sdim  }
99249423Sdim  if (getLangOpts().OpenMP)
100249423Sdim    OpenMPHandler.reset(new PragmaOpenMPHandler());
101249423Sdim  else
102249423Sdim    OpenMPHandler.reset(new PragmaNoOpenMPHandler());
103249423Sdim  PP.AddPragmaHandler(OpenMPHandler.get());
104239462Sdim
105251662Sdim  if (getLangOpts().MicrosoftExt) {
106263508Sdim    MSCommentHandler.reset(new PragmaCommentHandler(actions));
107251662Sdim    PP.AddPragmaHandler(MSCommentHandler.get());
108263508Sdim    MSDetectMismatchHandler.reset(new PragmaDetectMismatchHandler(actions));
109263508Sdim    PP.AddPragmaHandler(MSDetectMismatchHandler.get());
110251662Sdim  }
111251662Sdim
112239462Sdim  CommentSemaHandler.reset(new ActionCommentHandler(actions));
113239462Sdim  PP.addCommentHandler(CommentSemaHandler.get());
114239462Sdim
115212904Sdim  PP.setCodeCompletionHandler(*this);
116193326Sed}
117193326Sed
118193326SedDiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
119218893Sdim  return Diags.Report(Loc, DiagID);
120193326Sed}
121193326Sed
122193326SedDiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
123193326Sed  return Diag(Tok.getLocation(), DiagID);
124193326Sed}
125193326Sed
126193326Sed/// \brief Emits a diagnostic suggesting parentheses surrounding a
127193326Sed/// given range.
128193326Sed///
129193326Sed/// \param Loc The location where we'll emit the diagnostic.
130243830Sdim/// \param DK The kind of diagnostic to emit.
131193326Sed/// \param ParenRange Source range enclosing code that should be parenthesized.
132193326Sedvoid Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
133193326Sed                                SourceRange ParenRange) {
134193326Sed  SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
135193326Sed  if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
136193326Sed    // We can't display the parentheses, so just dig the
137193326Sed    // warning/error and return.
138193326Sed    Diag(Loc, DK);
139193326Sed    return;
140193326Sed  }
141198092Srdivacky
142198092Srdivacky  Diag(Loc, DK)
143206084Srdivacky    << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
144206084Srdivacky    << FixItHint::CreateInsertion(EndLoc, ")");
145193326Sed}
146193326Sed
147218893Sdimstatic bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
148218893Sdim  switch (ExpectedTok) {
149243830Sdim  case tok::semi:
150243830Sdim    return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
151218893Sdim  default: return false;
152218893Sdim  }
153218893Sdim}
154218893Sdim
155193326Sed/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
156193326Sed/// input.  If so, it is consumed and false is returned.
157193326Sed///
158193326Sed/// If the input is malformed, this emits the specified diagnostic.  Next, if
159193326Sed/// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
160193326Sed/// returned.
161193326Sedbool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
162193326Sed                              const char *Msg, tok::TokenKind SkipToTok) {
163208600Srdivacky  if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
164193326Sed    ConsumeAnyToken();
165193326Sed    return false;
166193326Sed  }
167193326Sed
168218893Sdim  // Detect common single-character typos and resume.
169218893Sdim  if (IsCommonTypo(ExpectedTok, Tok)) {
170218893Sdim    SourceLocation Loc = Tok.getLocation();
171218893Sdim    Diag(Loc, DiagID)
172218893Sdim      << Msg
173218893Sdim      << FixItHint::CreateReplacement(SourceRange(Loc),
174218893Sdim                                      getTokenSimpleSpelling(ExpectedTok));
175218893Sdim    ConsumeAnyToken();
176218893Sdim
177218893Sdim    // Pretend there wasn't a problem.
178218893Sdim    return false;
179218893Sdim  }
180218893Sdim
181193326Sed  const char *Spelling = 0;
182193326Sed  SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
183198092Srdivacky  if (EndLoc.isValid() &&
184193326Sed      (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
185193326Sed    // Show what code to insert to fix this problem.
186198092Srdivacky    Diag(EndLoc, DiagID)
187193326Sed      << Msg
188206084Srdivacky      << FixItHint::CreateInsertion(EndLoc, Spelling);
189193326Sed  } else
190193326Sed    Diag(Tok, DiagID) << Msg;
191193326Sed
192193326Sed  if (SkipToTok != tok::unknown)
193263508Sdim    SkipUntil(SkipToTok, StopAtSemi);
194193326Sed  return true;
195193326Sed}
196193326Sed
197218893Sdimbool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
198218893Sdim  if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
199239462Sdim    ConsumeToken();
200218893Sdim    return false;
201218893Sdim  }
202218893Sdim
203218893Sdim  if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
204218893Sdim      NextToken().is(tok::semi)) {
205218893Sdim    Diag(Tok, diag::err_extraneous_token_before_semi)
206218893Sdim      << PP.getSpelling(Tok)
207218893Sdim      << FixItHint::CreateRemoval(Tok.getLocation());
208218893Sdim    ConsumeAnyToken(); // The ')' or ']'.
209218893Sdim    ConsumeToken(); // The ';'.
210218893Sdim    return false;
211218893Sdim  }
212218893Sdim
213218893Sdim  return ExpectAndConsume(tok::semi, DiagID);
214218893Sdim}
215218893Sdim
216239462Sdimvoid Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
217239462Sdim  if (!Tok.is(tok::semi)) return;
218239462Sdim
219239462Sdim  bool HadMultipleSemis = false;
220239462Sdim  SourceLocation StartLoc = Tok.getLocation();
221239462Sdim  SourceLocation EndLoc = Tok.getLocation();
222239462Sdim  ConsumeToken();
223239462Sdim
224239462Sdim  while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
225239462Sdim    HadMultipleSemis = true;
226239462Sdim    EndLoc = Tok.getLocation();
227239462Sdim    ConsumeToken();
228239462Sdim  }
229239462Sdim
230239462Sdim  // C++11 allows extra semicolons at namespace scope, but not in any of the
231239462Sdim  // other contexts.
232239462Sdim  if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
233249423Sdim    if (getLangOpts().CPlusPlus11)
234239462Sdim      Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
235239462Sdim          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
236239462Sdim    else
237239462Sdim      Diag(StartLoc, diag::ext_extra_semi_cxx11)
238239462Sdim          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
239239462Sdim    return;
240239462Sdim  }
241239462Sdim
242239462Sdim  if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
243239462Sdim    Diag(StartLoc, diag::ext_extra_semi)
244239462Sdim        << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
245239462Sdim        << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
246239462Sdim  else
247239462Sdim    // A single semicolon is valid after a member function definition.
248239462Sdim    Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
249239462Sdim      << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
250239462Sdim}
251239462Sdim
252193326Sed//===----------------------------------------------------------------------===//
253193326Sed// Error recovery.
254193326Sed//===----------------------------------------------------------------------===//
255193326Sed
256263508Sdimstatic bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
257263508Sdim  return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
258263508Sdim}
259263508Sdim
260193326Sed/// SkipUntil - Read tokens until we get to the specified token, then consume
261263508Sdim/// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
262193326Sed/// token will ever occur, this skips to the next token, or to some likely
263193326Sed/// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
264193326Sed/// character.
265193326Sed///
266193326Sed/// If SkipUntil finds the specified token, it returns true, otherwise it
267193326Sed/// returns false.
268263508Sdimbool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
269193326Sed  // We always want this function to skip at least one token if the first token
270193326Sed  // isn't T and if not at EOF.
271193326Sed  bool isFirstTokenSkipped = true;
272193326Sed  while (1) {
273193326Sed    // If we found one of the tokens, stop and return true.
274234353Sdim    for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
275193326Sed      if (Tok.is(Toks[i])) {
276263508Sdim        if (HasFlagsSet(Flags, StopBeforeMatch)) {
277193326Sed          // Noop, don't consume the token.
278193326Sed        } else {
279193326Sed          ConsumeAnyToken();
280193326Sed        }
281193326Sed        return true;
282193326Sed      }
283193326Sed    }
284193326Sed
285263508Sdim    // Important special case: The caller has given up and just wants us to
286263508Sdim    // skip the rest of the file. Do this without recursing, since we can
287263508Sdim    // get here precisely because the caller detected too much recursion.
288263508Sdim    if (Toks.size() == 1 && Toks[0] == tok::eof &&
289263508Sdim        !HasFlagsSet(Flags, StopAtSemi) &&
290263508Sdim        !HasFlagsSet(Flags, StopAtCodeCompletion)) {
291263508Sdim      while (Tok.getKind() != tok::eof)
292263508Sdim        ConsumeAnyToken();
293263508Sdim      return true;
294263508Sdim    }
295263508Sdim
296193326Sed    switch (Tok.getKind()) {
297193326Sed    case tok::eof:
298193326Sed      // Ran out of tokens.
299193326Sed      return false;
300208600Srdivacky
301208600Srdivacky    case tok::code_completion:
302263508Sdim      if (!HasFlagsSet(Flags, StopAtCodeCompletion))
303218893Sdim        ConsumeToken();
304208600Srdivacky      return false;
305208600Srdivacky
306193326Sed    case tok::l_paren:
307193326Sed      // Recursively skip properly-nested parens.
308193326Sed      ConsumeParen();
309263508Sdim      if (HasFlagsSet(Flags, StopAtCodeCompletion))
310263508Sdim        SkipUntil(tok::r_paren, StopAtCodeCompletion);
311263508Sdim      else
312263508Sdim        SkipUntil(tok::r_paren);
313193326Sed      break;
314193326Sed    case tok::l_square:
315193326Sed      // Recursively skip properly-nested square brackets.
316193326Sed      ConsumeBracket();
317263508Sdim      if (HasFlagsSet(Flags, StopAtCodeCompletion))
318263508Sdim        SkipUntil(tok::r_square, StopAtCodeCompletion);
319263508Sdim      else
320263508Sdim        SkipUntil(tok::r_square);
321193326Sed      break;
322193326Sed    case tok::l_brace:
323193326Sed      // Recursively skip properly-nested braces.
324193326Sed      ConsumeBrace();
325263508Sdim      if (HasFlagsSet(Flags, StopAtCodeCompletion))
326263508Sdim        SkipUntil(tok::r_brace, StopAtCodeCompletion);
327263508Sdim      else
328263508Sdim        SkipUntil(tok::r_brace);
329193326Sed      break;
330193326Sed
331193326Sed    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
332193326Sed    // Since the user wasn't looking for this token (if they were, it would
333193326Sed    // already be handled), this isn't balanced.  If there is a LHS token at a
334193326Sed    // higher level, we will assume that this matches the unbalanced token
335193326Sed    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
336193326Sed    case tok::r_paren:
337193326Sed      if (ParenCount && !isFirstTokenSkipped)
338193326Sed        return false;  // Matches something.
339193326Sed      ConsumeParen();
340193326Sed      break;
341193326Sed    case tok::r_square:
342193326Sed      if (BracketCount && !isFirstTokenSkipped)
343193326Sed        return false;  // Matches something.
344193326Sed      ConsumeBracket();
345193326Sed      break;
346193326Sed    case tok::r_brace:
347193326Sed      if (BraceCount && !isFirstTokenSkipped)
348193326Sed        return false;  // Matches something.
349193326Sed      ConsumeBrace();
350193326Sed      break;
351193326Sed
352193326Sed    case tok::string_literal:
353193326Sed    case tok::wide_string_literal:
354226633Sdim    case tok::utf8_string_literal:
355226633Sdim    case tok::utf16_string_literal:
356226633Sdim    case tok::utf32_string_literal:
357193326Sed      ConsumeStringToken();
358193326Sed      break;
359219077Sdim
360193326Sed    case tok::semi:
361263508Sdim      if (HasFlagsSet(Flags, StopAtSemi))
362193326Sed        return false;
363193326Sed      // FALL THROUGH.
364193326Sed    default:
365193326Sed      // Skip this token.
366193326Sed      ConsumeToken();
367193326Sed      break;
368193326Sed    }
369193326Sed    isFirstTokenSkipped = false;
370193326Sed  }
371193326Sed}
372193326Sed
373193326Sed//===----------------------------------------------------------------------===//
374193326Sed// Scope manipulation
375193326Sed//===----------------------------------------------------------------------===//
376193326Sed
377193326Sed/// EnterScope - Start a new scope.
378193326Sedvoid Parser::EnterScope(unsigned ScopeFlags) {
379193326Sed  if (NumCachedScopes) {
380193326Sed    Scope *N = ScopeCache[--NumCachedScopes];
381210299Sed    N->Init(getCurScope(), ScopeFlags);
382210299Sed    Actions.CurScope = N;
383193326Sed  } else {
384218893Sdim    Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
385193326Sed  }
386193326Sed}
387193326Sed
388193326Sed/// ExitScope - Pop a scope off the scope stack.
389193326Sedvoid Parser::ExitScope() {
390210299Sed  assert(getCurScope() && "Scope imbalance!");
391193326Sed
392193326Sed  // Inform the actions module that this scope is going away if there are any
393193326Sed  // decls in it.
394210299Sed  if (!getCurScope()->decl_empty())
395210299Sed    Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
396193326Sed
397210299Sed  Scope *OldScope = getCurScope();
398210299Sed  Actions.CurScope = OldScope->getParent();
399193326Sed
400193326Sed  if (NumCachedScopes == ScopeCacheSize)
401193326Sed    delete OldScope;
402193326Sed  else
403193326Sed    ScopeCache[NumCachedScopes++] = OldScope;
404193326Sed}
405193326Sed
406223017Sdim/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
407223017Sdim/// this object does nothing.
408223017SdimParser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
409223017Sdim                                 bool ManageFlags)
410223017Sdim  : CurScope(ManageFlags ? Self->getCurScope() : 0) {
411223017Sdim  if (CurScope) {
412223017Sdim    OldFlags = CurScope->getFlags();
413223017Sdim    CurScope->setFlags(ScopeFlags);
414223017Sdim  }
415223017Sdim}
416193326Sed
417223017Sdim/// Restore the flags for the current scope to what they were before this
418223017Sdim/// object overrode them.
419223017SdimParser::ParseScopeFlags::~ParseScopeFlags() {
420223017Sdim  if (CurScope)
421223017Sdim    CurScope->setFlags(OldFlags);
422223017Sdim}
423193326Sed
424193326Sed
425193326Sed//===----------------------------------------------------------------------===//
426193326Sed// C99 6.9: External Definitions.
427193326Sed//===----------------------------------------------------------------------===//
428193326Sed
429193326SedParser::~Parser() {
430193326Sed  // If we still have scopes active, delete the scope tree.
431210299Sed  delete getCurScope();
432210299Sed  Actions.CurScope = 0;
433210299Sed
434193326Sed  // Free the scope cache.
435193326Sed  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
436193326Sed    delete ScopeCache[i];
437193326Sed
438193326Sed  // Remove the pragma handlers we installed.
439212904Sdim  PP.RemovePragmaHandler(AlignHandler.get());
440212904Sdim  AlignHandler.reset();
441212904Sdim  PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
442212904Sdim  GCCVisibilityHandler.reset();
443210299Sed  PP.RemovePragmaHandler(OptionsHandler.get());
444208600Srdivacky  OptionsHandler.reset();
445210299Sed  PP.RemovePragmaHandler(PackHandler.get());
446193326Sed  PackHandler.reset();
447221345Sdim  PP.RemovePragmaHandler(MSStructHandler.get());
448221345Sdim  MSStructHandler.reset();
449210299Sed  PP.RemovePragmaHandler(UnusedHandler.get());
450193326Sed  UnusedHandler.reset();
451210299Sed  PP.RemovePragmaHandler(WeakHandler.get());
452193576Sed  WeakHandler.reset();
453234353Sdim  PP.RemovePragmaHandler(RedefineExtnameHandler.get());
454234353Sdim  RedefineExtnameHandler.reset();
455218893Sdim
456234353Sdim  if (getLangOpts().OpenCL) {
457218893Sdim    PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
458218893Sdim    OpenCLExtensionHandler.reset();
459218893Sdim    PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
460218893Sdim  }
461249423Sdim  PP.RemovePragmaHandler(OpenMPHandler.get());
462249423Sdim  OpenMPHandler.reset();
463218893Sdim
464251662Sdim  if (getLangOpts().MicrosoftExt) {
465251662Sdim    PP.RemovePragmaHandler(MSCommentHandler.get());
466251662Sdim    MSCommentHandler.reset();
467263508Sdim    PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
468263508Sdim    MSDetectMismatchHandler.reset();
469251662Sdim  }
470251662Sdim
471218893Sdim  PP.RemovePragmaHandler("STDC", FPContractHandler.get());
472218893Sdim  FPContractHandler.reset();
473239462Sdim
474239462Sdim  PP.removeCommentHandler(CommentSemaHandler.get());
475239462Sdim
476212904Sdim  PP.clearCodeCompletionHandler();
477234982Sdim
478234982Sdim  assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
479193326Sed}
480193326Sed
481193326Sed/// Initialize - Warm up the parser.
482193326Sed///
483193326Sedvoid Parser::Initialize() {
484193326Sed  // Create the translation unit scope.  Install it as the current scope.
485210299Sed  assert(getCurScope() == 0 && "A scope is already active?");
486193326Sed  EnterScope(Scope::DeclScope);
487212904Sdim  Actions.ActOnTranslationUnitScope(getCurScope());
488193326Sed
489193326Sed  // Initialization for Objective-C context sensitive keywords recognition.
490193326Sed  // Referenced in Parser::ParseObjCTypeQualifierList.
491234353Sdim  if (getLangOpts().ObjC1) {
492193326Sed    ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
493193326Sed    ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
494193326Sed    ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
495193326Sed    ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
496193326Sed    ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
497193326Sed    ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
498193326Sed  }
499193326Sed
500226633Sdim  Ident_instancetype = 0;
501218893Sdim  Ident_final = 0;
502263508Sdim  Ident_sealed = 0;
503218893Sdim  Ident_override = 0;
504218893Sdim
505193326Sed  Ident_super = &PP.getIdentifierTable().get("super");
506203955Srdivacky
507234353Sdim  if (getLangOpts().AltiVec) {
508203955Srdivacky    Ident_vector = &PP.getIdentifierTable().get("vector");
509203955Srdivacky    Ident_pixel = &PP.getIdentifierTable().get("pixel");
510263508Sdim    Ident_bool = &PP.getIdentifierTable().get("bool");
511203955Srdivacky  }
512221345Sdim
513221345Sdim  Ident_introduced = 0;
514221345Sdim  Ident_deprecated = 0;
515221345Sdim  Ident_obsoleted = 0;
516221345Sdim  Ident_unavailable = 0;
517221345Sdim
518234353Sdim  Ident__except = 0;
519234353Sdim
520221345Sdim  Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
521221345Sdim  Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
522221345Sdim  Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
523221345Sdim
524234353Sdim  if(getLangOpts().Borland) {
525221345Sdim    Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
526221345Sdim    Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
527221345Sdim    Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
528221345Sdim    Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
529221345Sdim    Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
530221345Sdim    Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
531221345Sdim    Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
532221345Sdim    Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
533221345Sdim    Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
534221345Sdim
535221345Sdim    PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
536221345Sdim    PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
537221345Sdim    PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
538221345Sdim    PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
539221345Sdim    PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
540221345Sdim    PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
541221345Sdim    PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
542221345Sdim    PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
543221345Sdim    PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
544221345Sdim  }
545243830Sdim
546243830Sdim  Actions.Initialize();
547243830Sdim
548243830Sdim  // Prime the lexer look-ahead.
549243830Sdim  ConsumeToken();
550193326Sed}
551193326Sed
552234982Sdimnamespace {
553234982Sdim  /// \brief RAIIObject to destroy the contents of a SmallVector of
554234982Sdim  /// TemplateIdAnnotation pointers and clear the vector.
555234982Sdim  class DestroyTemplateIdAnnotationsRAIIObj {
556234982Sdim    SmallVectorImpl<TemplateIdAnnotation *> &Container;
557234982Sdim  public:
558234982Sdim    DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
559234982Sdim                                       &Container)
560234982Sdim      : Container(Container) {}
561234982Sdim
562234982Sdim    ~DestroyTemplateIdAnnotationsRAIIObj() {
563234982Sdim      for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
564234982Sdim           Container.begin(), E = Container.end();
565234982Sdim           I != E; ++I)
566234982Sdim        (*I)->Destroy();
567234982Sdim      Container.clear();
568234982Sdim    }
569234982Sdim  };
570234982Sdim}
571234982Sdim
572193326Sed/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
573193326Sed/// action tells us to.  This returns true if the EOF was encountered.
574193326Sedbool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
575234982Sdim  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
576218893Sdim
577234353Sdim  // Skip over the EOF token, flagging end of previous input for incremental
578234353Sdim  // processing
579234353Sdim  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
580234353Sdim    ConsumeToken();
581234353Sdim
582263508Sdim  Result = DeclGroupPtrTy();
583263508Sdim  switch (Tok.getKind()) {
584263508Sdim  case tok::annot_pragma_unused:
585218893Sdim    HandlePragmaUnused();
586263508Sdim    return false;
587218893Sdim
588263508Sdim  case tok::annot_module_include:
589263508Sdim    Actions.ActOnModuleInclude(Tok.getLocation(),
590263508Sdim                               reinterpret_cast<Module *>(
591263508Sdim                                   Tok.getAnnotationValue()));
592263508Sdim    ConsumeToken();
593263508Sdim    return false;
594263508Sdim
595263508Sdim  case tok::eof:
596221345Sdim    // Late template parsing can begin.
597234353Sdim    if (getLangOpts().DelayedTemplateParsing)
598221345Sdim      Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
599234353Sdim    if (!PP.isIncrementalProcessingEnabled())
600234353Sdim      Actions.ActOnEndOfTranslationUnit();
601234353Sdim    //else don't tell Sema that we ended parsing: more input might come.
602263508Sdim    return true;
603221345Sdim
604263508Sdim  default:
605263508Sdim    break;
606193326Sed  }
607193326Sed
608221345Sdim  ParsedAttributesWithRange attrs(AttrFactory);
609249423Sdim  MaybeParseCXX11Attributes(attrs);
610218893Sdim  MaybeParseMicrosoftAttributes(attrs);
611234353Sdim
612218893Sdim  Result = ParseExternalDeclaration(attrs);
613193326Sed  return false;
614193326Sed}
615193326Sed
616193326Sed/// ParseExternalDeclaration:
617193326Sed///
618193326Sed///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
619193326Sed///         function-definition
620193326Sed///         declaration
621193326Sed/// [GNU]   asm-definition
622193326Sed/// [GNU]   __extension__ external-declaration
623193326Sed/// [OBJC]  objc-class-definition
624193326Sed/// [OBJC]  objc-class-declaration
625193326Sed/// [OBJC]  objc-alias-declaration
626193326Sed/// [OBJC]  objc-protocol-definition
627193326Sed/// [OBJC]  objc-method-definition
628193326Sed/// [OBJC]  @end
629193326Sed/// [C++]   linkage-specification
630193326Sed/// [GNU] asm-definition:
631193326Sed///         simple-asm-expr ';'
632249423Sdim/// [C++11] empty-declaration
633249423Sdim/// [C++11] attribute-declaration
634193326Sed///
635249423Sdim/// [C++11] empty-declaration:
636198092Srdivacky///           ';'
637198092Srdivacky///
638198092Srdivacky/// [C++0x/GNU] 'extern' 'template' declaration
639218893SdimParser::DeclGroupPtrTy
640218893SdimParser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
641218893Sdim                                 ParsingDeclSpec *DS) {
642234982Sdim  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
643210299Sed  ParenBraceBracketBalancer BalancerRAIIObj(*this);
644226633Sdim
645226633Sdim  if (PP.isCodeCompletionReached()) {
646226633Sdim    cutOffParsing();
647226633Sdim    return DeclGroupPtrTy();
648226633Sdim  }
649226633Sdim
650212904Sdim  Decl *SingleDecl = 0;
651193326Sed  switch (Tok.getKind()) {
652234353Sdim  case tok::annot_pragma_vis:
653234353Sdim    HandlePragmaVisibility();
654234353Sdim    return DeclGroupPtrTy();
655234353Sdim  case tok::annot_pragma_pack:
656234353Sdim    HandlePragmaPack();
657234353Sdim    return DeclGroupPtrTy();
658243830Sdim  case tok::annot_pragma_msstruct:
659243830Sdim    HandlePragmaMSStruct();
660243830Sdim    return DeclGroupPtrTy();
661243830Sdim  case tok::annot_pragma_align:
662243830Sdim    HandlePragmaAlign();
663243830Sdim    return DeclGroupPtrTy();
664243830Sdim  case tok::annot_pragma_weak:
665243830Sdim    HandlePragmaWeak();
666243830Sdim    return DeclGroupPtrTy();
667243830Sdim  case tok::annot_pragma_weakalias:
668243830Sdim    HandlePragmaWeakAlias();
669243830Sdim    return DeclGroupPtrTy();
670243830Sdim  case tok::annot_pragma_redefine_extname:
671243830Sdim    HandlePragmaRedefineExtname();
672243830Sdim    return DeclGroupPtrTy();
673243830Sdim  case tok::annot_pragma_fp_contract:
674243830Sdim    HandlePragmaFPContract();
675243830Sdim    return DeclGroupPtrTy();
676243830Sdim  case tok::annot_pragma_opencl_extension:
677243830Sdim    HandlePragmaOpenCLExtension();
678243830Sdim    return DeclGroupPtrTy();
679249423Sdim  case tok::annot_pragma_openmp:
680249423Sdim    ParseOpenMPDeclarativeDirective();
681249423Sdim    return DeclGroupPtrTy();
682193326Sed  case tok::semi:
683249423Sdim    // Either a C++11 empty-declaration or attribute-declaration.
684249423Sdim    SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
685249423Sdim                                               attrs.getList(),
686249423Sdim                                               Tok.getLocation());
687239462Sdim    ConsumeExtraSemi(OutsideFunction);
688249423Sdim    break;
689193326Sed  case tok::r_brace:
690234353Sdim    Diag(Tok, diag::err_extraneous_closing_brace);
691193326Sed    ConsumeBrace();
692193326Sed    return DeclGroupPtrTy();
693193326Sed  case tok::eof:
694193326Sed    Diag(Tok, diag::err_expected_external_declaration);
695193326Sed    return DeclGroupPtrTy();
696193326Sed  case tok::kw___extension__: {
697193326Sed    // __extension__ silences extension warnings in the subexpression.
698193326Sed    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
699193326Sed    ConsumeToken();
700218893Sdim    return ParseExternalDeclaration(attrs);
701193326Sed  }
702193326Sed  case tok::kw_asm: {
703218893Sdim    ProhibitAttributes(attrs);
704199990Srdivacky
705221345Sdim    SourceLocation StartLoc = Tok.getLocation();
706221345Sdim    SourceLocation EndLoc;
707221345Sdim    ExprResult Result(ParseSimpleAsm(&EndLoc));
708193326Sed
709193326Sed    ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
710193326Sed                     "top-level asm block");
711193326Sed
712193326Sed    if (Result.isInvalid())
713193326Sed      return DeclGroupPtrTy();
714221345Sdim    SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
715193326Sed    break;
716193326Sed  }
717193326Sed  case tok::at:
718226633Sdim    return ParseObjCAtDirectives();
719193326Sed  case tok::minus:
720193326Sed  case tok::plus:
721234353Sdim    if (!getLangOpts().ObjC1) {
722193326Sed      Diag(Tok, diag::err_expected_external_declaration);
723193326Sed      ConsumeToken();
724193326Sed      return DeclGroupPtrTy();
725193326Sed    }
726193326Sed    SingleDecl = ParseObjCMethodDefinition();
727193326Sed    break;
728198092Srdivacky  case tok::code_completion:
729210299Sed      Actions.CodeCompleteOrdinaryName(getCurScope(),
730234353Sdim                             CurParsedObjCImpl? Sema::PCC_ObjCImplementation
731212904Sdim                                              : Sema::PCC_Namespace);
732226633Sdim    cutOffParsing();
733226633Sdim    return DeclGroupPtrTy();
734193326Sed  case tok::kw_using:
735193326Sed  case tok::kw_namespace:
736193326Sed  case tok::kw_typedef:
737193326Sed  case tok::kw_template:
738193326Sed  case tok::kw_export:    // As in 'export template'
739193326Sed  case tok::kw_static_assert:
740221345Sdim  case tok::kw__Static_assert:
741239462Sdim    // A function definition cannot start with any of these keywords.
742193326Sed    {
743193326Sed      SourceLocation DeclEnd;
744243830Sdim      StmtVector Stmts;
745218893Sdim      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
746193326Sed    }
747212904Sdim
748218893Sdim  case tok::kw_static:
749218893Sdim    // Parse (then ignore) 'static' prior to a template instantiation. This is
750218893Sdim    // a GCC extension that we intentionally do not support.
751234353Sdim    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
752218893Sdim      Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
753218893Sdim        << 0;
754218893Sdim      SourceLocation DeclEnd;
755243830Sdim      StmtVector Stmts;
756218893Sdim      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
757218893Sdim    }
758218893Sdim    goto dont_know;
759218893Sdim
760212904Sdim  case tok::kw_inline:
761234353Sdim    if (getLangOpts().CPlusPlus) {
762218893Sdim      tok::TokenKind NextKind = NextToken().getKind();
763218893Sdim
764212904Sdim      // Inline namespaces. Allowed as an extension even in C++03.
765218893Sdim      if (NextKind == tok::kw_namespace) {
766218893Sdim        SourceLocation DeclEnd;
767243830Sdim        StmtVector Stmts;
768218893Sdim        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
769218893Sdim      }
770218893Sdim
771218893Sdim      // Parse (then ignore) 'inline' prior to a template instantiation. This is
772218893Sdim      // a GCC extension that we intentionally do not support.
773218893Sdim      if (NextKind == tok::kw_template) {
774218893Sdim        Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
775218893Sdim          << 1;
776218893Sdim        SourceLocation DeclEnd;
777243830Sdim        StmtVector Stmts;
778218893Sdim        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
779218893Sdim      }
780212904Sdim    }
781212904Sdim    goto dont_know;
782212904Sdim
783198092Srdivacky  case tok::kw_extern:
784234353Sdim    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
785198092Srdivacky      // Extern templates
786198092Srdivacky      SourceLocation ExternLoc = ConsumeToken();
787198092Srdivacky      SourceLocation TemplateLoc = ConsumeToken();
788249423Sdim      Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
789234353Sdim             diag::warn_cxx98_compat_extern_template :
790234353Sdim             diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
791198092Srdivacky      SourceLocation DeclEnd;
792198092Srdivacky      return Actions.ConvertDeclToDeclGroup(
793234353Sdim                  ParseExplicitInstantiation(Declarator::FileContext,
794234353Sdim                                             ExternLoc, TemplateLoc, DeclEnd));
795198092Srdivacky    }
796198092Srdivacky    // FIXME: Detect C++ linkage specifications here?
797212904Sdim    goto dont_know;
798198092Srdivacky
799223017Sdim  case tok::kw___if_exists:
800223017Sdim  case tok::kw___if_not_exists:
801223017Sdim    ParseMicrosoftIfExistsExternalDeclaration();
802223017Sdim    return DeclGroupPtrTy();
803226633Sdim
804193326Sed  default:
805212904Sdim  dont_know:
806193326Sed    // We can't tell whether this is a function-definition or declaration yet.
807249423Sdim    return ParseDeclarationOrFunctionDefinition(attrs, DS);
808193326Sed  }
809198092Srdivacky
810193326Sed  // This routine returns a DeclGroup, if the thing we parsed only contains a
811193326Sed  // single decl, convert it now.
812193326Sed  return Actions.ConvertDeclToDeclGroup(SingleDecl);
813193326Sed}
814193326Sed
815193326Sed/// \brief Determine whether the current token, if it occurs after a
816193326Sed/// declarator, continues a declaration or declaration list.
817223017Sdimbool Parser::isDeclarationAfterDeclarator() {
818223017Sdim  // Check for '= delete' or '= default'
819234353Sdim  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
820223017Sdim    const Token &KW = NextToken();
821223017Sdim    if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
822223017Sdim      return false;
823223017Sdim  }
824239462Sdim
825193326Sed  return Tok.is(tok::equal) ||      // int X()=  -> not a function def
826193326Sed    Tok.is(tok::comma) ||           // int X(),  -> not a function def
827193326Sed    Tok.is(tok::semi)  ||           // int X();  -> not a function def
828193326Sed    Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
829193326Sed    Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
830234353Sdim    (getLangOpts().CPlusPlus &&
831193326Sed     Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
832193326Sed}
833193326Sed
834193326Sed/// \brief Determine whether the current token, if it occurs after a
835193326Sed/// declarator, indicates the start of a function definition.
836210299Sedbool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
837218893Sdim  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
838200583Srdivacky  if (Tok.is(tok::l_brace))   // int X() {}
839200583Srdivacky    return true;
840200583Srdivacky
841210299Sed  // Handle K&R C argument lists: int X(f) int f; {}
842234353Sdim  if (!getLangOpts().CPlusPlus &&
843218893Sdim      Declarator.getFunctionTypeInfo().isKNRPrototype())
844210299Sed    return isDeclarationSpecifier();
845223017Sdim
846234353Sdim  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
847223017Sdim    const Token &KW = NextToken();
848223017Sdim    return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
849223017Sdim  }
850210299Sed
851200583Srdivacky  return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
852200583Srdivacky         Tok.is(tok::kw_try);          // X() try { ... }
853193326Sed}
854193326Sed
855193326Sed/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
856193326Sed/// a declaration.  We can't tell which we have until we read up to the
857193326Sed/// compound-statement in function-definition. TemplateParams, if
858193326Sed/// non-NULL, provides the template parameters when we're parsing a
859198092Srdivacky/// C++ template-declaration.
860193326Sed///
861193326Sed///       function-definition: [C99 6.9.1]
862193326Sed///         decl-specs      declarator declaration-list[opt] compound-statement
863193326Sed/// [C90] function-definition: [C99 6.7.1] - implicit int result
864193326Sed/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
865193326Sed///
866193326Sed///       declaration: [C99 6.7]
867193326Sed///         declaration-specifiers init-declarator-list[opt] ';'
868193326Sed/// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
869193326Sed/// [OMP]   threadprivate-directive                              [TODO]
870193326Sed///
871193326SedParser::DeclGroupPtrTy
872239462SdimParser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
873239462Sdim                                       ParsingDeclSpec &DS,
874239462Sdim                                       AccessSpecifier AS) {
875193326Sed  // Parse the common declaration-specifiers piece.
876202379Srdivacky  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
877193326Sed
878263508Sdim  // If we had a free-standing type definition with a missing semicolon, we
879263508Sdim  // may get this far before the problem becomes obvious.
880263508Sdim  if (DS.hasTagDefinition() &&
881263508Sdim      DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
882263508Sdim    return DeclGroupPtrTy();
883263508Sdim
884193326Sed  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
885193326Sed  // declaration-specifiers init-declarator-list[opt] ';'
886193326Sed  if (Tok.is(tok::semi)) {
887239462Sdim    ProhibitAttributes(attrs);
888193326Sed    ConsumeToken();
889212904Sdim    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
890198893Srdivacky    DS.complete(TheDecl);
891193326Sed    return Actions.ConvertDeclToDeclGroup(TheDecl);
892193326Sed  }
893193326Sed
894239462Sdim  DS.takeAttributesFrom(attrs);
895239462Sdim
896193326Sed  // ObjC2 allows prefix attributes on class interfaces and protocols.
897193326Sed  // FIXME: This still needs better diagnostics. We should only accept
898193326Sed  // attributes here, no types, etc.
899234353Sdim  if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
900193326Sed    SourceLocation AtLoc = ConsumeToken(); // the "@"
901198092Srdivacky    if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
902193326Sed        !Tok.isObjCAtKeyword(tok::objc_protocol)) {
903193326Sed      Diag(Tok, diag::err_objc_unexpected_attr);
904193326Sed      SkipUntil(tok::semi); // FIXME: better skip?
905193326Sed      return DeclGroupPtrTy();
906193326Sed    }
907198893Srdivacky
908198893Srdivacky    DS.abort();
909198893Srdivacky
910193326Sed    const char *PrevSpec = 0;
911198092Srdivacky    unsigned DiagID;
912198092Srdivacky    if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
913198092Srdivacky      Diag(AtLoc, DiagID) << PrevSpec;
914198092Srdivacky
915193326Sed    if (Tok.isObjCAtKeyword(tok::objc_protocol))
916234353Sdim      return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
917234353Sdim
918234353Sdim    return Actions.ConvertDeclToDeclGroup(
919234353Sdim            ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
920193326Sed  }
921193326Sed
922193326Sed  // If the declspec consisted only of 'extern' and we have a string
923193326Sed  // literal following it, this must be a C++ linkage specifier like
924193326Sed  // 'extern "C"'.
925234353Sdim  if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
926193326Sed      DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
927193326Sed      DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
928212904Sdim    Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
929193326Sed    return Actions.ConvertDeclToDeclGroup(TheDecl);
930193326Sed  }
931193326Sed
932198893Srdivacky  return ParseDeclGroup(DS, Declarator::FileContext, true);
933193326Sed}
934193326Sed
935200583SrdivackyParser::DeclGroupPtrTy
936239462SdimParser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
937239462Sdim                                             ParsingDeclSpec *DS,
938200583Srdivacky                                             AccessSpecifier AS) {
939239462Sdim  if (DS) {
940239462Sdim    return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
941239462Sdim  } else {
942239462Sdim    ParsingDeclSpec PDS(*this);
943239462Sdim    // Must temporarily exit the objective-c container scope for
944239462Sdim    // parsing c constructs and re-enter objc container scope
945239462Sdim    // afterwards.
946239462Sdim    ObjCDeclContextSwitch ObjCDC(*this);
947239462Sdim
948239462Sdim    return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
949239462Sdim  }
950200583Srdivacky}
951200583Srdivacky
952263508Sdim
953263508Sdimstatic inline bool isFunctionDeclaratorRequiringReturnTypeDeduction(
954263508Sdim    const Declarator &D) {
955263508Sdim  if (!D.isFunctionDeclarator() || !D.getDeclSpec().containsPlaceholderType())
956263508Sdim    return false;
957263508Sdim  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
958263508Sdim    unsigned chunkIndex = E - I - 1;
959263508Sdim    const DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
960263508Sdim    if (DeclType.Kind == DeclaratorChunk::Function) {
961263508Sdim      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
962263508Sdim      if (!FTI.hasTrailingReturnType())
963263508Sdim        return true;
964263508Sdim      QualType TrailingRetType = FTI.getTrailingReturnType().get();
965263508Sdim      return TrailingRetType->getCanonicalTypeInternal()
966263508Sdim        ->getContainedAutoType();
967263508Sdim    }
968263508Sdim  }
969263508Sdim  return false;
970263508Sdim}
971263508Sdim
972193326Sed/// ParseFunctionDefinition - We parsed and verified that the specified
973193326Sed/// Declarator is well formed.  If this is a K&R-style function, read the
974193326Sed/// parameters declaration-list, then start the compound-statement.
975193326Sed///
976193326Sed///       function-definition: [C99 6.9.1]
977193326Sed///         decl-specs      declarator declaration-list[opt] compound-statement
978193326Sed/// [C90] function-definition: [C99 6.7.1] - implicit int result
979193326Sed/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
980193326Sed/// [C++] function-definition: [C++ 8.4]
981193326Sed///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
982193326Sed///         function-body
983193326Sed/// [C++] function-definition: [C++ 8.4]
984193326Sed///         decl-specifier-seq[opt] declarator function-try-block
985193326Sed///
986212904SdimDecl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
987234353Sdim                                      const ParsedTemplateInfo &TemplateInfo,
988234353Sdim                                      LateParsedAttrList *LateParsedAttrs) {
989221345Sdim  // Poison the SEH identifiers so they are flagged as illegal in function bodies
990221345Sdim  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
991218893Sdim  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
992193326Sed
993193326Sed  // If this is C90 and the declspecs were completely missing, fudge in an
994193326Sed  // implicit int.  We do this here because this is the only place where
995193326Sed  // declaration-specifiers are completely optional in the grammar.
996234353Sdim  if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
997193326Sed    const char *PrevSpec;
998198092Srdivacky    unsigned DiagID;
999193326Sed    D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1000193326Sed                                           D.getIdentifierLoc(),
1001198092Srdivacky                                           PrevSpec, DiagID);
1002193326Sed    D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1003193326Sed  }
1004193326Sed
1005193326Sed  // If this declaration was formed with a K&R-style identifier list for the
1006193326Sed  // arguments, parse declarations for all of the args next.
1007193326Sed  // int foo(a,b) int a; float b; {}
1008210299Sed  if (FTI.isKNRPrototype())
1009193326Sed    ParseKNRParamDeclarations(D);
1010193326Sed
1011193326Sed  // We should have either an opening brace or, in a C++ constructor,
1012193326Sed  // we may have a colon.
1013218893Sdim  if (Tok.isNot(tok::l_brace) &&
1014234353Sdim      (!getLangOpts().CPlusPlus ||
1015223017Sdim       (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1016223017Sdim        Tok.isNot(tok::equal)))) {
1017193326Sed    Diag(Tok, diag::err_expected_fn_body);
1018193326Sed
1019193326Sed    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1020263508Sdim    SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1021193326Sed
1022193326Sed    // If we didn't find the '{', bail out.
1023193326Sed    if (Tok.isNot(tok::l_brace))
1024212904Sdim      return 0;
1025193326Sed  }
1026193326Sed
1027234353Sdim  // Check to make sure that any normal attributes are allowed to be on
1028234353Sdim  // a definition.  Late parsed attributes are checked at the end.
1029234353Sdim  if (Tok.isNot(tok::equal)) {
1030234353Sdim    AttributeList *DtorAttrs = D.getAttributes();
1031234353Sdim    while (DtorAttrs) {
1032249423Sdim      if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName()) &&
1033249423Sdim          !DtorAttrs->isCXX11Attribute()) {
1034234353Sdim        Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
1035234353Sdim          << DtorAttrs->getName()->getName();
1036234353Sdim      }
1037234353Sdim      DtorAttrs = DtorAttrs->getNext();
1038234353Sdim    }
1039234353Sdim  }
1040234353Sdim
1041221345Sdim  // In delayed template parsing mode, for function template we consume the
1042221345Sdim  // tokens and store them for late parsing at the end of the translation unit.
1043263508Sdim  if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1044263508Sdim      TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1045263508Sdim      !D.getDeclSpec().isConstexprSpecified() &&
1046263508Sdim      !isFunctionDeclaratorRequiringReturnTypeDeduction(D)) {
1047243830Sdim    MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1048221345Sdim
1049221345Sdim    ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1050221345Sdim    Scope *ParentScope = getCurScope()->getParent();
1051221345Sdim
1052234353Sdim    D.setFunctionDefinitionKind(FDK_Definition);
1053221345Sdim    Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1054243830Sdim                                        TemplateParameterLists);
1055221345Sdim    D.complete(DP);
1056221345Sdim    D.getMutableDeclSpec().abort();
1057221345Sdim
1058263508Sdim    CachedTokens Toks;
1059263508Sdim    LexTemplateFunctionForLateParsing(Toks);
1060263508Sdim
1061221345Sdim    if (DP) {
1062221345Sdim      FunctionDecl *FnD = 0;
1063221345Sdim      if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1064221345Sdim        FnD = FunTmpl->getTemplatedDecl();
1065221345Sdim      else
1066221345Sdim        FnD = cast<FunctionDecl>(DP);
1067263508Sdim
1068221345Sdim      Actions.CheckForFunctionRedefinition(FnD);
1069263508Sdim      Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1070221345Sdim    }
1071221345Sdim    return DP;
1072221345Sdim  }
1073239462Sdim  else if (CurParsedObjCImpl &&
1074239462Sdim           !TemplateInfo.TemplateParams &&
1075239462Sdim           (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1076239462Sdim            Tok.is(tok::colon)) &&
1077239462Sdim      Actions.CurContext->isTranslationUnit()) {
1078239462Sdim    ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1079239462Sdim    Scope *ParentScope = getCurScope()->getParent();
1080239462Sdim
1081239462Sdim    D.setFunctionDefinitionKind(FDK_Definition);
1082239462Sdim    Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1083243830Sdim                                              MultiTemplateParamsArg());
1084239462Sdim    D.complete(FuncDecl);
1085239462Sdim    D.getMutableDeclSpec().abort();
1086239462Sdim    if (FuncDecl) {
1087239462Sdim      // Consume the tokens and store them for later parsing.
1088239462Sdim      StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1089239462Sdim      CurParsedObjCImpl->HasCFunction = true;
1090239462Sdim      return FuncDecl;
1091239462Sdim    }
1092239462Sdim  }
1093239462Sdim
1094193326Sed  // Enter a scope for the function body.
1095193326Sed  ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1096193326Sed
1097193326Sed  // Tell the actions module that we have entered a function definition with the
1098193326Sed  // specified Declarator for the function.
1099212904Sdim  Decl *Res = TemplateInfo.TemplateParams?
1100210299Sed      Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1101243830Sdim                                              *TemplateInfo.TemplateParams, D)
1102210299Sed    : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1103193326Sed
1104198893Srdivacky  // Break out of the ParsingDeclarator context before we parse the body.
1105198893Srdivacky  D.complete(Res);
1106198893Srdivacky
1107198893Srdivacky  // Break out of the ParsingDeclSpec context, too.  This const_cast is
1108198893Srdivacky  // safe because we're always the sole owner.
1109198893Srdivacky  D.getMutableDeclSpec().abort();
1110198893Srdivacky
1111223017Sdim  if (Tok.is(tok::equal)) {
1112234353Sdim    assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1113223017Sdim    ConsumeToken();
1114223017Sdim
1115223017Sdim    Actions.ActOnFinishFunctionBody(Res, 0, false);
1116223017Sdim
1117223017Sdim    bool Delete = false;
1118223017Sdim    SourceLocation KWLoc;
1119223017Sdim    if (Tok.is(tok::kw_delete)) {
1120249423Sdim      Diag(Tok, getLangOpts().CPlusPlus11 ?
1121234353Sdim           diag::warn_cxx98_compat_deleted_function :
1122234353Sdim           diag::ext_deleted_function);
1123223017Sdim
1124223017Sdim      KWLoc = ConsumeToken();
1125223017Sdim      Actions.SetDeclDeleted(Res, KWLoc);
1126223017Sdim      Delete = true;
1127223017Sdim    } else if (Tok.is(tok::kw_default)) {
1128249423Sdim      Diag(Tok, getLangOpts().CPlusPlus11 ?
1129234353Sdim           diag::warn_cxx98_compat_defaulted_function :
1130234353Sdim           diag::ext_defaulted_function);
1131223017Sdim
1132223017Sdim      KWLoc = ConsumeToken();
1133223017Sdim      Actions.SetDeclDefaulted(Res, KWLoc);
1134223017Sdim    } else {
1135223017Sdim      llvm_unreachable("function definition after = not 'delete' or 'default'");
1136223017Sdim    }
1137223017Sdim
1138223017Sdim    if (Tok.is(tok::comma)) {
1139223017Sdim      Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1140223017Sdim        << Delete;
1141223017Sdim      SkipUntil(tok::semi);
1142223017Sdim    } else {
1143223017Sdim      ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1144223017Sdim                       Delete ? "delete" : "default", tok::semi);
1145223017Sdim    }
1146223017Sdim
1147223017Sdim    return Res;
1148223017Sdim  }
1149223017Sdim
1150193326Sed  if (Tok.is(tok::kw_try))
1151221345Sdim    return ParseFunctionTryBlock(Res, BodyScope);
1152193326Sed
1153193326Sed  // If we have a colon, then we're probably parsing a C++
1154193326Sed  // ctor-initializer.
1155207619Srdivacky  if (Tok.is(tok::colon)) {
1156193326Sed    ParseConstructorInitializer(Res);
1157207619Srdivacky
1158207619Srdivacky    // Recover from error.
1159207619Srdivacky    if (!Tok.is(tok::l_brace)) {
1160221345Sdim      BodyScope.Exit();
1161212904Sdim      Actions.ActOnFinishFunctionBody(Res, 0);
1162207619Srdivacky      return Res;
1163207619Srdivacky    }
1164207619Srdivacky  } else
1165198092Srdivacky    Actions.ActOnDefaultCtorInitializers(Res);
1166193326Sed
1167234353Sdim  // Late attributes are parsed in the same scope as the function body.
1168234353Sdim  if (LateParsedAttrs)
1169234353Sdim    ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1170234353Sdim
1171221345Sdim  return ParseFunctionStatementBody(Res, BodyScope);
1172193326Sed}
1173193326Sed
1174193326Sed/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1175193326Sed/// types for a function with a K&R-style identifier list for arguments.
1176193326Sedvoid Parser::ParseKNRParamDeclarations(Declarator &D) {
1177193326Sed  // We know that the top-level of this declarator is a function.
1178218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1179193326Sed
1180193326Sed  // Enter function-declaration scope, limiting any declarators to the
1181193326Sed  // function prototype scope, including parameter declarators.
1182249423Sdim  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1183249423Sdim                            Scope::FunctionDeclarationScope | Scope::DeclScope);
1184193326Sed
1185193326Sed  // Read all the argument declarations.
1186193326Sed  while (isDeclarationSpecifier()) {
1187193326Sed    SourceLocation DSStart = Tok.getLocation();
1188193326Sed
1189193326Sed    // Parse the common declaration-specifiers piece.
1190221345Sdim    DeclSpec DS(AttrFactory);
1191193326Sed    ParseDeclarationSpecifiers(DS);
1192193326Sed
1193193326Sed    // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1194193326Sed    // least one declarator'.
1195193326Sed    // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1196193326Sed    // the declarations though.  It's trivial to ignore them, really hard to do
1197193326Sed    // anything else with them.
1198193326Sed    if (Tok.is(tok::semi)) {
1199193326Sed      Diag(DSStart, diag::err_declaration_does_not_declare_param);
1200193326Sed      ConsumeToken();
1201193326Sed      continue;
1202193326Sed    }
1203193326Sed
1204193326Sed    // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1205193326Sed    // than register.
1206193326Sed    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1207193326Sed        DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1208193326Sed      Diag(DS.getStorageClassSpecLoc(),
1209193326Sed           diag::err_invalid_storage_class_in_func_decl);
1210193326Sed      DS.ClearStorageClassSpecs();
1211193326Sed    }
1212251662Sdim    if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1213251662Sdim      Diag(DS.getThreadStorageClassSpecLoc(),
1214193326Sed           diag::err_invalid_storage_class_in_func_decl);
1215193326Sed      DS.ClearStorageClassSpecs();
1216193326Sed    }
1217193326Sed
1218193326Sed    // Parse the first declarator attached to this declspec.
1219193326Sed    Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1220193326Sed    ParseDeclarator(ParmDeclarator);
1221193326Sed
1222193326Sed    // Handle the full declarator list.
1223193326Sed    while (1) {
1224193326Sed      // If attributes are present, parse them.
1225218893Sdim      MaybeParseGNUAttributes(ParmDeclarator);
1226193326Sed
1227193326Sed      // Ask the actions module to compute the type for this declarator.
1228212904Sdim      Decl *Param =
1229210299Sed        Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1230193326Sed
1231193326Sed      if (Param &&
1232193326Sed          // A missing identifier has already been diagnosed.
1233193326Sed          ParmDeclarator.getIdentifier()) {
1234193326Sed
1235193326Sed        // Scan the argument list looking for the correct param to apply this
1236193326Sed        // type.
1237193326Sed        for (unsigned i = 0; ; ++i) {
1238193326Sed          // C99 6.9.1p6: those declarators shall declare only identifiers from
1239193326Sed          // the identifier list.
1240193326Sed          if (i == FTI.NumArgs) {
1241193326Sed            Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1242193326Sed              << ParmDeclarator.getIdentifier();
1243193326Sed            break;
1244193326Sed          }
1245193326Sed
1246193326Sed          if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1247193326Sed            // Reject redefinitions of parameters.
1248193326Sed            if (FTI.ArgInfo[i].Param) {
1249193326Sed              Diag(ParmDeclarator.getIdentifierLoc(),
1250193326Sed                   diag::err_param_redefinition)
1251193326Sed                 << ParmDeclarator.getIdentifier();
1252193326Sed            } else {
1253193326Sed              FTI.ArgInfo[i].Param = Param;
1254193326Sed            }
1255193326Sed            break;
1256193326Sed          }
1257193326Sed        }
1258193326Sed      }
1259193326Sed
1260193326Sed      // If we don't have a comma, it is either the end of the list (a ';') or
1261193326Sed      // an error, bail out.
1262193326Sed      if (Tok.isNot(tok::comma))
1263193326Sed        break;
1264193326Sed
1265234353Sdim      ParmDeclarator.clear();
1266234353Sdim
1267193326Sed      // Consume the comma.
1268234353Sdim      ParmDeclarator.setCommaLoc(ConsumeToken());
1269193326Sed
1270193326Sed      // Parse the next declarator.
1271193326Sed      ParseDeclarator(ParmDeclarator);
1272193326Sed    }
1273193326Sed
1274239462Sdim    if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1275193326Sed      // Skip to end of block or statement
1276263508Sdim      SkipUntil(tok::semi);
1277193326Sed      if (Tok.is(tok::semi))
1278193326Sed        ConsumeToken();
1279193326Sed    }
1280193326Sed  }
1281193326Sed
1282193326Sed  // The actions module must verify that all arguments were declared.
1283210299Sed  Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1284193326Sed}
1285193326Sed
1286193326Sed
1287193326Sed/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1288193326Sed/// allowed to be a wide string, and is not subject to character translation.
1289193326Sed///
1290193326Sed/// [GNU] asm-string-literal:
1291193326Sed///         string-literal
1292193326Sed///
1293212904SdimParser::ExprResult Parser::ParseAsmStringLiteral() {
1294234353Sdim  switch (Tok.getKind()) {
1295234353Sdim    case tok::string_literal:
1296234353Sdim      break;
1297234353Sdim    case tok::utf8_string_literal:
1298234353Sdim    case tok::utf16_string_literal:
1299234353Sdim    case tok::utf32_string_literal:
1300234353Sdim    case tok::wide_string_literal: {
1301234353Sdim      SourceLocation L = Tok.getLocation();
1302234353Sdim      Diag(Tok, diag::err_asm_operand_wide_string_literal)
1303234353Sdim        << (Tok.getKind() == tok::wide_string_literal)
1304234353Sdim        << SourceRange(L, L);
1305234353Sdim      return ExprError();
1306234353Sdim    }
1307234353Sdim    default:
1308249423Sdim      Diag(Tok, diag::err_expected_string_literal)
1309249423Sdim        << /*Source='in...'*/0 << "'asm'";
1310234353Sdim      return ExprError();
1311193326Sed  }
1312193326Sed
1313234353Sdim  return ParseStringLiteralExpression();
1314193326Sed}
1315193326Sed
1316193326Sed/// ParseSimpleAsm
1317193326Sed///
1318193326Sed/// [GNU] simple-asm-expr:
1319193326Sed///         'asm' '(' asm-string-literal ')'
1320193326Sed///
1321212904SdimParser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1322193326Sed  assert(Tok.is(tok::kw_asm) && "Not an asm!");
1323193326Sed  SourceLocation Loc = ConsumeToken();
1324193326Sed
1325203955Srdivacky  if (Tok.is(tok::kw_volatile)) {
1326203955Srdivacky    // Remove from the end of 'asm' to the end of 'volatile'.
1327203955Srdivacky    SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1328203955Srdivacky                             PP.getLocForEndOfToken(Tok.getLocation()));
1329203955Srdivacky
1330203955Srdivacky    Diag(Tok, diag::warn_file_asm_volatile)
1331206084Srdivacky      << FixItHint::CreateRemoval(RemovalRange);
1332203955Srdivacky    ConsumeToken();
1333203955Srdivacky  }
1334203955Srdivacky
1335226633Sdim  BalancedDelimiterTracker T(*this, tok::l_paren);
1336226633Sdim  if (T.consumeOpen()) {
1337193326Sed    Diag(Tok, diag::err_expected_lparen_after) << "asm";
1338193326Sed    return ExprError();
1339193326Sed  }
1340193326Sed
1341212904Sdim  ExprResult Result(ParseAsmStringLiteral());
1342193326Sed
1343193326Sed  if (Result.isInvalid()) {
1344263508Sdim    SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1345193326Sed    if (EndLoc)
1346193326Sed      *EndLoc = Tok.getLocation();
1347193326Sed    ConsumeAnyToken();
1348193326Sed  } else {
1349226633Sdim    // Close the paren and get the location of the end bracket
1350226633Sdim    T.consumeClose();
1351193326Sed    if (EndLoc)
1352226633Sdim      *EndLoc = T.getCloseLocation();
1353193326Sed  }
1354193326Sed
1355243830Sdim  return Result;
1356193326Sed}
1357193326Sed
1358224145Sdim/// \brief Get the TemplateIdAnnotation from the token and put it in the
1359224145Sdim/// cleanup pool so that it gets destroyed when parsing the current top level
1360224145Sdim/// declaration is finished.
1361224145SdimTemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1362224145Sdim  assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1363224145Sdim  TemplateIdAnnotation *
1364224145Sdim      Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1365224145Sdim  return Id;
1366224145Sdim}
1367224145Sdim
1368243830Sdimvoid Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1369243830Sdim  // Push the current token back into the token stream (or revert it if it is
1370243830Sdim  // cached) and use an annotation scope token for current token.
1371243830Sdim  if (PP.isBacktrackEnabled())
1372243830Sdim    PP.RevertCachedTokens(1);
1373243830Sdim  else
1374243830Sdim    PP.EnterToken(Tok);
1375243830Sdim  Tok.setKind(tok::annot_cxxscope);
1376243830Sdim  Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1377243830Sdim  Tok.setAnnotationRange(SS.getRange());
1378243830Sdim
1379243830Sdim  // In case the tokens were cached, have Preprocessor replace them
1380243830Sdim  // with the annotation token.  We don't need to do this if we've
1381243830Sdim  // just reverted back to a prior state.
1382243830Sdim  if (IsNewAnnotation)
1383243830Sdim    PP.AnnotateCachedTokens(Tok);
1384243830Sdim}
1385243830Sdim
1386243830Sdim/// \brief Attempt to classify the name at the current token position. This may
1387243830Sdim/// form a type, scope or primary expression annotation, or replace the token
1388243830Sdim/// with a typo-corrected keyword. This is only appropriate when the current
1389243830Sdim/// name must refer to an entity which has already been declared.
1390243830Sdim///
1391243830Sdim/// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1392243830Sdim///        and might possibly have a dependent nested name specifier.
1393243830Sdim/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1394243830Sdim///        no typo correction will be performed.
1395243830SdimParser::AnnotatedNameKind
1396243830SdimParser::TryAnnotateName(bool IsAddressOfOperand,
1397243830Sdim                        CorrectionCandidateCallback *CCC) {
1398243830Sdim  assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1399243830Sdim
1400243830Sdim  const bool EnteringContext = false;
1401243830Sdim  const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1402243830Sdim
1403243830Sdim  CXXScopeSpec SS;
1404243830Sdim  if (getLangOpts().CPlusPlus &&
1405243830Sdim      ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1406243830Sdim    return ANK_Error;
1407243830Sdim
1408243830Sdim  if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1409243830Sdim    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1410243830Sdim                                                  !WasScopeAnnotation))
1411243830Sdim      return ANK_Error;
1412243830Sdim    return ANK_Unresolved;
1413243830Sdim  }
1414243830Sdim
1415243830Sdim  IdentifierInfo *Name = Tok.getIdentifierInfo();
1416243830Sdim  SourceLocation NameLoc = Tok.getLocation();
1417243830Sdim
1418243830Sdim  // FIXME: Move the tentative declaration logic into ClassifyName so we can
1419243830Sdim  // typo-correct to tentatively-declared identifiers.
1420243830Sdim  if (isTentativelyDeclared(Name)) {
1421243830Sdim    // Identifier has been tentatively declared, and thus cannot be resolved as
1422243830Sdim    // an expression. Fall back to annotating it as a type.
1423243830Sdim    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1424243830Sdim                                                  !WasScopeAnnotation))
1425243830Sdim      return ANK_Error;
1426243830Sdim    return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1427243830Sdim  }
1428243830Sdim
1429243830Sdim  Token Next = NextToken();
1430243830Sdim
1431243830Sdim  // Look up and classify the identifier. We don't perform any typo-correction
1432243830Sdim  // after a scope specifier, because in general we can't recover from typos
1433243830Sdim  // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1434243830Sdim  // back into scope specifier parsing).
1435243830Sdim  Sema::NameClassification Classification
1436243830Sdim    = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1437243830Sdim                           IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1438243830Sdim
1439243830Sdim  switch (Classification.getKind()) {
1440243830Sdim  case Sema::NC_Error:
1441243830Sdim    return ANK_Error;
1442243830Sdim
1443243830Sdim  case Sema::NC_Keyword:
1444243830Sdim    // The identifier was typo-corrected to a keyword.
1445243830Sdim    Tok.setIdentifierInfo(Name);
1446243830Sdim    Tok.setKind(Name->getTokenID());
1447243830Sdim    PP.TypoCorrectToken(Tok);
1448243830Sdim    if (SS.isNotEmpty())
1449243830Sdim      AnnotateScopeToken(SS, !WasScopeAnnotation);
1450243830Sdim    // We've "annotated" this as a keyword.
1451243830Sdim    return ANK_Success;
1452243830Sdim
1453243830Sdim  case Sema::NC_Unknown:
1454243830Sdim    // It's not something we know about. Leave it unannotated.
1455243830Sdim    break;
1456243830Sdim
1457243830Sdim  case Sema::NC_Type:
1458243830Sdim    Tok.setKind(tok::annot_typename);
1459243830Sdim    setTypeAnnotation(Tok, Classification.getType());
1460243830Sdim    Tok.setAnnotationEndLoc(NameLoc);
1461243830Sdim    if (SS.isNotEmpty())
1462243830Sdim      Tok.setLocation(SS.getBeginLoc());
1463243830Sdim    PP.AnnotateCachedTokens(Tok);
1464243830Sdim    return ANK_Success;
1465243830Sdim
1466243830Sdim  case Sema::NC_Expression:
1467243830Sdim    Tok.setKind(tok::annot_primary_expr);
1468243830Sdim    setExprAnnotation(Tok, Classification.getExpression());
1469243830Sdim    Tok.setAnnotationEndLoc(NameLoc);
1470243830Sdim    if (SS.isNotEmpty())
1471243830Sdim      Tok.setLocation(SS.getBeginLoc());
1472243830Sdim    PP.AnnotateCachedTokens(Tok);
1473243830Sdim    return ANK_Success;
1474243830Sdim
1475243830Sdim  case Sema::NC_TypeTemplate:
1476243830Sdim    if (Next.isNot(tok::less)) {
1477243830Sdim      // This may be a type template being used as a template template argument.
1478243830Sdim      if (SS.isNotEmpty())
1479243830Sdim        AnnotateScopeToken(SS, !WasScopeAnnotation);
1480243830Sdim      return ANK_TemplateName;
1481243830Sdim    }
1482243830Sdim    // Fall through.
1483263508Sdim  case Sema::NC_VarTemplate:
1484243830Sdim  case Sema::NC_FunctionTemplate: {
1485263508Sdim    // We have a type, variable or function template followed by '<'.
1486243830Sdim    ConsumeToken();
1487243830Sdim    UnqualifiedId Id;
1488243830Sdim    Id.setIdentifier(Name, NameLoc);
1489243830Sdim    if (AnnotateTemplateIdToken(
1490243830Sdim            TemplateTy::make(Classification.getTemplateName()),
1491243830Sdim            Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1492243830Sdim      return ANK_Error;
1493243830Sdim    return ANK_Success;
1494243830Sdim  }
1495243830Sdim
1496243830Sdim  case Sema::NC_NestedNameSpecifier:
1497243830Sdim    llvm_unreachable("already parsed nested name specifier");
1498243830Sdim  }
1499243830Sdim
1500243830Sdim  // Unable to classify the name, but maybe we can annotate a scope specifier.
1501243830Sdim  if (SS.isNotEmpty())
1502243830Sdim    AnnotateScopeToken(SS, !WasScopeAnnotation);
1503243830Sdim  return ANK_Unresolved;
1504243830Sdim}
1505243830Sdim
1506263508Sdimbool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1507263508Sdim  assert(Tok.isNot(tok::identifier));
1508263508Sdim  Diag(Tok, diag::ext_keyword_as_ident)
1509263508Sdim    << PP.getSpelling(Tok)
1510263508Sdim    << DisableKeyword;
1511263508Sdim  if (DisableKeyword)
1512263508Sdim    Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1513263508Sdim  Tok.setKind(tok::identifier);
1514263508Sdim  return true;
1515263508Sdim}
1516263508Sdim
1517193326Sed/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1518193326Sed/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1519193326Sed/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1520193326Sed/// with a single annotation token representing the typename or C++ scope
1521193326Sed/// respectively.
1522193326Sed/// This simplifies handling of C++ scope specifiers and allows efficient
1523193326Sed/// backtracking without the need to re-parse and resolve nested-names and
1524193326Sed/// typenames.
1525193326Sed/// It will mainly be called when we expect to treat identifiers as typenames
1526193326Sed/// (if they are typenames). For example, in C we do not expect identifiers
1527193326Sed/// inside expressions to be treated as typenames so it will not be called
1528193326Sed/// for expressions in C.
1529193326Sed/// The benefit for C/ObjC is that a typename will be annotated and
1530193326Sed/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1531193326Sed/// will not be called twice, once to check whether we have a declaration
1532193326Sed/// specifier, and another one to get the actual type inside
1533193326Sed/// ParseDeclarationSpecifiers).
1534193326Sed///
1535204643Srdivacky/// This returns true if an error occurred.
1536198092Srdivacky///
1537193326Sed/// Note that this routine emits an error if you call it with ::new or ::delete
1538193326Sed/// as the current tokens, so only call it in contexts where these are invalid.
1539226633Sdimbool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1540198092Srdivacky  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1541234353Sdim          || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1542239462Sdim          || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1543239462Sdim          && "Cannot be a type or scope token!");
1544198092Srdivacky
1545193326Sed  if (Tok.is(tok::kw_typename)) {
1546263508Sdim    // MSVC lets you do stuff like:
1547263508Sdim    //   typename typedef T_::D D;
1548263508Sdim    //
1549263508Sdim    // We will consume the typedef token here and put it back after we have
1550263508Sdim    // parsed the first identifier, transforming it into something more like:
1551263508Sdim    //   typename T_::D typedef D;
1552263508Sdim    if (getLangOpts().MicrosoftMode && NextToken().is(tok::kw_typedef)) {
1553263508Sdim      Token TypedefToken;
1554263508Sdim      PP.Lex(TypedefToken);
1555263508Sdim      bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
1556263508Sdim      PP.EnterToken(Tok);
1557263508Sdim      Tok = TypedefToken;
1558263508Sdim      if (!Result)
1559263508Sdim        Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1560263508Sdim      return Result;
1561263508Sdim    }
1562263508Sdim
1563193326Sed    // Parse a C++ typename-specifier, e.g., "typename T::type".
1564193326Sed    //
1565193326Sed    //   typename-specifier:
1566193326Sed    //     'typename' '::' [opt] nested-name-specifier identifier
1567198092Srdivacky    //     'typename' '::' [opt] nested-name-specifier template [opt]
1568193326Sed    //            simple-template-id
1569193326Sed    SourceLocation TypenameLoc = ConsumeToken();
1570193326Sed    CXXScopeSpec SS;
1571234353Sdim    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1572234353Sdim                                       /*EnteringContext=*/false,
1573221345Sdim                                       0, /*IsTypename*/true))
1574204643Srdivacky      return true;
1575204643Srdivacky    if (!SS.isSet()) {
1576239462Sdim      if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1577239462Sdim          Tok.is(tok::annot_decltype)) {
1578239462Sdim        // Attempt to recover by skipping the invalid 'typename'
1579239462Sdim        if (Tok.is(tok::annot_decltype) ||
1580239462Sdim            (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1581263508Sdim             Tok.isAnnotation())) {
1582239462Sdim          unsigned DiagID = diag::err_expected_qualified_after_typename;
1583239462Sdim          // MS compatibility: MSVC permits using known types with typename.
1584239462Sdim          // e.g. "typedef typename T* pointer_type"
1585239462Sdim          if (getLangOpts().MicrosoftExt)
1586239462Sdim            DiagID = diag::warn_expected_qualified_after_typename;
1587239462Sdim          Diag(Tok.getLocation(), DiagID);
1588239462Sdim          return false;
1589239462Sdim        }
1590239462Sdim      }
1591239462Sdim
1592239462Sdim      Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1593204643Srdivacky      return true;
1594193326Sed    }
1595193326Sed
1596193326Sed    TypeResult Ty;
1597193326Sed    if (Tok.is(tok::identifier)) {
1598193326Sed      // FIXME: check whether the next token is '<', first!
1599210299Sed      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1600210299Sed                                     *Tok.getIdentifierInfo(),
1601193326Sed                                     Tok.getLocation());
1602193326Sed    } else if (Tok.is(tok::annot_template_id)) {
1603224145Sdim      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1604193326Sed      if (TemplateId->Kind == TNK_Function_template) {
1605193326Sed        Diag(Tok, diag::err_typename_refers_to_non_type_template)
1606193326Sed          << Tok.getAnnotationRange();
1607204643Srdivacky        return true;
1608193326Sed      }
1609193326Sed
1610243830Sdim      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1611221345Sdim                                         TemplateId->NumArgs);
1612234353Sdim
1613221345Sdim      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1614234353Sdim                                     TemplateId->TemplateKWLoc,
1615221345Sdim                                     TemplateId->Template,
1616221345Sdim                                     TemplateId->TemplateNameLoc,
1617221345Sdim                                     TemplateId->LAngleLoc,
1618234353Sdim                                     TemplateArgsPtr,
1619221345Sdim                                     TemplateId->RAngleLoc);
1620193326Sed    } else {
1621193326Sed      Diag(Tok, diag::err_expected_type_name_after_typename)
1622193326Sed        << SS.getRange();
1623204643Srdivacky      return true;
1624193326Sed    }
1625193326Sed
1626203955Srdivacky    SourceLocation EndLoc = Tok.getLastLoc();
1627193326Sed    Tok.setKind(tok::annot_typename);
1628212904Sdim    setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1629203955Srdivacky    Tok.setAnnotationEndLoc(EndLoc);
1630193326Sed    Tok.setLocation(TypenameLoc);
1631193326Sed    PP.AnnotateCachedTokens(Tok);
1632204643Srdivacky    return false;
1633193326Sed  }
1634193326Sed
1635201361Srdivacky  // Remembers whether the token was originally a scope annotation.
1636243830Sdim  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1637201361Srdivacky
1638193326Sed  CXXScopeSpec SS;
1639234353Sdim  if (getLangOpts().CPlusPlus)
1640212904Sdim    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1641204643Srdivacky      return true;
1642193326Sed
1643243830Sdim  return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1644243830Sdim                                                   SS, !WasScopeAnnotation);
1645243830Sdim}
1646243830Sdim
1647243830Sdim/// \brief Try to annotate a type or scope token, having already parsed an
1648243830Sdim/// optional scope specifier. \p IsNewScope should be \c true unless the scope
1649243830Sdim/// specifier was extracted from an existing tok::annot_cxxscope annotation.
1650243830Sdimbool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1651243830Sdim                                                       bool NeedType,
1652243830Sdim                                                       CXXScopeSpec &SS,
1653243830Sdim                                                       bool IsNewScope) {
1654193326Sed  if (Tok.is(tok::identifier)) {
1655226633Sdim    IdentifierInfo *CorrectedII = 0;
1656193326Sed    // Determine whether the identifier is a type name.
1657212904Sdim    if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1658212904Sdim                                            Tok.getLocation(), getCurScope(),
1659218893Sdim                                            &SS, false,
1660221345Sdim                                            NextToken().is(tok::period),
1661221345Sdim                                            ParsedType(),
1662234353Sdim                                            /*IsCtorOrDtorName=*/false,
1663226633Sdim                                            /*NonTrivialTypeSourceInfo*/true,
1664226633Sdim                                            NeedType ? &CorrectedII : NULL)) {
1665226633Sdim      // A FixIt was applied as a result of typo correction
1666226633Sdim      if (CorrectedII)
1667226633Sdim        Tok.setIdentifierInfo(CorrectedII);
1668193326Sed      // This is a typename. Replace the current token in-place with an
1669193326Sed      // annotation type token.
1670193326Sed      Tok.setKind(tok::annot_typename);
1671212904Sdim      setTypeAnnotation(Tok, Ty);
1672193326Sed      Tok.setAnnotationEndLoc(Tok.getLocation());
1673193326Sed      if (SS.isNotEmpty()) // it was a C++ qualified type name.
1674193326Sed        Tok.setLocation(SS.getBeginLoc());
1675198092Srdivacky
1676193326Sed      // In case the tokens were cached, have Preprocessor replace
1677193326Sed      // them with the annotation token.
1678193326Sed      PP.AnnotateCachedTokens(Tok);
1679204643Srdivacky      return false;
1680198092Srdivacky    }
1681193326Sed
1682234353Sdim    if (!getLangOpts().CPlusPlus) {
1683193326Sed      // If we're in C, we can't have :: tokens at all (the lexer won't return
1684193326Sed      // them).  If the identifier is not a type, then it can't be scope either,
1685198092Srdivacky      // just early exit.
1686193326Sed      return false;
1687193326Sed    }
1688198092Srdivacky
1689193326Sed    // If this is a template-id, annotate with a template-id or type token.
1690193326Sed    if (NextToken().is(tok::less)) {
1691193326Sed      TemplateTy Template;
1692198893Srdivacky      UnqualifiedId TemplateName;
1693198893Srdivacky      TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1694208600Srdivacky      bool MemberOfUnknownSpecialization;
1695198092Srdivacky      if (TemplateNameKind TNK
1696212904Sdim          = Actions.isTemplateName(getCurScope(), SS,
1697212904Sdim                                   /*hasTemplateKeyword=*/false, TemplateName,
1698212904Sdim                                   /*ObjectType=*/ ParsedType(),
1699212904Sdim                                   EnteringContext,
1700212904Sdim                                   Template, MemberOfUnknownSpecialization)) {
1701198893Srdivacky        // Consume the identifier.
1702198893Srdivacky        ConsumeToken();
1703234353Sdim        if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1704234353Sdim                                    TemplateName)) {
1705195099Sed          // If an unrecoverable error occurred, we need to return true here,
1706195099Sed          // because the token stream is in a damaged state.  We may not return
1707195099Sed          // a valid identifier.
1708204643Srdivacky          return true;
1709195099Sed        }
1710198893Srdivacky      }
1711193326Sed    }
1712193326Sed
1713193326Sed    // The current token, which is either an identifier or a
1714193326Sed    // template-id, is not part of the annotation. Fall through to
1715193326Sed    // push that token back into the stream and complete the C++ scope
1716193326Sed    // specifier annotation.
1717198092Srdivacky  }
1718193326Sed
1719193326Sed  if (Tok.is(tok::annot_template_id)) {
1720224145Sdim    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1721193326Sed    if (TemplateId->Kind == TNK_Type_template) {
1722193326Sed      // A template-id that refers to a type was parsed into a
1723193326Sed      // template-id annotation in a context where we weren't allowed
1724193326Sed      // to produce a type annotation token. Update the template-id
1725193326Sed      // annotation token to a type annotation token now.
1726221345Sdim      AnnotateTemplateIdTokenAsType();
1727204643Srdivacky      return false;
1728263508Sdim    } else if (TemplateId->Kind == TNK_Var_template)
1729263508Sdim      return false;
1730193326Sed  }
1731193326Sed
1732193326Sed  if (SS.isEmpty())
1733204643Srdivacky    return false;
1734198092Srdivacky
1735193326Sed  // A C++ scope specifier that isn't followed by a typename.
1736243830Sdim  AnnotateScopeToken(SS, IsNewScope);
1737204643Srdivacky  return false;
1738193326Sed}
1739193326Sed
1740193326Sed/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1741193326Sed/// annotates C++ scope specifiers and template-ids.  This returns
1742239462Sdim/// true if there was an error that could not be recovered from.
1743198092Srdivacky///
1744193326Sed/// Note that this routine emits an error if you call it with ::new or ::delete
1745193326Sed/// as the current tokens, so only call it in contexts where these are invalid.
1746198092Srdivackybool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1747234353Sdim  assert(getLangOpts().CPlusPlus &&
1748193326Sed         "Call sites of this function should be guarded by checking for C++");
1749221345Sdim  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1750234353Sdim          (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1751234353Sdim         Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1752193326Sed
1753193326Sed  CXXScopeSpec SS;
1754212904Sdim  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1755204643Srdivacky    return true;
1756207619Srdivacky  if (SS.isEmpty())
1757204643Srdivacky    return false;
1758193326Sed
1759243830Sdim  AnnotateScopeToken(SS, true);
1760204643Srdivacky  return false;
1761193326Sed}
1762198893Srdivacky
1763234353Sdimbool Parser::isTokenEqualOrEqualTypo() {
1764234353Sdim  tok::TokenKind Kind = Tok.getKind();
1765234353Sdim  switch (Kind) {
1766234353Sdim  default:
1767234353Sdim    return false;
1768234353Sdim  case tok::ampequal:            // &=
1769234353Sdim  case tok::starequal:           // *=
1770234353Sdim  case tok::plusequal:           // +=
1771234353Sdim  case tok::minusequal:          // -=
1772234353Sdim  case tok::exclaimequal:        // !=
1773234353Sdim  case tok::slashequal:          // /=
1774234353Sdim  case tok::percentequal:        // %=
1775234353Sdim  case tok::lessequal:           // <=
1776234353Sdim  case tok::lesslessequal:       // <<=
1777234353Sdim  case tok::greaterequal:        // >=
1778234353Sdim  case tok::greatergreaterequal: // >>=
1779234353Sdim  case tok::caretequal:          // ^=
1780234353Sdim  case tok::pipeequal:           // |=
1781234353Sdim  case tok::equalequal:          // ==
1782234353Sdim    Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1783234353Sdim      << getTokenSimpleSpelling(Kind)
1784234353Sdim      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1785234353Sdim  case tok::equal:
1786218893Sdim    return true;
1787218893Sdim  }
1788218893Sdim}
1789218893Sdim
1790226633SdimSourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1791226633Sdim  assert(Tok.is(tok::code_completion));
1792226633Sdim  PrevTokLocation = Tok.getLocation();
1793226633Sdim
1794210299Sed  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1795208600Srdivacky    if (S->getFlags() & Scope::FnScope) {
1796212904Sdim      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1797226633Sdim      cutOffParsing();
1798226633Sdim      return PrevTokLocation;
1799208600Srdivacky    }
1800208600Srdivacky
1801208600Srdivacky    if (S->getFlags() & Scope::ClassScope) {
1802212904Sdim      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1803226633Sdim      cutOffParsing();
1804226633Sdim      return PrevTokLocation;
1805208600Srdivacky    }
1806208600Srdivacky  }
1807208600Srdivacky
1808212904Sdim  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1809226633Sdim  cutOffParsing();
1810226633Sdim  return PrevTokLocation;
1811208600Srdivacky}
1812208600Srdivacky
1813198893Srdivacky// Anchor the Parser::FieldCallback vtable to this translation unit.
1814198893Srdivacky// We use a spurious method instead of the destructor because
1815198893Srdivacky// destroying FieldCallbacks can actually be slightly
1816198893Srdivacky// performance-sensitive.
1817198893Srdivackyvoid Parser::FieldCallback::_anchor() {
1818198893Srdivacky}
1819212904Sdim
1820212904Sdim// Code-completion pass-through functions
1821212904Sdim
1822212904Sdimvoid Parser::CodeCompleteDirective(bool InConditional) {
1823212904Sdim  Actions.CodeCompletePreprocessorDirective(InConditional);
1824212904Sdim}
1825212904Sdim
1826212904Sdimvoid Parser::CodeCompleteInConditionalExclusion() {
1827212904Sdim  Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1828212904Sdim}
1829212904Sdim
1830212904Sdimvoid Parser::CodeCompleteMacroName(bool IsDefinition) {
1831212904Sdim  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1832212904Sdim}
1833212904Sdim
1834212904Sdimvoid Parser::CodeCompletePreprocessorExpression() {
1835212904Sdim  Actions.CodeCompletePreprocessorExpression();
1836212904Sdim}
1837212904Sdim
1838212904Sdimvoid Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1839212904Sdim                                       MacroInfo *MacroInfo,
1840212904Sdim                                       unsigned ArgumentIndex) {
1841212904Sdim  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1842212904Sdim                                                ArgumentIndex);
1843212904Sdim}
1844212904Sdim
1845212904Sdimvoid Parser::CodeCompleteNaturalLanguage() {
1846212904Sdim  Actions.CodeCompleteNaturalLanguage();
1847212904Sdim}
1848223017Sdim
1849234353Sdimbool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1850223017Sdim  assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1851223017Sdim         "Expected '__if_exists' or '__if_not_exists'");
1852234353Sdim  Result.IsIfExists = Tok.is(tok::kw___if_exists);
1853234353Sdim  Result.KeywordLoc = ConsumeToken();
1854223017Sdim
1855226633Sdim  BalancedDelimiterTracker T(*this, tok::l_paren);
1856226633Sdim  if (T.consumeOpen()) {
1857234353Sdim    Diag(Tok, diag::err_expected_lparen_after)
1858234353Sdim      << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1859223017Sdim    return true;
1860223017Sdim  }
1861223017Sdim
1862223017Sdim  // Parse nested-name-specifier.
1863234353Sdim  ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1864234353Sdim                                 /*EnteringContext=*/false);
1865223017Sdim
1866223017Sdim  // Check nested-name specifier.
1867234353Sdim  if (Result.SS.isInvalid()) {
1868234353Sdim    T.skipToEnd();
1869223017Sdim    return true;
1870223017Sdim  }
1871223017Sdim
1872234353Sdim  // Parse the unqualified-id.
1873234353Sdim  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1874234353Sdim  if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1875234353Sdim                         TemplateKWLoc, Result.Name)) {
1876234353Sdim    T.skipToEnd();
1877223017Sdim    return true;
1878223017Sdim  }
1879223017Sdim
1880234353Sdim  if (T.consumeClose())
1881223017Sdim    return true;
1882234353Sdim
1883223017Sdim  // Check if the symbol exists.
1884234353Sdim  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1885234353Sdim                                               Result.IsIfExists, Result.SS,
1886234353Sdim                                               Result.Name)) {
1887234353Sdim  case Sema::IER_Exists:
1888234353Sdim    Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1889234353Sdim    break;
1890223017Sdim
1891234353Sdim  case Sema::IER_DoesNotExist:
1892234353Sdim    Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1893234353Sdim    break;
1894223017Sdim
1895234353Sdim  case Sema::IER_Dependent:
1896234353Sdim    Result.Behavior = IEB_Dependent;
1897234353Sdim    break;
1898234353Sdim
1899234353Sdim  case Sema::IER_Error:
1900234353Sdim    return true;
1901234353Sdim  }
1902234353Sdim
1903223017Sdim  return false;
1904223017Sdim}
1905223017Sdim
1906223017Sdimvoid Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1907234353Sdim  IfExistsCondition Result;
1908223017Sdim  if (ParseMicrosoftIfExistsCondition(Result))
1909223017Sdim    return;
1910223017Sdim
1911234353Sdim  BalancedDelimiterTracker Braces(*this, tok::l_brace);
1912234353Sdim  if (Braces.consumeOpen()) {
1913223017Sdim    Diag(Tok, diag::err_expected_lbrace);
1914223017Sdim    return;
1915223017Sdim  }
1916223017Sdim
1917234353Sdim  switch (Result.Behavior) {
1918234353Sdim  case IEB_Parse:
1919234353Sdim    // Parse declarations below.
1920234353Sdim    break;
1921234353Sdim
1922234353Sdim  case IEB_Dependent:
1923234353Sdim    llvm_unreachable("Cannot have a dependent external declaration");
1924234353Sdim
1925234353Sdim  case IEB_Skip:
1926234353Sdim    Braces.skipToEnd();
1927223017Sdim    return;
1928223017Sdim  }
1929223017Sdim
1930234353Sdim  // Parse the declarations.
1931234353Sdim  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1932223017Sdim    ParsedAttributesWithRange attrs(AttrFactory);
1933249423Sdim    MaybeParseCXX11Attributes(attrs);
1934223017Sdim    MaybeParseMicrosoftAttributes(attrs);
1935223017Sdim    DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1936223017Sdim    if (Result && !getCurScope()->getParent())
1937223017Sdim      Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1938234353Sdim  }
1939234353Sdim  Braces.consumeClose();
1940223017Sdim}
1941226633Sdim
1942234353SdimParser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1943249423Sdim  assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1944226633Sdim         "Improper start to module import");
1945226633Sdim  SourceLocation ImportLoc = ConsumeToken();
1946226633Sdim
1947249423Sdim  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1948226633Sdim
1949234353Sdim  // Parse the module path.
1950234353Sdim  do {
1951234353Sdim    if (!Tok.is(tok::identifier)) {
1952234353Sdim      if (Tok.is(tok::code_completion)) {
1953234353Sdim        Actions.CodeCompleteModuleImport(ImportLoc, Path);
1954234353Sdim        ConsumeCodeCompletionToken();
1955234353Sdim        SkipUntil(tok::semi);
1956234353Sdim        return DeclGroupPtrTy();
1957234353Sdim      }
1958234353Sdim
1959234353Sdim      Diag(Tok, diag::err_module_expected_ident);
1960234353Sdim      SkipUntil(tok::semi);
1961234353Sdim      return DeclGroupPtrTy();
1962234353Sdim    }
1963234353Sdim
1964234353Sdim    // Record this part of the module path.
1965234353Sdim    Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1966234353Sdim    ConsumeToken();
1967234353Sdim
1968234353Sdim    if (Tok.is(tok::period)) {
1969234353Sdim      ConsumeToken();
1970234353Sdim      continue;
1971234353Sdim    }
1972234353Sdim
1973234353Sdim    break;
1974234353Sdim  } while (true);
1975263508Sdim
1976263508Sdim  if (PP.hadModuleLoaderFatalFailure()) {
1977263508Sdim    // With a fatal failure in the module loader, we abort parsing.
1978263508Sdim    cutOffParsing();
1979263508Sdim    return DeclGroupPtrTy();
1980263508Sdim  }
1981263508Sdim
1982234353Sdim  DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1983226633Sdim  ExpectAndConsumeSemi(diag::err_module_expected_semi);
1984226633Sdim  if (Import.isInvalid())
1985226633Sdim    return DeclGroupPtrTy();
1986226633Sdim
1987226633Sdim  return Actions.ConvertDeclToDeclGroup(Import.get());
1988226633Sdim}
1989226633Sdim
1990239462Sdimbool BalancedDelimiterTracker::diagnoseOverflow() {
1991249423Sdim  P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1992249423Sdim    << P.getLangOpts().BracketDepth;
1993249423Sdim  P.Diag(P.Tok, diag::note_bracket_depth);
1994234353Sdim  P.SkipUntil(tok::eof);
1995234353Sdim  return true;
1996226633Sdim}
1997226633Sdim
1998239462Sdimbool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1999226633Sdim                                            const char *Msg,
2000226633Sdim                                            tok::TokenKind SkipToToc ) {
2001226633Sdim  LOpen = P.Tok.getLocation();
2002234353Sdim  if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
2003234353Sdim    return true;
2004234353Sdim
2005234353Sdim  if (getDepth() < MaxDepth)
2006234353Sdim    return false;
2007234353Sdim
2008234353Sdim  return diagnoseOverflow();
2009226633Sdim}
2010226633Sdim
2011239462Sdimbool BalancedDelimiterTracker::diagnoseMissingClose() {
2012234353Sdim  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2013234353Sdim
2014234353Sdim  const char *LHSName = "unknown";
2015234353Sdim  diag::kind DID;
2016234353Sdim  switch (Close) {
2017234353Sdim  default: llvm_unreachable("Unexpected balanced token");
2018234353Sdim  case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
2019234353Sdim  case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
2020234353Sdim  case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
2021226633Sdim  }
2022234353Sdim  P.Diag(P.Tok, DID);
2023234353Sdim  P.Diag(LOpen, diag::note_matching) << LHSName;
2024263508Sdim
2025263508Sdim  // If we're not already at some kind of closing bracket, skip to our closing
2026263508Sdim  // token.
2027263508Sdim  if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2028263508Sdim      P.Tok.isNot(tok::r_square) &&
2029263508Sdim      P.SkipUntil(Close, FinalToken,
2030263508Sdim                  Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2031263508Sdim      P.Tok.is(Close))
2032243830Sdim    LClose = P.ConsumeAnyToken();
2033226633Sdim  return true;
2034226633Sdim}
2035234353Sdim
2036239462Sdimvoid BalancedDelimiterTracker::skipToEnd() {
2037263508Sdim  P.SkipUntil(Close, Parser::StopBeforeMatch);
2038263508Sdim  consumeClose();
2039234353Sdim}
2040