1//===--- Parser.cpp - C Language Family Parser ----------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "ParsePragma.h"
16#include "RAIIObjectsForParser.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
22#include "clang/Sema/Scope.h"
23#include "llvm/Support/raw_ostream.h"
24using namespace clang;
25
26
27namespace {
28/// \brief A comment handler that passes comments found by the preprocessor
29/// to the parser action.
30class ActionCommentHandler : public CommentHandler {
31  Sema &S;
32
33public:
34  explicit ActionCommentHandler(Sema &S) : S(S) { }
35
36  virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37    S.ActOnComment(Comment);
38    return false;
39  }
40};
41} // end anonymous namespace
42
43IdentifierInfo *Parser::getSEHExceptKeyword() {
44  // __except is accepted as a (contextual) keyword
45  if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46    Ident__except = PP.getIdentifierInfo("__except");
47
48  return Ident__except;
49}
50
51Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52  : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53    GreaterThanIsOperator(true), ColonIsSacred(false),
54    InMessageExpression(false), TemplateParameterDepth(0),
55    ParsingInObjCContainer(false) {
56  SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57  Tok.startToken();
58  Tok.setKind(tok::eof);
59  Actions.CurScope = 0;
60  NumCachedScopes = 0;
61  ParenCount = BracketCount = BraceCount = 0;
62  CurParsedObjCImpl = 0;
63
64  // Add #pragma handlers. These are removed and destroyed in the
65  // destructor.
66  AlignHandler.reset(new PragmaAlignHandler());
67  PP.AddPragmaHandler(AlignHandler.get());
68
69  GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
70  PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
71
72  OptionsHandler.reset(new PragmaOptionsHandler());
73  PP.AddPragmaHandler(OptionsHandler.get());
74
75  PackHandler.reset(new PragmaPackHandler());
76  PP.AddPragmaHandler(PackHandler.get());
77
78  MSStructHandler.reset(new PragmaMSStructHandler());
79  PP.AddPragmaHandler(MSStructHandler.get());
80
81  UnusedHandler.reset(new PragmaUnusedHandler());
82  PP.AddPragmaHandler(UnusedHandler.get());
83
84  WeakHandler.reset(new PragmaWeakHandler());
85  PP.AddPragmaHandler(WeakHandler.get());
86
87  RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
88  PP.AddPragmaHandler(RedefineExtnameHandler.get());
89
90  FPContractHandler.reset(new PragmaFPContractHandler());
91  PP.AddPragmaHandler("STDC", FPContractHandler.get());
92
93  if (getLangOpts().OpenCL) {
94    OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
95    PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
96
97    PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
98  }
99
100  CommentSemaHandler.reset(new ActionCommentHandler(actions));
101  PP.addCommentHandler(CommentSemaHandler.get());
102
103  PP.setCodeCompletionHandler(*this);
104}
105
106DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
107  return Diags.Report(Loc, DiagID);
108}
109
110DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
111  return Diag(Tok.getLocation(), DiagID);
112}
113
114/// \brief Emits a diagnostic suggesting parentheses surrounding a
115/// given range.
116///
117/// \param Loc The location where we'll emit the diagnostic.
118/// \param DK The kind of diagnostic to emit.
119/// \param ParenRange Source range enclosing code that should be parenthesized.
120void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
121                                SourceRange ParenRange) {
122  SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
123  if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
124    // We can't display the parentheses, so just dig the
125    // warning/error and return.
126    Diag(Loc, DK);
127    return;
128  }
129
130  Diag(Loc, DK)
131    << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
132    << FixItHint::CreateInsertion(EndLoc, ")");
133}
134
135static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
136  switch (ExpectedTok) {
137  case tok::semi:
138    return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
139  default: return false;
140  }
141}
142
143/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
144/// input.  If so, it is consumed and false is returned.
145///
146/// If the input is malformed, this emits the specified diagnostic.  Next, if
147/// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
148/// returned.
149bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
150                              const char *Msg, tok::TokenKind SkipToTok) {
151  if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
152    ConsumeAnyToken();
153    return false;
154  }
155
156  // Detect common single-character typos and resume.
157  if (IsCommonTypo(ExpectedTok, Tok)) {
158    SourceLocation Loc = Tok.getLocation();
159    Diag(Loc, DiagID)
160      << Msg
161      << FixItHint::CreateReplacement(SourceRange(Loc),
162                                      getTokenSimpleSpelling(ExpectedTok));
163    ConsumeAnyToken();
164
165    // Pretend there wasn't a problem.
166    return false;
167  }
168
169  const char *Spelling = 0;
170  SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
171  if (EndLoc.isValid() &&
172      (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
173    // Show what code to insert to fix this problem.
174    Diag(EndLoc, DiagID)
175      << Msg
176      << FixItHint::CreateInsertion(EndLoc, Spelling);
177  } else
178    Diag(Tok, DiagID) << Msg;
179
180  if (SkipToTok != tok::unknown)
181    SkipUntil(SkipToTok);
182  return true;
183}
184
185bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
186  if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
187    ConsumeToken();
188    return false;
189  }
190
191  if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
192      NextToken().is(tok::semi)) {
193    Diag(Tok, diag::err_extraneous_token_before_semi)
194      << PP.getSpelling(Tok)
195      << FixItHint::CreateRemoval(Tok.getLocation());
196    ConsumeAnyToken(); // The ')' or ']'.
197    ConsumeToken(); // The ';'.
198    return false;
199  }
200
201  return ExpectAndConsume(tok::semi, DiagID);
202}
203
204void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
205  if (!Tok.is(tok::semi)) return;
206
207  bool HadMultipleSemis = false;
208  SourceLocation StartLoc = Tok.getLocation();
209  SourceLocation EndLoc = Tok.getLocation();
210  ConsumeToken();
211
212  while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
213    HadMultipleSemis = true;
214    EndLoc = Tok.getLocation();
215    ConsumeToken();
216  }
217
218  // C++11 allows extra semicolons at namespace scope, but not in any of the
219  // other contexts.
220  if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
221    if (getLangOpts().CPlusPlus11)
222      Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
223          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
224    else
225      Diag(StartLoc, diag::ext_extra_semi_cxx11)
226          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
227    return;
228  }
229
230  if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
231    Diag(StartLoc, diag::ext_extra_semi)
232        << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
233        << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
234  else
235    // A single semicolon is valid after a member function definition.
236    Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
237      << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
238}
239
240//===----------------------------------------------------------------------===//
241// Error recovery.
242//===----------------------------------------------------------------------===//
243
244/// SkipUntil - Read tokens until we get to the specified token, then consume
245/// it (unless DontConsume is true).  Because we cannot guarantee that the
246/// token will ever occur, this skips to the next token, or to some likely
247/// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
248/// character.
249///
250/// If SkipUntil finds the specified token, it returns true, otherwise it
251/// returns false.
252bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
253                       bool DontConsume, bool StopAtCodeCompletion) {
254  // We always want this function to skip at least one token if the first token
255  // isn't T and if not at EOF.
256  bool isFirstTokenSkipped = true;
257  while (1) {
258    // If we found one of the tokens, stop and return true.
259    for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
260      if (Tok.is(Toks[i])) {
261        if (DontConsume) {
262          // Noop, don't consume the token.
263        } else {
264          ConsumeAnyToken();
265        }
266        return true;
267      }
268    }
269
270    switch (Tok.getKind()) {
271    case tok::eof:
272      // Ran out of tokens.
273      return false;
274
275    case tok::code_completion:
276      if (!StopAtCodeCompletion)
277        ConsumeToken();
278      return false;
279
280    case tok::l_paren:
281      // Recursively skip properly-nested parens.
282      ConsumeParen();
283      SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
284      break;
285    case tok::l_square:
286      // Recursively skip properly-nested square brackets.
287      ConsumeBracket();
288      SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
289      break;
290    case tok::l_brace:
291      // Recursively skip properly-nested braces.
292      ConsumeBrace();
293      SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
294      break;
295
296    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
297    // Since the user wasn't looking for this token (if they were, it would
298    // already be handled), this isn't balanced.  If there is a LHS token at a
299    // higher level, we will assume that this matches the unbalanced token
300    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
301    case tok::r_paren:
302      if (ParenCount && !isFirstTokenSkipped)
303        return false;  // Matches something.
304      ConsumeParen();
305      break;
306    case tok::r_square:
307      if (BracketCount && !isFirstTokenSkipped)
308        return false;  // Matches something.
309      ConsumeBracket();
310      break;
311    case tok::r_brace:
312      if (BraceCount && !isFirstTokenSkipped)
313        return false;  // Matches something.
314      ConsumeBrace();
315      break;
316
317    case tok::string_literal:
318    case tok::wide_string_literal:
319    case tok::utf8_string_literal:
320    case tok::utf16_string_literal:
321    case tok::utf32_string_literal:
322      ConsumeStringToken();
323      break;
324
325    case tok::semi:
326      if (StopAtSemi)
327        return false;
328      // FALL THROUGH.
329    default:
330      // Skip this token.
331      ConsumeToken();
332      break;
333    }
334    isFirstTokenSkipped = false;
335  }
336}
337
338//===----------------------------------------------------------------------===//
339// Scope manipulation
340//===----------------------------------------------------------------------===//
341
342/// EnterScope - Start a new scope.
343void Parser::EnterScope(unsigned ScopeFlags) {
344  if (NumCachedScopes) {
345    Scope *N = ScopeCache[--NumCachedScopes];
346    N->Init(getCurScope(), ScopeFlags);
347    Actions.CurScope = N;
348  } else {
349    Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
350  }
351}
352
353/// ExitScope - Pop a scope off the scope stack.
354void Parser::ExitScope() {
355  assert(getCurScope() && "Scope imbalance!");
356
357  // Inform the actions module that this scope is going away if there are any
358  // decls in it.
359  if (!getCurScope()->decl_empty())
360    Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
361
362  Scope *OldScope = getCurScope();
363  Actions.CurScope = OldScope->getParent();
364
365  if (NumCachedScopes == ScopeCacheSize)
366    delete OldScope;
367  else
368    ScopeCache[NumCachedScopes++] = OldScope;
369}
370
371/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
372/// this object does nothing.
373Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
374                                 bool ManageFlags)
375  : CurScope(ManageFlags ? Self->getCurScope() : 0) {
376  if (CurScope) {
377    OldFlags = CurScope->getFlags();
378    CurScope->setFlags(ScopeFlags);
379  }
380}
381
382/// Restore the flags for the current scope to what they were before this
383/// object overrode them.
384Parser::ParseScopeFlags::~ParseScopeFlags() {
385  if (CurScope)
386    CurScope->setFlags(OldFlags);
387}
388
389
390//===----------------------------------------------------------------------===//
391// C99 6.9: External Definitions.
392//===----------------------------------------------------------------------===//
393
394Parser::~Parser() {
395  // If we still have scopes active, delete the scope tree.
396  delete getCurScope();
397  Actions.CurScope = 0;
398
399  // Free the scope cache.
400  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
401    delete ScopeCache[i];
402
403  // Free LateParsedTemplatedFunction nodes.
404  for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
405      it != LateParsedTemplateMap.end(); ++it)
406    delete it->second;
407
408  // Remove the pragma handlers we installed.
409  PP.RemovePragmaHandler(AlignHandler.get());
410  AlignHandler.reset();
411  PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
412  GCCVisibilityHandler.reset();
413  PP.RemovePragmaHandler(OptionsHandler.get());
414  OptionsHandler.reset();
415  PP.RemovePragmaHandler(PackHandler.get());
416  PackHandler.reset();
417  PP.RemovePragmaHandler(MSStructHandler.get());
418  MSStructHandler.reset();
419  PP.RemovePragmaHandler(UnusedHandler.get());
420  UnusedHandler.reset();
421  PP.RemovePragmaHandler(WeakHandler.get());
422  WeakHandler.reset();
423  PP.RemovePragmaHandler(RedefineExtnameHandler.get());
424  RedefineExtnameHandler.reset();
425
426  if (getLangOpts().OpenCL) {
427    PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
428    OpenCLExtensionHandler.reset();
429    PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
430  }
431
432  PP.RemovePragmaHandler("STDC", FPContractHandler.get());
433  FPContractHandler.reset();
434
435  PP.removeCommentHandler(CommentSemaHandler.get());
436
437  PP.clearCodeCompletionHandler();
438
439  assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
440}
441
442/// Initialize - Warm up the parser.
443///
444void Parser::Initialize() {
445  // Create the translation unit scope.  Install it as the current scope.
446  assert(getCurScope() == 0 && "A scope is already active?");
447  EnterScope(Scope::DeclScope);
448  Actions.ActOnTranslationUnitScope(getCurScope());
449
450  // Initialization for Objective-C context sensitive keywords recognition.
451  // Referenced in Parser::ParseObjCTypeQualifierList.
452  if (getLangOpts().ObjC1) {
453    ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
454    ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
455    ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
456    ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
457    ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
458    ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
459  }
460
461  Ident_instancetype = 0;
462  Ident_final = 0;
463  Ident_override = 0;
464
465  Ident_super = &PP.getIdentifierTable().get("super");
466
467  if (getLangOpts().AltiVec) {
468    Ident_vector = &PP.getIdentifierTable().get("vector");
469    Ident_pixel = &PP.getIdentifierTable().get("pixel");
470  }
471
472  Ident_introduced = 0;
473  Ident_deprecated = 0;
474  Ident_obsoleted = 0;
475  Ident_unavailable = 0;
476
477  Ident__except = 0;
478
479  Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
480  Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
481  Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
482
483  if(getLangOpts().Borland) {
484    Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
485    Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
486    Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
487    Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
488    Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
489    Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
490    Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
491    Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
492    Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
493
494    PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
495    PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
496    PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
497    PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
498    PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
499    PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
500    PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
501    PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
502    PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
503  }
504
505  Actions.Initialize();
506
507  // Prime the lexer look-ahead.
508  ConsumeToken();
509}
510
511namespace {
512  /// \brief RAIIObject to destroy the contents of a SmallVector of
513  /// TemplateIdAnnotation pointers and clear the vector.
514  class DestroyTemplateIdAnnotationsRAIIObj {
515    SmallVectorImpl<TemplateIdAnnotation *> &Container;
516  public:
517    DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
518                                       &Container)
519      : Container(Container) {}
520
521    ~DestroyTemplateIdAnnotationsRAIIObj() {
522      for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
523           Container.begin(), E = Container.end();
524           I != E; ++I)
525        (*I)->Destroy();
526      Container.clear();
527    }
528  };
529}
530
531/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
532/// action tells us to.  This returns true if the EOF was encountered.
533bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
534  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
535
536  // Skip over the EOF token, flagging end of previous input for incremental
537  // processing
538  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
539    ConsumeToken();
540
541  while (Tok.is(tok::annot_pragma_unused))
542    HandlePragmaUnused();
543
544  Result = DeclGroupPtrTy();
545  if (Tok.is(tok::eof)) {
546    // Late template parsing can begin.
547    if (getLangOpts().DelayedTemplateParsing)
548      Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
549    if (!PP.isIncrementalProcessingEnabled())
550      Actions.ActOnEndOfTranslationUnit();
551    //else don't tell Sema that we ended parsing: more input might come.
552
553    return true;
554  }
555
556  ParsedAttributesWithRange attrs(AttrFactory);
557  MaybeParseCXX11Attributes(attrs);
558  MaybeParseMicrosoftAttributes(attrs);
559
560  Result = ParseExternalDeclaration(attrs);
561  return false;
562}
563
564/// ParseExternalDeclaration:
565///
566///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
567///         function-definition
568///         declaration
569/// [GNU]   asm-definition
570/// [GNU]   __extension__ external-declaration
571/// [OBJC]  objc-class-definition
572/// [OBJC]  objc-class-declaration
573/// [OBJC]  objc-alias-declaration
574/// [OBJC]  objc-protocol-definition
575/// [OBJC]  objc-method-definition
576/// [OBJC]  @end
577/// [C++]   linkage-specification
578/// [GNU] asm-definition:
579///         simple-asm-expr ';'
580/// [C++11] empty-declaration
581/// [C++11] attribute-declaration
582///
583/// [C++11] empty-declaration:
584///           ';'
585///
586/// [C++0x/GNU] 'extern' 'template' declaration
587Parser::DeclGroupPtrTy
588Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
589                                 ParsingDeclSpec *DS) {
590  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
591  ParenBraceBracketBalancer BalancerRAIIObj(*this);
592
593  if (PP.isCodeCompletionReached()) {
594    cutOffParsing();
595    return DeclGroupPtrTy();
596  }
597
598  Decl *SingleDecl = 0;
599  switch (Tok.getKind()) {
600  case tok::annot_pragma_vis:
601    HandlePragmaVisibility();
602    return DeclGroupPtrTy();
603  case tok::annot_pragma_pack:
604    HandlePragmaPack();
605    return DeclGroupPtrTy();
606  case tok::annot_pragma_msstruct:
607    HandlePragmaMSStruct();
608    return DeclGroupPtrTy();
609  case tok::annot_pragma_align:
610    HandlePragmaAlign();
611    return DeclGroupPtrTy();
612  case tok::annot_pragma_weak:
613    HandlePragmaWeak();
614    return DeclGroupPtrTy();
615  case tok::annot_pragma_weakalias:
616    HandlePragmaWeakAlias();
617    return DeclGroupPtrTy();
618  case tok::annot_pragma_redefine_extname:
619    HandlePragmaRedefineExtname();
620    return DeclGroupPtrTy();
621  case tok::annot_pragma_fp_contract:
622    HandlePragmaFPContract();
623    return DeclGroupPtrTy();
624  case tok::annot_pragma_opencl_extension:
625    HandlePragmaOpenCLExtension();
626    return DeclGroupPtrTy();
627  case tok::semi:
628    // Either a C++11 empty-declaration or attribute-declaration.
629    SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
630                                               attrs.getList(),
631                                               Tok.getLocation());
632    ConsumeExtraSemi(OutsideFunction);
633    break;
634  case tok::r_brace:
635    Diag(Tok, diag::err_extraneous_closing_brace);
636    ConsumeBrace();
637    return DeclGroupPtrTy();
638  case tok::eof:
639    Diag(Tok, diag::err_expected_external_declaration);
640    return DeclGroupPtrTy();
641  case tok::kw___extension__: {
642    // __extension__ silences extension warnings in the subexpression.
643    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
644    ConsumeToken();
645    return ParseExternalDeclaration(attrs);
646  }
647  case tok::kw_asm: {
648    ProhibitAttributes(attrs);
649
650    SourceLocation StartLoc = Tok.getLocation();
651    SourceLocation EndLoc;
652    ExprResult Result(ParseSimpleAsm(&EndLoc));
653
654    ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
655                     "top-level asm block");
656
657    if (Result.isInvalid())
658      return DeclGroupPtrTy();
659    SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
660    break;
661  }
662  case tok::at:
663    return ParseObjCAtDirectives();
664  case tok::minus:
665  case tok::plus:
666    if (!getLangOpts().ObjC1) {
667      Diag(Tok, diag::err_expected_external_declaration);
668      ConsumeToken();
669      return DeclGroupPtrTy();
670    }
671    SingleDecl = ParseObjCMethodDefinition();
672    break;
673  case tok::code_completion:
674      Actions.CodeCompleteOrdinaryName(getCurScope(),
675                             CurParsedObjCImpl? Sema::PCC_ObjCImplementation
676                                              : Sema::PCC_Namespace);
677    cutOffParsing();
678    return DeclGroupPtrTy();
679  case tok::kw_using:
680  case tok::kw_namespace:
681  case tok::kw_typedef:
682  case tok::kw_template:
683  case tok::kw_export:    // As in 'export template'
684  case tok::kw_static_assert:
685  case tok::kw__Static_assert:
686    // A function definition cannot start with any of these keywords.
687    {
688      SourceLocation DeclEnd;
689      StmtVector Stmts;
690      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
691    }
692
693  case tok::kw_static:
694    // Parse (then ignore) 'static' prior to a template instantiation. This is
695    // a GCC extension that we intentionally do not support.
696    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
697      Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
698        << 0;
699      SourceLocation DeclEnd;
700      StmtVector Stmts;
701      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
702    }
703    goto dont_know;
704
705  case tok::kw_inline:
706    if (getLangOpts().CPlusPlus) {
707      tok::TokenKind NextKind = NextToken().getKind();
708
709      // Inline namespaces. Allowed as an extension even in C++03.
710      if (NextKind == tok::kw_namespace) {
711        SourceLocation DeclEnd;
712        StmtVector Stmts;
713        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
714      }
715
716      // Parse (then ignore) 'inline' prior to a template instantiation. This is
717      // a GCC extension that we intentionally do not support.
718      if (NextKind == tok::kw_template) {
719        Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
720          << 1;
721        SourceLocation DeclEnd;
722        StmtVector Stmts;
723        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
724      }
725    }
726    goto dont_know;
727
728  case tok::kw_extern:
729    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
730      // Extern templates
731      SourceLocation ExternLoc = ConsumeToken();
732      SourceLocation TemplateLoc = ConsumeToken();
733      Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
734             diag::warn_cxx98_compat_extern_template :
735             diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
736      SourceLocation DeclEnd;
737      return Actions.ConvertDeclToDeclGroup(
738                  ParseExplicitInstantiation(Declarator::FileContext,
739                                             ExternLoc, TemplateLoc, DeclEnd));
740    }
741    // FIXME: Detect C++ linkage specifications here?
742    goto dont_know;
743
744  case tok::kw___if_exists:
745  case tok::kw___if_not_exists:
746    ParseMicrosoftIfExistsExternalDeclaration();
747    return DeclGroupPtrTy();
748
749  default:
750  dont_know:
751    // We can't tell whether this is a function-definition or declaration yet.
752    return ParseDeclarationOrFunctionDefinition(attrs, DS);
753  }
754
755  // This routine returns a DeclGroup, if the thing we parsed only contains a
756  // single decl, convert it now.
757  return Actions.ConvertDeclToDeclGroup(SingleDecl);
758}
759
760/// \brief Determine whether the current token, if it occurs after a
761/// declarator, continues a declaration or declaration list.
762bool Parser::isDeclarationAfterDeclarator() {
763  // Check for '= delete' or '= default'
764  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
765    const Token &KW = NextToken();
766    if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
767      return false;
768  }
769
770  return Tok.is(tok::equal) ||      // int X()=  -> not a function def
771    Tok.is(tok::comma) ||           // int X(),  -> not a function def
772    Tok.is(tok::semi)  ||           // int X();  -> not a function def
773    Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
774    Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
775    (getLangOpts().CPlusPlus &&
776     Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
777}
778
779/// \brief Determine whether the current token, if it occurs after a
780/// declarator, indicates the start of a function definition.
781bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
782  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
783  if (Tok.is(tok::l_brace))   // int X() {}
784    return true;
785
786  // Handle K&R C argument lists: int X(f) int f; {}
787  if (!getLangOpts().CPlusPlus &&
788      Declarator.getFunctionTypeInfo().isKNRPrototype())
789    return isDeclarationSpecifier();
790
791  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
792    const Token &KW = NextToken();
793    return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
794  }
795
796  return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
797         Tok.is(tok::kw_try);          // X() try { ... }
798}
799
800/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
801/// a declaration.  We can't tell which we have until we read up to the
802/// compound-statement in function-definition. TemplateParams, if
803/// non-NULL, provides the template parameters when we're parsing a
804/// C++ template-declaration.
805///
806///       function-definition: [C99 6.9.1]
807///         decl-specs      declarator declaration-list[opt] compound-statement
808/// [C90] function-definition: [C99 6.7.1] - implicit int result
809/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
810///
811///       declaration: [C99 6.7]
812///         declaration-specifiers init-declarator-list[opt] ';'
813/// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
814/// [OMP]   threadprivate-directive                              [TODO]
815///
816Parser::DeclGroupPtrTy
817Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
818                                       ParsingDeclSpec &DS,
819                                       AccessSpecifier AS) {
820  // Parse the common declaration-specifiers piece.
821  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
822
823  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
824  // declaration-specifiers init-declarator-list[opt] ';'
825  if (Tok.is(tok::semi)) {
826    ProhibitAttributes(attrs);
827    ConsumeToken();
828    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
829    DS.complete(TheDecl);
830    return Actions.ConvertDeclToDeclGroup(TheDecl);
831  }
832
833  DS.takeAttributesFrom(attrs);
834
835  // ObjC2 allows prefix attributes on class interfaces and protocols.
836  // FIXME: This still needs better diagnostics. We should only accept
837  // attributes here, no types, etc.
838  if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
839    SourceLocation AtLoc = ConsumeToken(); // the "@"
840    if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
841        !Tok.isObjCAtKeyword(tok::objc_protocol)) {
842      Diag(Tok, diag::err_objc_unexpected_attr);
843      SkipUntil(tok::semi); // FIXME: better skip?
844      return DeclGroupPtrTy();
845    }
846
847    DS.abort();
848
849    const char *PrevSpec = 0;
850    unsigned DiagID;
851    if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
852      Diag(AtLoc, DiagID) << PrevSpec;
853
854    if (Tok.isObjCAtKeyword(tok::objc_protocol))
855      return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
856
857    return Actions.ConvertDeclToDeclGroup(
858            ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
859  }
860
861  // If the declspec consisted only of 'extern' and we have a string
862  // literal following it, this must be a C++ linkage specifier like
863  // 'extern "C"'.
864  if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
865      DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
866      DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
867    Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
868    return Actions.ConvertDeclToDeclGroup(TheDecl);
869  }
870
871  return ParseDeclGroup(DS, Declarator::FileContext, true);
872}
873
874Parser::DeclGroupPtrTy
875Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
876                                             ParsingDeclSpec *DS,
877                                             AccessSpecifier AS) {
878  if (DS) {
879    return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
880  } else {
881    ParsingDeclSpec PDS(*this);
882    // Must temporarily exit the objective-c container scope for
883    // parsing c constructs and re-enter objc container scope
884    // afterwards.
885    ObjCDeclContextSwitch ObjCDC(*this);
886
887    return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
888  }
889}
890
891/// ParseFunctionDefinition - We parsed and verified that the specified
892/// Declarator is well formed.  If this is a K&R-style function, read the
893/// parameters declaration-list, then start the compound-statement.
894///
895///       function-definition: [C99 6.9.1]
896///         decl-specs      declarator declaration-list[opt] compound-statement
897/// [C90] function-definition: [C99 6.7.1] - implicit int result
898/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
899/// [C++] function-definition: [C++ 8.4]
900///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
901///         function-body
902/// [C++] function-definition: [C++ 8.4]
903///         decl-specifier-seq[opt] declarator function-try-block
904///
905Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
906                                      const ParsedTemplateInfo &TemplateInfo,
907                                      LateParsedAttrList *LateParsedAttrs) {
908  // Poison the SEH identifiers so they are flagged as illegal in function bodies
909  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
910  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
911
912  // If this is C90 and the declspecs were completely missing, fudge in an
913  // implicit int.  We do this here because this is the only place where
914  // declaration-specifiers are completely optional in the grammar.
915  if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
916    const char *PrevSpec;
917    unsigned DiagID;
918    D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
919                                           D.getIdentifierLoc(),
920                                           PrevSpec, DiagID);
921    D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
922  }
923
924  // If this declaration was formed with a K&R-style identifier list for the
925  // arguments, parse declarations for all of the args next.
926  // int foo(a,b) int a; float b; {}
927  if (FTI.isKNRPrototype())
928    ParseKNRParamDeclarations(D);
929
930  // We should have either an opening brace or, in a C++ constructor,
931  // we may have a colon.
932  if (Tok.isNot(tok::l_brace) &&
933      (!getLangOpts().CPlusPlus ||
934       (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
935        Tok.isNot(tok::equal)))) {
936    Diag(Tok, diag::err_expected_fn_body);
937
938    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
939    SkipUntil(tok::l_brace, true, true);
940
941    // If we didn't find the '{', bail out.
942    if (Tok.isNot(tok::l_brace))
943      return 0;
944  }
945
946  // Check to make sure that any normal attributes are allowed to be on
947  // a definition.  Late parsed attributes are checked at the end.
948  if (Tok.isNot(tok::equal)) {
949    AttributeList *DtorAttrs = D.getAttributes();
950    while (DtorAttrs) {
951      if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName()) &&
952          !DtorAttrs->isCXX11Attribute()) {
953        Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
954          << DtorAttrs->getName()->getName();
955      }
956      DtorAttrs = DtorAttrs->getNext();
957    }
958  }
959
960  // In delayed template parsing mode, for function template we consume the
961  // tokens and store them for late parsing at the end of the translation unit.
962  if (getLangOpts().DelayedTemplateParsing &&
963      Tok.isNot(tok::equal) &&
964      TemplateInfo.Kind == ParsedTemplateInfo::Template) {
965    MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
966
967    ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
968    Scope *ParentScope = getCurScope()->getParent();
969
970    D.setFunctionDefinitionKind(FDK_Definition);
971    Decl *DP = Actions.HandleDeclarator(ParentScope, D,
972                                        TemplateParameterLists);
973    D.complete(DP);
974    D.getMutableDeclSpec().abort();
975
976    if (DP) {
977      LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
978
979      FunctionDecl *FnD = 0;
980      if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
981        FnD = FunTmpl->getTemplatedDecl();
982      else
983        FnD = cast<FunctionDecl>(DP);
984      Actions.CheckForFunctionRedefinition(FnD);
985
986      LateParsedTemplateMap[FnD] = LPT;
987      Actions.MarkAsLateParsedTemplate(FnD);
988      LexTemplateFunctionForLateParsing(LPT->Toks);
989    } else {
990      CachedTokens Toks;
991      LexTemplateFunctionForLateParsing(Toks);
992    }
993    return DP;
994  }
995  else if (CurParsedObjCImpl &&
996           !TemplateInfo.TemplateParams &&
997           (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
998            Tok.is(tok::colon)) &&
999      Actions.CurContext->isTranslationUnit()) {
1000    ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1001    Scope *ParentScope = getCurScope()->getParent();
1002
1003    D.setFunctionDefinitionKind(FDK_Definition);
1004    Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1005                                              MultiTemplateParamsArg());
1006    D.complete(FuncDecl);
1007    D.getMutableDeclSpec().abort();
1008    if (FuncDecl) {
1009      // Consume the tokens and store them for later parsing.
1010      StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1011      CurParsedObjCImpl->HasCFunction = true;
1012      return FuncDecl;
1013    }
1014  }
1015
1016  // Enter a scope for the function body.
1017  ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1018
1019  // Tell the actions module that we have entered a function definition with the
1020  // specified Declarator for the function.
1021  Decl *Res = TemplateInfo.TemplateParams?
1022      Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1023                                              *TemplateInfo.TemplateParams, D)
1024    : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1025
1026  // Break out of the ParsingDeclarator context before we parse the body.
1027  D.complete(Res);
1028
1029  // Break out of the ParsingDeclSpec context, too.  This const_cast is
1030  // safe because we're always the sole owner.
1031  D.getMutableDeclSpec().abort();
1032
1033  if (Tok.is(tok::equal)) {
1034    assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1035    ConsumeToken();
1036
1037    Actions.ActOnFinishFunctionBody(Res, 0, false);
1038
1039    bool Delete = false;
1040    SourceLocation KWLoc;
1041    if (Tok.is(tok::kw_delete)) {
1042      Diag(Tok, getLangOpts().CPlusPlus11 ?
1043           diag::warn_cxx98_compat_deleted_function :
1044           diag::ext_deleted_function);
1045
1046      KWLoc = ConsumeToken();
1047      Actions.SetDeclDeleted(Res, KWLoc);
1048      Delete = true;
1049    } else if (Tok.is(tok::kw_default)) {
1050      Diag(Tok, getLangOpts().CPlusPlus11 ?
1051           diag::warn_cxx98_compat_defaulted_function :
1052           diag::ext_defaulted_function);
1053
1054      KWLoc = ConsumeToken();
1055      Actions.SetDeclDefaulted(Res, KWLoc);
1056    } else {
1057      llvm_unreachable("function definition after = not 'delete' or 'default'");
1058    }
1059
1060    if (Tok.is(tok::comma)) {
1061      Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1062        << Delete;
1063      SkipUntil(tok::semi);
1064    } else {
1065      ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1066                       Delete ? "delete" : "default", tok::semi);
1067    }
1068
1069    return Res;
1070  }
1071
1072  if (Tok.is(tok::kw_try))
1073    return ParseFunctionTryBlock(Res, BodyScope);
1074
1075  // If we have a colon, then we're probably parsing a C++
1076  // ctor-initializer.
1077  if (Tok.is(tok::colon)) {
1078    ParseConstructorInitializer(Res);
1079
1080    // Recover from error.
1081    if (!Tok.is(tok::l_brace)) {
1082      BodyScope.Exit();
1083      Actions.ActOnFinishFunctionBody(Res, 0);
1084      return Res;
1085    }
1086  } else
1087    Actions.ActOnDefaultCtorInitializers(Res);
1088
1089  // Late attributes are parsed in the same scope as the function body.
1090  if (LateParsedAttrs)
1091    ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1092
1093  return ParseFunctionStatementBody(Res, BodyScope);
1094}
1095
1096/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1097/// types for a function with a K&R-style identifier list for arguments.
1098void Parser::ParseKNRParamDeclarations(Declarator &D) {
1099  // We know that the top-level of this declarator is a function.
1100  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1101
1102  // Enter function-declaration scope, limiting any declarators to the
1103  // function prototype scope, including parameter declarators.
1104  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1105                            Scope::FunctionDeclarationScope | Scope::DeclScope);
1106
1107  // Read all the argument declarations.
1108  while (isDeclarationSpecifier()) {
1109    SourceLocation DSStart = Tok.getLocation();
1110
1111    // Parse the common declaration-specifiers piece.
1112    DeclSpec DS(AttrFactory);
1113    ParseDeclarationSpecifiers(DS);
1114
1115    // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1116    // least one declarator'.
1117    // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1118    // the declarations though.  It's trivial to ignore them, really hard to do
1119    // anything else with them.
1120    if (Tok.is(tok::semi)) {
1121      Diag(DSStart, diag::err_declaration_does_not_declare_param);
1122      ConsumeToken();
1123      continue;
1124    }
1125
1126    // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1127    // than register.
1128    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1129        DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1130      Diag(DS.getStorageClassSpecLoc(),
1131           diag::err_invalid_storage_class_in_func_decl);
1132      DS.ClearStorageClassSpecs();
1133    }
1134    if (DS.isThreadSpecified()) {
1135      Diag(DS.getThreadSpecLoc(),
1136           diag::err_invalid_storage_class_in_func_decl);
1137      DS.ClearStorageClassSpecs();
1138    }
1139
1140    // Parse the first declarator attached to this declspec.
1141    Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1142    ParseDeclarator(ParmDeclarator);
1143
1144    // Handle the full declarator list.
1145    while (1) {
1146      // If attributes are present, parse them.
1147      MaybeParseGNUAttributes(ParmDeclarator);
1148
1149      // Ask the actions module to compute the type for this declarator.
1150      Decl *Param =
1151        Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1152
1153      if (Param &&
1154          // A missing identifier has already been diagnosed.
1155          ParmDeclarator.getIdentifier()) {
1156
1157        // Scan the argument list looking for the correct param to apply this
1158        // type.
1159        for (unsigned i = 0; ; ++i) {
1160          // C99 6.9.1p6: those declarators shall declare only identifiers from
1161          // the identifier list.
1162          if (i == FTI.NumArgs) {
1163            Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1164              << ParmDeclarator.getIdentifier();
1165            break;
1166          }
1167
1168          if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1169            // Reject redefinitions of parameters.
1170            if (FTI.ArgInfo[i].Param) {
1171              Diag(ParmDeclarator.getIdentifierLoc(),
1172                   diag::err_param_redefinition)
1173                 << ParmDeclarator.getIdentifier();
1174            } else {
1175              FTI.ArgInfo[i].Param = Param;
1176            }
1177            break;
1178          }
1179        }
1180      }
1181
1182      // If we don't have a comma, it is either the end of the list (a ';') or
1183      // an error, bail out.
1184      if (Tok.isNot(tok::comma))
1185        break;
1186
1187      ParmDeclarator.clear();
1188
1189      // Consume the comma.
1190      ParmDeclarator.setCommaLoc(ConsumeToken());
1191
1192      // Parse the next declarator.
1193      ParseDeclarator(ParmDeclarator);
1194    }
1195
1196    if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1197      // Skip to end of block or statement
1198      SkipUntil(tok::semi, true);
1199      if (Tok.is(tok::semi))
1200        ConsumeToken();
1201    }
1202  }
1203
1204  // The actions module must verify that all arguments were declared.
1205  Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1206}
1207
1208
1209/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1210/// allowed to be a wide string, and is not subject to character translation.
1211///
1212/// [GNU] asm-string-literal:
1213///         string-literal
1214///
1215Parser::ExprResult Parser::ParseAsmStringLiteral() {
1216  switch (Tok.getKind()) {
1217    case tok::string_literal:
1218      break;
1219    case tok::utf8_string_literal:
1220    case tok::utf16_string_literal:
1221    case tok::utf32_string_literal:
1222    case tok::wide_string_literal: {
1223      SourceLocation L = Tok.getLocation();
1224      Diag(Tok, diag::err_asm_operand_wide_string_literal)
1225        << (Tok.getKind() == tok::wide_string_literal)
1226        << SourceRange(L, L);
1227      return ExprError();
1228    }
1229    default:
1230      Diag(Tok, diag::err_expected_string_literal)
1231        << /*Source='in...'*/0 << "'asm'";
1232      return ExprError();
1233  }
1234
1235  return ParseStringLiteralExpression();
1236}
1237
1238/// ParseSimpleAsm
1239///
1240/// [GNU] simple-asm-expr:
1241///         'asm' '(' asm-string-literal ')'
1242///
1243Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1244  assert(Tok.is(tok::kw_asm) && "Not an asm!");
1245  SourceLocation Loc = ConsumeToken();
1246
1247  if (Tok.is(tok::kw_volatile)) {
1248    // Remove from the end of 'asm' to the end of 'volatile'.
1249    SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1250                             PP.getLocForEndOfToken(Tok.getLocation()));
1251
1252    Diag(Tok, diag::warn_file_asm_volatile)
1253      << FixItHint::CreateRemoval(RemovalRange);
1254    ConsumeToken();
1255  }
1256
1257  BalancedDelimiterTracker T(*this, tok::l_paren);
1258  if (T.consumeOpen()) {
1259    Diag(Tok, diag::err_expected_lparen_after) << "asm";
1260    return ExprError();
1261  }
1262
1263  ExprResult Result(ParseAsmStringLiteral());
1264
1265  if (Result.isInvalid()) {
1266    SkipUntil(tok::r_paren, true, true);
1267    if (EndLoc)
1268      *EndLoc = Tok.getLocation();
1269    ConsumeAnyToken();
1270  } else {
1271    // Close the paren and get the location of the end bracket
1272    T.consumeClose();
1273    if (EndLoc)
1274      *EndLoc = T.getCloseLocation();
1275  }
1276
1277  return Result;
1278}
1279
1280/// \brief Get the TemplateIdAnnotation from the token and put it in the
1281/// cleanup pool so that it gets destroyed when parsing the current top level
1282/// declaration is finished.
1283TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1284  assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1285  TemplateIdAnnotation *
1286      Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1287  return Id;
1288}
1289
1290void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1291  // Push the current token back into the token stream (or revert it if it is
1292  // cached) and use an annotation scope token for current token.
1293  if (PP.isBacktrackEnabled())
1294    PP.RevertCachedTokens(1);
1295  else
1296    PP.EnterToken(Tok);
1297  Tok.setKind(tok::annot_cxxscope);
1298  Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1299  Tok.setAnnotationRange(SS.getRange());
1300
1301  // In case the tokens were cached, have Preprocessor replace them
1302  // with the annotation token.  We don't need to do this if we've
1303  // just reverted back to a prior state.
1304  if (IsNewAnnotation)
1305    PP.AnnotateCachedTokens(Tok);
1306}
1307
1308/// \brief Attempt to classify the name at the current token position. This may
1309/// form a type, scope or primary expression annotation, or replace the token
1310/// with a typo-corrected keyword. This is only appropriate when the current
1311/// name must refer to an entity which has already been declared.
1312///
1313/// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1314///        and might possibly have a dependent nested name specifier.
1315/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1316///        no typo correction will be performed.
1317Parser::AnnotatedNameKind
1318Parser::TryAnnotateName(bool IsAddressOfOperand,
1319                        CorrectionCandidateCallback *CCC) {
1320  assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1321
1322  const bool EnteringContext = false;
1323  const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1324
1325  CXXScopeSpec SS;
1326  if (getLangOpts().CPlusPlus &&
1327      ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1328    return ANK_Error;
1329
1330  if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1331    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1332                                                  !WasScopeAnnotation))
1333      return ANK_Error;
1334    return ANK_Unresolved;
1335  }
1336
1337  IdentifierInfo *Name = Tok.getIdentifierInfo();
1338  SourceLocation NameLoc = Tok.getLocation();
1339
1340  // FIXME: Move the tentative declaration logic into ClassifyName so we can
1341  // typo-correct to tentatively-declared identifiers.
1342  if (isTentativelyDeclared(Name)) {
1343    // Identifier has been tentatively declared, and thus cannot be resolved as
1344    // an expression. Fall back to annotating it as a type.
1345    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1346                                                  !WasScopeAnnotation))
1347      return ANK_Error;
1348    return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1349  }
1350
1351  Token Next = NextToken();
1352
1353  // Look up and classify the identifier. We don't perform any typo-correction
1354  // after a scope specifier, because in general we can't recover from typos
1355  // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1356  // back into scope specifier parsing).
1357  Sema::NameClassification Classification
1358    = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1359                           IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1360
1361  switch (Classification.getKind()) {
1362  case Sema::NC_Error:
1363    return ANK_Error;
1364
1365  case Sema::NC_Keyword:
1366    // The identifier was typo-corrected to a keyword.
1367    Tok.setIdentifierInfo(Name);
1368    Tok.setKind(Name->getTokenID());
1369    PP.TypoCorrectToken(Tok);
1370    if (SS.isNotEmpty())
1371      AnnotateScopeToken(SS, !WasScopeAnnotation);
1372    // We've "annotated" this as a keyword.
1373    return ANK_Success;
1374
1375  case Sema::NC_Unknown:
1376    // It's not something we know about. Leave it unannotated.
1377    break;
1378
1379  case Sema::NC_Type:
1380    Tok.setKind(tok::annot_typename);
1381    setTypeAnnotation(Tok, Classification.getType());
1382    Tok.setAnnotationEndLoc(NameLoc);
1383    if (SS.isNotEmpty())
1384      Tok.setLocation(SS.getBeginLoc());
1385    PP.AnnotateCachedTokens(Tok);
1386    return ANK_Success;
1387
1388  case Sema::NC_Expression:
1389    Tok.setKind(tok::annot_primary_expr);
1390    setExprAnnotation(Tok, Classification.getExpression());
1391    Tok.setAnnotationEndLoc(NameLoc);
1392    if (SS.isNotEmpty())
1393      Tok.setLocation(SS.getBeginLoc());
1394    PP.AnnotateCachedTokens(Tok);
1395    return ANK_Success;
1396
1397  case Sema::NC_TypeTemplate:
1398    if (Next.isNot(tok::less)) {
1399      // This may be a type template being used as a template template argument.
1400      if (SS.isNotEmpty())
1401        AnnotateScopeToken(SS, !WasScopeAnnotation);
1402      return ANK_TemplateName;
1403    }
1404    // Fall through.
1405  case Sema::NC_FunctionTemplate: {
1406    // We have a type or function template followed by '<'.
1407    ConsumeToken();
1408    UnqualifiedId Id;
1409    Id.setIdentifier(Name, NameLoc);
1410    if (AnnotateTemplateIdToken(
1411            TemplateTy::make(Classification.getTemplateName()),
1412            Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1413      return ANK_Error;
1414    return ANK_Success;
1415  }
1416
1417  case Sema::NC_NestedNameSpecifier:
1418    llvm_unreachable("already parsed nested name specifier");
1419  }
1420
1421  // Unable to classify the name, but maybe we can annotate a scope specifier.
1422  if (SS.isNotEmpty())
1423    AnnotateScopeToken(SS, !WasScopeAnnotation);
1424  return ANK_Unresolved;
1425}
1426
1427/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1428/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1429/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1430/// with a single annotation token representing the typename or C++ scope
1431/// respectively.
1432/// This simplifies handling of C++ scope specifiers and allows efficient
1433/// backtracking without the need to re-parse and resolve nested-names and
1434/// typenames.
1435/// It will mainly be called when we expect to treat identifiers as typenames
1436/// (if they are typenames). For example, in C we do not expect identifiers
1437/// inside expressions to be treated as typenames so it will not be called
1438/// for expressions in C.
1439/// The benefit for C/ObjC is that a typename will be annotated and
1440/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1441/// will not be called twice, once to check whether we have a declaration
1442/// specifier, and another one to get the actual type inside
1443/// ParseDeclarationSpecifiers).
1444///
1445/// This returns true if an error occurred.
1446///
1447/// Note that this routine emits an error if you call it with ::new or ::delete
1448/// as the current tokens, so only call it in contexts where these are invalid.
1449bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1450  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1451          || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1452          || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1453          && "Cannot be a type or scope token!");
1454
1455  if (Tok.is(tok::kw_typename)) {
1456    // Parse a C++ typename-specifier, e.g., "typename T::type".
1457    //
1458    //   typename-specifier:
1459    //     'typename' '::' [opt] nested-name-specifier identifier
1460    //     'typename' '::' [opt] nested-name-specifier template [opt]
1461    //            simple-template-id
1462    SourceLocation TypenameLoc = ConsumeToken();
1463    CXXScopeSpec SS;
1464    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1465                                       /*EnteringContext=*/false,
1466                                       0, /*IsTypename*/true))
1467      return true;
1468    if (!SS.isSet()) {
1469      if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1470          Tok.is(tok::annot_decltype)) {
1471        // Attempt to recover by skipping the invalid 'typename'
1472        if (Tok.is(tok::annot_decltype) ||
1473            (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1474            Tok.isAnnotation())) {
1475          unsigned DiagID = diag::err_expected_qualified_after_typename;
1476          // MS compatibility: MSVC permits using known types with typename.
1477          // e.g. "typedef typename T* pointer_type"
1478          if (getLangOpts().MicrosoftExt)
1479            DiagID = diag::warn_expected_qualified_after_typename;
1480          Diag(Tok.getLocation(), DiagID);
1481          return false;
1482        }
1483      }
1484
1485      Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1486      return true;
1487    }
1488
1489    TypeResult Ty;
1490    if (Tok.is(tok::identifier)) {
1491      // FIXME: check whether the next token is '<', first!
1492      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1493                                     *Tok.getIdentifierInfo(),
1494                                     Tok.getLocation());
1495    } else if (Tok.is(tok::annot_template_id)) {
1496      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1497      if (TemplateId->Kind == TNK_Function_template) {
1498        Diag(Tok, diag::err_typename_refers_to_non_type_template)
1499          << Tok.getAnnotationRange();
1500        return true;
1501      }
1502
1503      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1504                                         TemplateId->NumArgs);
1505
1506      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1507                                     TemplateId->TemplateKWLoc,
1508                                     TemplateId->Template,
1509                                     TemplateId->TemplateNameLoc,
1510                                     TemplateId->LAngleLoc,
1511                                     TemplateArgsPtr,
1512                                     TemplateId->RAngleLoc);
1513    } else {
1514      Diag(Tok, diag::err_expected_type_name_after_typename)
1515        << SS.getRange();
1516      return true;
1517    }
1518
1519    SourceLocation EndLoc = Tok.getLastLoc();
1520    Tok.setKind(tok::annot_typename);
1521    setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1522    Tok.setAnnotationEndLoc(EndLoc);
1523    Tok.setLocation(TypenameLoc);
1524    PP.AnnotateCachedTokens(Tok);
1525    return false;
1526  }
1527
1528  // Remembers whether the token was originally a scope annotation.
1529  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1530
1531  CXXScopeSpec SS;
1532  if (getLangOpts().CPlusPlus)
1533    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1534      return true;
1535
1536  return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1537                                                   SS, !WasScopeAnnotation);
1538}
1539
1540/// \brief Try to annotate a type or scope token, having already parsed an
1541/// optional scope specifier. \p IsNewScope should be \c true unless the scope
1542/// specifier was extracted from an existing tok::annot_cxxscope annotation.
1543bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1544                                                       bool NeedType,
1545                                                       CXXScopeSpec &SS,
1546                                                       bool IsNewScope) {
1547  if (Tok.is(tok::identifier)) {
1548    IdentifierInfo *CorrectedII = 0;
1549    // Determine whether the identifier is a type name.
1550    if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1551                                            Tok.getLocation(), getCurScope(),
1552                                            &SS, false,
1553                                            NextToken().is(tok::period),
1554                                            ParsedType(),
1555                                            /*IsCtorOrDtorName=*/false,
1556                                            /*NonTrivialTypeSourceInfo*/true,
1557                                            NeedType ? &CorrectedII : NULL)) {
1558      // A FixIt was applied as a result of typo correction
1559      if (CorrectedII)
1560        Tok.setIdentifierInfo(CorrectedII);
1561      // This is a typename. Replace the current token in-place with an
1562      // annotation type token.
1563      Tok.setKind(tok::annot_typename);
1564      setTypeAnnotation(Tok, Ty);
1565      Tok.setAnnotationEndLoc(Tok.getLocation());
1566      if (SS.isNotEmpty()) // it was a C++ qualified type name.
1567        Tok.setLocation(SS.getBeginLoc());
1568
1569      // In case the tokens were cached, have Preprocessor replace
1570      // them with the annotation token.
1571      PP.AnnotateCachedTokens(Tok);
1572      return false;
1573    }
1574
1575    if (!getLangOpts().CPlusPlus) {
1576      // If we're in C, we can't have :: tokens at all (the lexer won't return
1577      // them).  If the identifier is not a type, then it can't be scope either,
1578      // just early exit.
1579      return false;
1580    }
1581
1582    // If this is a template-id, annotate with a template-id or type token.
1583    if (NextToken().is(tok::less)) {
1584      TemplateTy Template;
1585      UnqualifiedId TemplateName;
1586      TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1587      bool MemberOfUnknownSpecialization;
1588      if (TemplateNameKind TNK
1589          = Actions.isTemplateName(getCurScope(), SS,
1590                                   /*hasTemplateKeyword=*/false, TemplateName,
1591                                   /*ObjectType=*/ ParsedType(),
1592                                   EnteringContext,
1593                                   Template, MemberOfUnknownSpecialization)) {
1594        // Consume the identifier.
1595        ConsumeToken();
1596        if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1597                                    TemplateName)) {
1598          // If an unrecoverable error occurred, we need to return true here,
1599          // because the token stream is in a damaged state.  We may not return
1600          // a valid identifier.
1601          return true;
1602        }
1603      }
1604    }
1605
1606    // The current token, which is either an identifier or a
1607    // template-id, is not part of the annotation. Fall through to
1608    // push that token back into the stream and complete the C++ scope
1609    // specifier annotation.
1610  }
1611
1612  if (Tok.is(tok::annot_template_id)) {
1613    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1614    if (TemplateId->Kind == TNK_Type_template) {
1615      // A template-id that refers to a type was parsed into a
1616      // template-id annotation in a context where we weren't allowed
1617      // to produce a type annotation token. Update the template-id
1618      // annotation token to a type annotation token now.
1619      AnnotateTemplateIdTokenAsType();
1620      return false;
1621    }
1622  }
1623
1624  if (SS.isEmpty())
1625    return false;
1626
1627  // A C++ scope specifier that isn't followed by a typename.
1628  AnnotateScopeToken(SS, IsNewScope);
1629  return false;
1630}
1631
1632/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1633/// annotates C++ scope specifiers and template-ids.  This returns
1634/// true if there was an error that could not be recovered from.
1635///
1636/// Note that this routine emits an error if you call it with ::new or ::delete
1637/// as the current tokens, so only call it in contexts where these are invalid.
1638bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1639  assert(getLangOpts().CPlusPlus &&
1640         "Call sites of this function should be guarded by checking for C++");
1641  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1642          (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1643         Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1644
1645  CXXScopeSpec SS;
1646  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1647    return true;
1648  if (SS.isEmpty())
1649    return false;
1650
1651  AnnotateScopeToken(SS, true);
1652  return false;
1653}
1654
1655bool Parser::isTokenEqualOrEqualTypo() {
1656  tok::TokenKind Kind = Tok.getKind();
1657  switch (Kind) {
1658  default:
1659    return false;
1660  case tok::ampequal:            // &=
1661  case tok::starequal:           // *=
1662  case tok::plusequal:           // +=
1663  case tok::minusequal:          // -=
1664  case tok::exclaimequal:        // !=
1665  case tok::slashequal:          // /=
1666  case tok::percentequal:        // %=
1667  case tok::lessequal:           // <=
1668  case tok::lesslessequal:       // <<=
1669  case tok::greaterequal:        // >=
1670  case tok::greatergreaterequal: // >>=
1671  case tok::caretequal:          // ^=
1672  case tok::pipeequal:           // |=
1673  case tok::equalequal:          // ==
1674    Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1675      << getTokenSimpleSpelling(Kind)
1676      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1677  case tok::equal:
1678    return true;
1679  }
1680}
1681
1682SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1683  assert(Tok.is(tok::code_completion));
1684  PrevTokLocation = Tok.getLocation();
1685
1686  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1687    if (S->getFlags() & Scope::FnScope) {
1688      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1689      cutOffParsing();
1690      return PrevTokLocation;
1691    }
1692
1693    if (S->getFlags() & Scope::ClassScope) {
1694      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1695      cutOffParsing();
1696      return PrevTokLocation;
1697    }
1698  }
1699
1700  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1701  cutOffParsing();
1702  return PrevTokLocation;
1703}
1704
1705// Anchor the Parser::FieldCallback vtable to this translation unit.
1706// We use a spurious method instead of the destructor because
1707// destroying FieldCallbacks can actually be slightly
1708// performance-sensitive.
1709void Parser::FieldCallback::_anchor() {
1710}
1711
1712// Code-completion pass-through functions
1713
1714void Parser::CodeCompleteDirective(bool InConditional) {
1715  Actions.CodeCompletePreprocessorDirective(InConditional);
1716}
1717
1718void Parser::CodeCompleteInConditionalExclusion() {
1719  Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1720}
1721
1722void Parser::CodeCompleteMacroName(bool IsDefinition) {
1723  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1724}
1725
1726void Parser::CodeCompletePreprocessorExpression() {
1727  Actions.CodeCompletePreprocessorExpression();
1728}
1729
1730void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1731                                       MacroInfo *MacroInfo,
1732                                       unsigned ArgumentIndex) {
1733  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1734                                                ArgumentIndex);
1735}
1736
1737void Parser::CodeCompleteNaturalLanguage() {
1738  Actions.CodeCompleteNaturalLanguage();
1739}
1740
1741bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1742  assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1743         "Expected '__if_exists' or '__if_not_exists'");
1744  Result.IsIfExists = Tok.is(tok::kw___if_exists);
1745  Result.KeywordLoc = ConsumeToken();
1746
1747  BalancedDelimiterTracker T(*this, tok::l_paren);
1748  if (T.consumeOpen()) {
1749    Diag(Tok, diag::err_expected_lparen_after)
1750      << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1751    return true;
1752  }
1753
1754  // Parse nested-name-specifier.
1755  ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1756                                 /*EnteringContext=*/false);
1757
1758  // Check nested-name specifier.
1759  if (Result.SS.isInvalid()) {
1760    T.skipToEnd();
1761    return true;
1762  }
1763
1764  // Parse the unqualified-id.
1765  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1766  if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1767                         TemplateKWLoc, Result.Name)) {
1768    T.skipToEnd();
1769    return true;
1770  }
1771
1772  if (T.consumeClose())
1773    return true;
1774
1775  // Check if the symbol exists.
1776  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1777                                               Result.IsIfExists, Result.SS,
1778                                               Result.Name)) {
1779  case Sema::IER_Exists:
1780    Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1781    break;
1782
1783  case Sema::IER_DoesNotExist:
1784    Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1785    break;
1786
1787  case Sema::IER_Dependent:
1788    Result.Behavior = IEB_Dependent;
1789    break;
1790
1791  case Sema::IER_Error:
1792    return true;
1793  }
1794
1795  return false;
1796}
1797
1798void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1799  IfExistsCondition Result;
1800  if (ParseMicrosoftIfExistsCondition(Result))
1801    return;
1802
1803  BalancedDelimiterTracker Braces(*this, tok::l_brace);
1804  if (Braces.consumeOpen()) {
1805    Diag(Tok, diag::err_expected_lbrace);
1806    return;
1807  }
1808
1809  switch (Result.Behavior) {
1810  case IEB_Parse:
1811    // Parse declarations below.
1812    break;
1813
1814  case IEB_Dependent:
1815    llvm_unreachable("Cannot have a dependent external declaration");
1816
1817  case IEB_Skip:
1818    Braces.skipToEnd();
1819    return;
1820  }
1821
1822  // Parse the declarations.
1823  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1824    ParsedAttributesWithRange attrs(AttrFactory);
1825    MaybeParseCXX11Attributes(attrs);
1826    MaybeParseMicrosoftAttributes(attrs);
1827    DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1828    if (Result && !getCurScope()->getParent())
1829      Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1830  }
1831  Braces.consumeClose();
1832}
1833
1834Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1835  assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1836         "Improper start to module import");
1837  SourceLocation ImportLoc = ConsumeToken();
1838
1839  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1840
1841  // Parse the module path.
1842  do {
1843    if (!Tok.is(tok::identifier)) {
1844      if (Tok.is(tok::code_completion)) {
1845        Actions.CodeCompleteModuleImport(ImportLoc, Path);
1846        ConsumeCodeCompletionToken();
1847        SkipUntil(tok::semi);
1848        return DeclGroupPtrTy();
1849      }
1850
1851      Diag(Tok, diag::err_module_expected_ident);
1852      SkipUntil(tok::semi);
1853      return DeclGroupPtrTy();
1854    }
1855
1856    // Record this part of the module path.
1857    Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1858    ConsumeToken();
1859
1860    if (Tok.is(tok::period)) {
1861      ConsumeToken();
1862      continue;
1863    }
1864
1865    break;
1866  } while (true);
1867
1868  DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1869  ExpectAndConsumeSemi(diag::err_module_expected_semi);
1870  if (Import.isInvalid())
1871    return DeclGroupPtrTy();
1872
1873  return Actions.ConvertDeclToDeclGroup(Import.get());
1874}
1875
1876bool BalancedDelimiterTracker::diagnoseOverflow() {
1877  P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1878    << P.getLangOpts().BracketDepth;
1879  P.Diag(P.Tok, diag::note_bracket_depth);
1880  P.SkipUntil(tok::eof);
1881  return true;
1882}
1883
1884bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1885                                            const char *Msg,
1886                                            tok::TokenKind SkipToToc ) {
1887  LOpen = P.Tok.getLocation();
1888  if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1889    return true;
1890
1891  if (getDepth() < MaxDepth)
1892    return false;
1893
1894  return diagnoseOverflow();
1895}
1896
1897bool BalancedDelimiterTracker::diagnoseMissingClose() {
1898  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1899
1900  const char *LHSName = "unknown";
1901  diag::kind DID;
1902  switch (Close) {
1903  default: llvm_unreachable("Unexpected balanced token");
1904  case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1905  case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1906  case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1907  }
1908  P.Diag(P.Tok, DID);
1909  P.Diag(LOpen, diag::note_matching) << LHSName;
1910  if (P.SkipUntil(Close, /*StopAtSemi*/ true, /*DontConsume*/ true))
1911    LClose = P.ConsumeAnyToken();
1912  return true;
1913}
1914
1915void BalancedDelimiterTracker::skipToEnd() {
1916  P.SkipUntil(Close, false);
1917}
1918