Parser.cpp revision 218893
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 "clang/Parse/ParseDiagnostic.h"
16#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "llvm/Support/raw_ostream.h"
20#include "RAIIObjectsForParser.h"
21#include "ParsePragma.h"
22using namespace clang;
23
24Parser::Parser(Preprocessor &pp, Sema &actions)
25  : CrashInfo(*this), PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
26    GreaterThanIsOperator(true), ColonIsSacred(false),
27    InMessageExpression(false), TemplateParameterDepth(0) {
28  Tok.setKind(tok::eof);
29  Actions.CurScope = 0;
30  NumCachedScopes = 0;
31  ParenCount = BracketCount = BraceCount = 0;
32  ObjCImpDecl = 0;
33
34  // Add #pragma handlers. These are removed and destroyed in the
35  // destructor.
36  AlignHandler.reset(new PragmaAlignHandler(actions));
37  PP.AddPragmaHandler(AlignHandler.get());
38
39  GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
40  PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
41
42  OptionsHandler.reset(new PragmaOptionsHandler(actions));
43  PP.AddPragmaHandler(OptionsHandler.get());
44
45  PackHandler.reset(new PragmaPackHandler(actions));
46  PP.AddPragmaHandler(PackHandler.get());
47
48  UnusedHandler.reset(new PragmaUnusedHandler(actions, *this));
49  PP.AddPragmaHandler(UnusedHandler.get());
50
51  WeakHandler.reset(new PragmaWeakHandler(actions));
52  PP.AddPragmaHandler(WeakHandler.get());
53
54  FPContractHandler.reset(new PragmaFPContractHandler(actions, *this));
55  PP.AddPragmaHandler("STDC", FPContractHandler.get());
56
57  if (getLang().OpenCL) {
58    OpenCLExtensionHandler.reset(
59                  new PragmaOpenCLExtensionHandler(actions, *this));
60    PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
61
62    PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
63  }
64
65  PP.setCodeCompletionHandler(*this);
66}
67
68/// If a crash happens while the parser is active, print out a line indicating
69/// what the current token is.
70void PrettyStackTraceParserEntry::print(llvm::raw_ostream &OS) const {
71  const Token &Tok = P.getCurToken();
72  if (Tok.is(tok::eof)) {
73    OS << "<eof> parser at end of file\n";
74    return;
75  }
76
77  if (Tok.getLocation().isInvalid()) {
78    OS << "<unknown> parser at unknown location\n";
79    return;
80  }
81
82  const Preprocessor &PP = P.getPreprocessor();
83  Tok.getLocation().print(OS, PP.getSourceManager());
84  if (Tok.isAnnotation())
85    OS << ": at annotation token \n";
86  else
87    OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
88}
89
90
91DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
92  return Diags.Report(Loc, DiagID);
93}
94
95DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
96  return Diag(Tok.getLocation(), DiagID);
97}
98
99/// \brief Emits a diagnostic suggesting parentheses surrounding a
100/// given range.
101///
102/// \param Loc The location where we'll emit the diagnostic.
103/// \param Loc The kind of diagnostic to emit.
104/// \param ParenRange Source range enclosing code that should be parenthesized.
105void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
106                                SourceRange ParenRange) {
107  SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
108  if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
109    // We can't display the parentheses, so just dig the
110    // warning/error and return.
111    Diag(Loc, DK);
112    return;
113  }
114
115  Diag(Loc, DK)
116    << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
117    << FixItHint::CreateInsertion(EndLoc, ")");
118}
119
120/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
121/// this helper function matches and consumes the specified RHS token if
122/// present.  If not present, it emits the specified diagnostic indicating
123/// that the parser failed to match the RHS of the token at LHSLoc.  LHSName
124/// should be the name of the unmatched LHS token.
125SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
126                                           SourceLocation LHSLoc) {
127
128  if (Tok.is(RHSTok))
129    return ConsumeAnyToken();
130
131  SourceLocation R = Tok.getLocation();
132  const char *LHSName = "unknown";
133  diag::kind DID = diag::err_parse_error;
134  switch (RHSTok) {
135  default: break;
136  case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
137  case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
138  case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
139  case tok::greater:  LHSName = "<"; DID = diag::err_expected_greater; break;
140  case tok::greatergreatergreater:
141                      LHSName = "<<<"; DID = diag::err_expected_ggg; break;
142  }
143  Diag(Tok, DID);
144  Diag(LHSLoc, diag::note_matching) << LHSName;
145  SkipUntil(RHSTok);
146  return R;
147}
148
149static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
150  switch (ExpectedTok) {
151  case tok::semi: return Tok.is(tok::colon); // : for ;
152  default: return false;
153  }
154}
155
156/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
157/// input.  If so, it is consumed and false is returned.
158///
159/// If the input is malformed, this emits the specified diagnostic.  Next, if
160/// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
161/// returned.
162bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
163                              const char *Msg, tok::TokenKind SkipToTok) {
164  if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
165    ConsumeAnyToken();
166    return false;
167  }
168
169  // Detect common single-character typos and resume.
170  if (IsCommonTypo(ExpectedTok, Tok)) {
171    SourceLocation Loc = Tok.getLocation();
172    Diag(Loc, DiagID)
173      << Msg
174      << FixItHint::CreateReplacement(SourceRange(Loc),
175                                      getTokenSimpleSpelling(ExpectedTok));
176    ConsumeAnyToken();
177
178    // Pretend there wasn't a problem.
179    return false;
180  }
181
182  const char *Spelling = 0;
183  SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
184  if (EndLoc.isValid() &&
185      (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
186    // Show what code to insert to fix this problem.
187    Diag(EndLoc, DiagID)
188      << Msg
189      << FixItHint::CreateInsertion(EndLoc, Spelling);
190  } else
191    Diag(Tok, DiagID) << Msg;
192
193  if (SkipToTok != tok::unknown)
194    SkipUntil(SkipToTok);
195  return true;
196}
197
198bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
199  if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
200    ConsumeAnyToken();
201    return false;
202  }
203
204  if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
205      NextToken().is(tok::semi)) {
206    Diag(Tok, diag::err_extraneous_token_before_semi)
207      << PP.getSpelling(Tok)
208      << FixItHint::CreateRemoval(Tok.getLocation());
209    ConsumeAnyToken(); // The ')' or ']'.
210    ConsumeToken(); // The ';'.
211    return false;
212  }
213
214  return ExpectAndConsume(tok::semi, DiagID);
215}
216
217//===----------------------------------------------------------------------===//
218// Error recovery.
219//===----------------------------------------------------------------------===//
220
221/// SkipUntil - Read tokens until we get to the specified token, then consume
222/// it (unless DontConsume is true).  Because we cannot guarantee that the
223/// token will ever occur, this skips to the next token, or to some likely
224/// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
225/// character.
226///
227/// If SkipUntil finds the specified token, it returns true, otherwise it
228/// returns false.
229bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
230                       bool StopAtSemi, bool DontConsume,
231                       bool StopAtCodeCompletion) {
232  // We always want this function to skip at least one token if the first token
233  // isn't T and if not at EOF.
234  bool isFirstTokenSkipped = true;
235  while (1) {
236    // If we found one of the tokens, stop and return true.
237    for (unsigned i = 0; i != NumToks; ++i) {
238      if (Tok.is(Toks[i])) {
239        if (DontConsume) {
240          // Noop, don't consume the token.
241        } else {
242          ConsumeAnyToken();
243        }
244        return true;
245      }
246    }
247
248    switch (Tok.getKind()) {
249    case tok::eof:
250      // Ran out of tokens.
251      return false;
252
253    case tok::code_completion:
254      if (!StopAtCodeCompletion)
255        ConsumeToken();
256      return false;
257
258    case tok::l_paren:
259      // Recursively skip properly-nested parens.
260      ConsumeParen();
261      SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
262      break;
263    case tok::l_square:
264      // Recursively skip properly-nested square brackets.
265      ConsumeBracket();
266      SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
267      break;
268    case tok::l_brace:
269      // Recursively skip properly-nested braces.
270      ConsumeBrace();
271      SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
272      break;
273
274    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
275    // Since the user wasn't looking for this token (if they were, it would
276    // already be handled), this isn't balanced.  If there is a LHS token at a
277    // higher level, we will assume that this matches the unbalanced token
278    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
279    case tok::r_paren:
280      if (ParenCount && !isFirstTokenSkipped)
281        return false;  // Matches something.
282      ConsumeParen();
283      break;
284    case tok::r_square:
285      if (BracketCount && !isFirstTokenSkipped)
286        return false;  // Matches something.
287      ConsumeBracket();
288      break;
289    case tok::r_brace:
290      if (BraceCount && !isFirstTokenSkipped)
291        return false;  // Matches something.
292      ConsumeBrace();
293      break;
294
295    case tok::string_literal:
296    case tok::wide_string_literal:
297      ConsumeStringToken();
298      break;
299    case tok::semi:
300      if (StopAtSemi)
301        return false;
302      // FALL THROUGH.
303    default:
304      // Skip this token.
305      ConsumeToken();
306      break;
307    }
308    isFirstTokenSkipped = false;
309  }
310}
311
312//===----------------------------------------------------------------------===//
313// Scope manipulation
314//===----------------------------------------------------------------------===//
315
316/// EnterScope - Start a new scope.
317void Parser::EnterScope(unsigned ScopeFlags) {
318  if (NumCachedScopes) {
319    Scope *N = ScopeCache[--NumCachedScopes];
320    N->Init(getCurScope(), ScopeFlags);
321    Actions.CurScope = N;
322  } else {
323    Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
324  }
325}
326
327/// ExitScope - Pop a scope off the scope stack.
328void Parser::ExitScope() {
329  assert(getCurScope() && "Scope imbalance!");
330
331  // Inform the actions module that this scope is going away if there are any
332  // decls in it.
333  if (!getCurScope()->decl_empty())
334    Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
335
336  Scope *OldScope = getCurScope();
337  Actions.CurScope = OldScope->getParent();
338
339  if (NumCachedScopes == ScopeCacheSize)
340    delete OldScope;
341  else
342    ScopeCache[NumCachedScopes++] = OldScope;
343}
344
345
346
347
348//===----------------------------------------------------------------------===//
349// C99 6.9: External Definitions.
350//===----------------------------------------------------------------------===//
351
352Parser::~Parser() {
353  // If we still have scopes active, delete the scope tree.
354  delete getCurScope();
355  Actions.CurScope = 0;
356
357  // Free the scope cache.
358  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
359    delete ScopeCache[i];
360
361  // Remove the pragma handlers we installed.
362  PP.RemovePragmaHandler(AlignHandler.get());
363  AlignHandler.reset();
364  PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
365  GCCVisibilityHandler.reset();
366  PP.RemovePragmaHandler(OptionsHandler.get());
367  OptionsHandler.reset();
368  PP.RemovePragmaHandler(PackHandler.get());
369  PackHandler.reset();
370  PP.RemovePragmaHandler(UnusedHandler.get());
371  UnusedHandler.reset();
372  PP.RemovePragmaHandler(WeakHandler.get());
373  WeakHandler.reset();
374
375  if (getLang().OpenCL) {
376    PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
377    OpenCLExtensionHandler.reset();
378    PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
379  }
380
381  PP.RemovePragmaHandler("STDC", FPContractHandler.get());
382  FPContractHandler.reset();
383  PP.clearCodeCompletionHandler();
384}
385
386/// Initialize - Warm up the parser.
387///
388void Parser::Initialize() {
389  // Create the translation unit scope.  Install it as the current scope.
390  assert(getCurScope() == 0 && "A scope is already active?");
391  EnterScope(Scope::DeclScope);
392  Actions.ActOnTranslationUnitScope(getCurScope());
393
394  // Prime the lexer look-ahead.
395  ConsumeToken();
396
397  if (Tok.is(tok::eof) &&
398      !getLang().CPlusPlus)  // Empty source file is an extension in C
399    Diag(Tok, diag::ext_empty_source_file);
400
401  // Initialization for Objective-C context sensitive keywords recognition.
402  // Referenced in Parser::ParseObjCTypeQualifierList.
403  if (getLang().ObjC1) {
404    ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
405    ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
406    ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
407    ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
408    ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
409    ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
410  }
411
412  Ident_final = 0;
413  Ident_override = 0;
414
415  Ident_super = &PP.getIdentifierTable().get("super");
416
417  if (getLang().AltiVec) {
418    Ident_vector = &PP.getIdentifierTable().get("vector");
419    Ident_pixel = &PP.getIdentifierTable().get("pixel");
420  }
421}
422
423/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
424/// action tells us to.  This returns true if the EOF was encountered.
425bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
426
427  while (Tok.is(tok::annot_pragma_unused))
428    HandlePragmaUnused();
429
430  Result = DeclGroupPtrTy();
431  if (Tok.is(tok::eof)) {
432    Actions.ActOnEndOfTranslationUnit();
433    return true;
434  }
435
436  ParsedAttributesWithRange attrs;
437  MaybeParseCXX0XAttributes(attrs);
438  MaybeParseMicrosoftAttributes(attrs);
439
440  Result = ParseExternalDeclaration(attrs);
441  return false;
442}
443
444/// ParseTranslationUnit:
445///       translation-unit: [C99 6.9]
446///         external-declaration
447///         translation-unit external-declaration
448void Parser::ParseTranslationUnit() {
449  Initialize();
450
451  DeclGroupPtrTy Res;
452  while (!ParseTopLevelDecl(Res))
453    /*parse them all*/;
454
455  ExitScope();
456  assert(getCurScope() == 0 && "Scope imbalance!");
457}
458
459/// ParseExternalDeclaration:
460///
461///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
462///         function-definition
463///         declaration
464/// [C++0x] empty-declaration
465/// [GNU]   asm-definition
466/// [GNU]   __extension__ external-declaration
467/// [OBJC]  objc-class-definition
468/// [OBJC]  objc-class-declaration
469/// [OBJC]  objc-alias-declaration
470/// [OBJC]  objc-protocol-definition
471/// [OBJC]  objc-method-definition
472/// [OBJC]  @end
473/// [C++]   linkage-specification
474/// [GNU] asm-definition:
475///         simple-asm-expr ';'
476///
477/// [C++0x] empty-declaration:
478///           ';'
479///
480/// [C++0x/GNU] 'extern' 'template' declaration
481Parser::DeclGroupPtrTy
482Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
483                                 ParsingDeclSpec *DS) {
484  ParenBraceBracketBalancer BalancerRAIIObj(*this);
485
486  Decl *SingleDecl = 0;
487  switch (Tok.getKind()) {
488  case tok::semi:
489    if (!getLang().CPlusPlus0x)
490      Diag(Tok, diag::ext_top_level_semi)
491        << FixItHint::CreateRemoval(Tok.getLocation());
492
493    ConsumeToken();
494    // TODO: Invoke action for top-level semicolon.
495    return DeclGroupPtrTy();
496  case tok::r_brace:
497    Diag(Tok, diag::err_expected_external_declaration);
498    ConsumeBrace();
499    return DeclGroupPtrTy();
500  case tok::eof:
501    Diag(Tok, diag::err_expected_external_declaration);
502    return DeclGroupPtrTy();
503  case tok::kw___extension__: {
504    // __extension__ silences extension warnings in the subexpression.
505    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
506    ConsumeToken();
507    return ParseExternalDeclaration(attrs);
508  }
509  case tok::kw_asm: {
510    ProhibitAttributes(attrs);
511
512    ExprResult Result(ParseSimpleAsm());
513
514    ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
515                     "top-level asm block");
516
517    if (Result.isInvalid())
518      return DeclGroupPtrTy();
519    SingleDecl = Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), Result.get());
520    break;
521  }
522  case tok::at:
523    // @ is not a legal token unless objc is enabled, no need to check for ObjC.
524    /// FIXME: ParseObjCAtDirectives should return a DeclGroup for things like
525    /// @class foo, bar;
526    SingleDecl = ParseObjCAtDirectives();
527    break;
528  case tok::minus:
529  case tok::plus:
530    if (!getLang().ObjC1) {
531      Diag(Tok, diag::err_expected_external_declaration);
532      ConsumeToken();
533      return DeclGroupPtrTy();
534    }
535    SingleDecl = ParseObjCMethodDefinition();
536    break;
537  case tok::code_completion:
538      Actions.CodeCompleteOrdinaryName(getCurScope(),
539                                   ObjCImpDecl? Sema::PCC_ObjCImplementation
540                                              : Sema::PCC_Namespace);
541    ConsumeCodeCompletionToken();
542    return ParseExternalDeclaration(attrs);
543  case tok::kw_using:
544  case tok::kw_namespace:
545  case tok::kw_typedef:
546  case tok::kw_template:
547  case tok::kw_export:    // As in 'export template'
548  case tok::kw_static_assert:
549    // A function definition cannot start with a these keywords.
550    {
551      SourceLocation DeclEnd;
552      StmtVector Stmts(Actions);
553      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
554    }
555
556  case tok::kw_static:
557    // Parse (then ignore) 'static' prior to a template instantiation. This is
558    // a GCC extension that we intentionally do not support.
559    if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
560      Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
561        << 0;
562      SourceLocation DeclEnd;
563      StmtVector Stmts(Actions);
564      return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
565    }
566    goto dont_know;
567
568  case tok::kw_inline:
569    if (getLang().CPlusPlus) {
570      tok::TokenKind NextKind = NextToken().getKind();
571
572      // Inline namespaces. Allowed as an extension even in C++03.
573      if (NextKind == tok::kw_namespace) {
574        SourceLocation DeclEnd;
575        StmtVector Stmts(Actions);
576        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
577      }
578
579      // Parse (then ignore) 'inline' prior to a template instantiation. This is
580      // a GCC extension that we intentionally do not support.
581      if (NextKind == tok::kw_template) {
582        Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
583          << 1;
584        SourceLocation DeclEnd;
585        StmtVector Stmts(Actions);
586        return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
587      }
588    }
589    goto dont_know;
590
591  case tok::kw_extern:
592    if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
593      // Extern templates
594      SourceLocation ExternLoc = ConsumeToken();
595      SourceLocation TemplateLoc = ConsumeToken();
596      SourceLocation DeclEnd;
597      return Actions.ConvertDeclToDeclGroup(
598                  ParseExplicitInstantiation(ExternLoc, TemplateLoc, DeclEnd));
599    }
600    // FIXME: Detect C++ linkage specifications here?
601    goto dont_know;
602
603  default:
604  dont_know:
605    // We can't tell whether this is a function-definition or declaration yet.
606    if (DS) {
607      DS->takeAttributesFrom(attrs);
608      return ParseDeclarationOrFunctionDefinition(*DS);
609    } else {
610      return ParseDeclarationOrFunctionDefinition(attrs);
611    }
612  }
613
614  // This routine returns a DeclGroup, if the thing we parsed only contains a
615  // single decl, convert it now.
616  return Actions.ConvertDeclToDeclGroup(SingleDecl);
617}
618
619/// \brief Determine whether the current token, if it occurs after a
620/// declarator, continues a declaration or declaration list.
621bool Parser::isDeclarationAfterDeclarator() const {
622  return Tok.is(tok::equal) ||      // int X()=  -> not a function def
623    Tok.is(tok::comma) ||           // int X(),  -> not a function def
624    Tok.is(tok::semi)  ||           // int X();  -> not a function def
625    Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
626    Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
627    (getLang().CPlusPlus &&
628     Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
629}
630
631/// \brief Determine whether the current token, if it occurs after a
632/// declarator, indicates the start of a function definition.
633bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
634  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
635  if (Tok.is(tok::l_brace))   // int X() {}
636    return true;
637
638  // Handle K&R C argument lists: int X(f) int f; {}
639  if (!getLang().CPlusPlus &&
640      Declarator.getFunctionTypeInfo().isKNRPrototype())
641    return isDeclarationSpecifier();
642
643  return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
644         Tok.is(tok::kw_try);          // X() try { ... }
645}
646
647/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
648/// a declaration.  We can't tell which we have until we read up to the
649/// compound-statement in function-definition. TemplateParams, if
650/// non-NULL, provides the template parameters when we're parsing a
651/// C++ template-declaration.
652///
653///       function-definition: [C99 6.9.1]
654///         decl-specs      declarator declaration-list[opt] compound-statement
655/// [C90] function-definition: [C99 6.7.1] - implicit int result
656/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
657///
658///       declaration: [C99 6.7]
659///         declaration-specifiers init-declarator-list[opt] ';'
660/// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
661/// [OMP]   threadprivate-directive                              [TODO]
662///
663Parser::DeclGroupPtrTy
664Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
665                                             AccessSpecifier AS) {
666  // Parse the common declaration-specifiers piece.
667  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
668
669  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
670  // declaration-specifiers init-declarator-list[opt] ';'
671  if (Tok.is(tok::semi)) {
672    ConsumeToken();
673    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
674    DS.complete(TheDecl);
675    return Actions.ConvertDeclToDeclGroup(TheDecl);
676  }
677
678  // ObjC2 allows prefix attributes on class interfaces and protocols.
679  // FIXME: This still needs better diagnostics. We should only accept
680  // attributes here, no types, etc.
681  if (getLang().ObjC2 && Tok.is(tok::at)) {
682    SourceLocation AtLoc = ConsumeToken(); // the "@"
683    if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
684        !Tok.isObjCAtKeyword(tok::objc_protocol)) {
685      Diag(Tok, diag::err_objc_unexpected_attr);
686      SkipUntil(tok::semi); // FIXME: better skip?
687      return DeclGroupPtrTy();
688    }
689
690    DS.abort();
691
692    const char *PrevSpec = 0;
693    unsigned DiagID;
694    if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
695      Diag(AtLoc, DiagID) << PrevSpec;
696
697    Decl *TheDecl = 0;
698    if (Tok.isObjCAtKeyword(tok::objc_protocol))
699      TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
700    else
701      TheDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
702    return Actions.ConvertDeclToDeclGroup(TheDecl);
703  }
704
705  // If the declspec consisted only of 'extern' and we have a string
706  // literal following it, this must be a C++ linkage specifier like
707  // 'extern "C"'.
708  if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
709      DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
710      DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
711    Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
712    return Actions.ConvertDeclToDeclGroup(TheDecl);
713  }
714
715  return ParseDeclGroup(DS, Declarator::FileContext, true);
716}
717
718Parser::DeclGroupPtrTy
719Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs,
720                                             AccessSpecifier AS) {
721  ParsingDeclSpec DS(*this);
722  DS.takeAttributesFrom(attrs);
723  return ParseDeclarationOrFunctionDefinition(DS, AS);
724}
725
726/// ParseFunctionDefinition - We parsed and verified that the specified
727/// Declarator is well formed.  If this is a K&R-style function, read the
728/// parameters declaration-list, then start the compound-statement.
729///
730///       function-definition: [C99 6.9.1]
731///         decl-specs      declarator declaration-list[opt] compound-statement
732/// [C90] function-definition: [C99 6.7.1] - implicit int result
733/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
734/// [C++] function-definition: [C++ 8.4]
735///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
736///         function-body
737/// [C++] function-definition: [C++ 8.4]
738///         decl-specifier-seq[opt] declarator function-try-block
739///
740Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
741                                      const ParsedTemplateInfo &TemplateInfo) {
742  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
743
744  // If this is C90 and the declspecs were completely missing, fudge in an
745  // implicit int.  We do this here because this is the only place where
746  // declaration-specifiers are completely optional in the grammar.
747  if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
748    const char *PrevSpec;
749    unsigned DiagID;
750    D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
751                                           D.getIdentifierLoc(),
752                                           PrevSpec, DiagID);
753    D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
754  }
755
756  // If this declaration was formed with a K&R-style identifier list for the
757  // arguments, parse declarations for all of the args next.
758  // int foo(a,b) int a; float b; {}
759  if (FTI.isKNRPrototype())
760    ParseKNRParamDeclarations(D);
761
762  // We should have either an opening brace or, in a C++ constructor,
763  // we may have a colon.
764  if (Tok.isNot(tok::l_brace) &&
765      (!getLang().CPlusPlus ||
766       (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try)))) {
767    Diag(Tok, diag::err_expected_fn_body);
768
769    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
770    SkipUntil(tok::l_brace, true, true);
771
772    // If we didn't find the '{', bail out.
773    if (Tok.isNot(tok::l_brace))
774      return 0;
775  }
776
777  // Enter a scope for the function body.
778  ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
779
780  // Tell the actions module that we have entered a function definition with the
781  // specified Declarator for the function.
782  Decl *Res = TemplateInfo.TemplateParams?
783      Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
784                              MultiTemplateParamsArg(Actions,
785                                          TemplateInfo.TemplateParams->data(),
786                                         TemplateInfo.TemplateParams->size()),
787                                              D)
788    : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
789
790  // Break out of the ParsingDeclarator context before we parse the body.
791  D.complete(Res);
792
793  // Break out of the ParsingDeclSpec context, too.  This const_cast is
794  // safe because we're always the sole owner.
795  D.getMutableDeclSpec().abort();
796
797  if (Tok.is(tok::kw_try))
798    return ParseFunctionTryBlock(Res);
799
800  // If we have a colon, then we're probably parsing a C++
801  // ctor-initializer.
802  if (Tok.is(tok::colon)) {
803    ParseConstructorInitializer(Res);
804
805    // Recover from error.
806    if (!Tok.is(tok::l_brace)) {
807      Actions.ActOnFinishFunctionBody(Res, 0);
808      return Res;
809    }
810  } else
811    Actions.ActOnDefaultCtorInitializers(Res);
812
813  return ParseFunctionStatementBody(Res);
814}
815
816/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
817/// types for a function with a K&R-style identifier list for arguments.
818void Parser::ParseKNRParamDeclarations(Declarator &D) {
819  // We know that the top-level of this declarator is a function.
820  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
821
822  // Enter function-declaration scope, limiting any declarators to the
823  // function prototype scope, including parameter declarators.
824  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
825
826  // Read all the argument declarations.
827  while (isDeclarationSpecifier()) {
828    SourceLocation DSStart = Tok.getLocation();
829
830    // Parse the common declaration-specifiers piece.
831    DeclSpec DS;
832    ParseDeclarationSpecifiers(DS);
833
834    // C99 6.9.1p6: 'each declaration in the declaration list shall have at
835    // least one declarator'.
836    // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
837    // the declarations though.  It's trivial to ignore them, really hard to do
838    // anything else with them.
839    if (Tok.is(tok::semi)) {
840      Diag(DSStart, diag::err_declaration_does_not_declare_param);
841      ConsumeToken();
842      continue;
843    }
844
845    // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
846    // than register.
847    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
848        DS.getStorageClassSpec() != DeclSpec::SCS_register) {
849      Diag(DS.getStorageClassSpecLoc(),
850           diag::err_invalid_storage_class_in_func_decl);
851      DS.ClearStorageClassSpecs();
852    }
853    if (DS.isThreadSpecified()) {
854      Diag(DS.getThreadSpecLoc(),
855           diag::err_invalid_storage_class_in_func_decl);
856      DS.ClearStorageClassSpecs();
857    }
858
859    // Parse the first declarator attached to this declspec.
860    Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
861    ParseDeclarator(ParmDeclarator);
862
863    // Handle the full declarator list.
864    while (1) {
865      // If attributes are present, parse them.
866      MaybeParseGNUAttributes(ParmDeclarator);
867
868      // Ask the actions module to compute the type for this declarator.
869      Decl *Param =
870        Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
871
872      if (Param &&
873          // A missing identifier has already been diagnosed.
874          ParmDeclarator.getIdentifier()) {
875
876        // Scan the argument list looking for the correct param to apply this
877        // type.
878        for (unsigned i = 0; ; ++i) {
879          // C99 6.9.1p6: those declarators shall declare only identifiers from
880          // the identifier list.
881          if (i == FTI.NumArgs) {
882            Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
883              << ParmDeclarator.getIdentifier();
884            break;
885          }
886
887          if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
888            // Reject redefinitions of parameters.
889            if (FTI.ArgInfo[i].Param) {
890              Diag(ParmDeclarator.getIdentifierLoc(),
891                   diag::err_param_redefinition)
892                 << ParmDeclarator.getIdentifier();
893            } else {
894              FTI.ArgInfo[i].Param = Param;
895            }
896            break;
897          }
898        }
899      }
900
901      // If we don't have a comma, it is either the end of the list (a ';') or
902      // an error, bail out.
903      if (Tok.isNot(tok::comma))
904        break;
905
906      // Consume the comma.
907      ConsumeToken();
908
909      // Parse the next declarator.
910      ParmDeclarator.clear();
911      ParseDeclarator(ParmDeclarator);
912    }
913
914    if (Tok.is(tok::semi)) {
915      ConsumeToken();
916    } else {
917      Diag(Tok, diag::err_parse_error);
918      // Skip to end of block or statement
919      SkipUntil(tok::semi, true);
920      if (Tok.is(tok::semi))
921        ConsumeToken();
922    }
923  }
924
925  // The actions module must verify that all arguments were declared.
926  Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
927}
928
929
930/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
931/// allowed to be a wide string, and is not subject to character translation.
932///
933/// [GNU] asm-string-literal:
934///         string-literal
935///
936Parser::ExprResult Parser::ParseAsmStringLiteral() {
937  if (!isTokenStringLiteral()) {
938    Diag(Tok, diag::err_expected_string_literal);
939    return ExprError();
940  }
941
942  ExprResult Res(ParseStringLiteralExpression());
943  if (Res.isInvalid()) return move(Res);
944
945  // TODO: Diagnose: wide string literal in 'asm'
946
947  return move(Res);
948}
949
950/// ParseSimpleAsm
951///
952/// [GNU] simple-asm-expr:
953///         'asm' '(' asm-string-literal ')'
954///
955Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
956  assert(Tok.is(tok::kw_asm) && "Not an asm!");
957  SourceLocation Loc = ConsumeToken();
958
959  if (Tok.is(tok::kw_volatile)) {
960    // Remove from the end of 'asm' to the end of 'volatile'.
961    SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
962                             PP.getLocForEndOfToken(Tok.getLocation()));
963
964    Diag(Tok, diag::warn_file_asm_volatile)
965      << FixItHint::CreateRemoval(RemovalRange);
966    ConsumeToken();
967  }
968
969  if (Tok.isNot(tok::l_paren)) {
970    Diag(Tok, diag::err_expected_lparen_after) << "asm";
971    return ExprError();
972  }
973
974  Loc = ConsumeParen();
975
976  ExprResult Result(ParseAsmStringLiteral());
977
978  if (Result.isInvalid()) {
979    SkipUntil(tok::r_paren, true, true);
980    if (EndLoc)
981      *EndLoc = Tok.getLocation();
982    ConsumeAnyToken();
983  } else {
984    Loc = MatchRHSPunctuation(tok::r_paren, Loc);
985    if (EndLoc)
986      *EndLoc = Loc;
987  }
988
989  return move(Result);
990}
991
992/// TryAnnotateTypeOrScopeToken - If the current token position is on a
993/// typename (possibly qualified in C++) or a C++ scope specifier not followed
994/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
995/// with a single annotation token representing the typename or C++ scope
996/// respectively.
997/// This simplifies handling of C++ scope specifiers and allows efficient
998/// backtracking without the need to re-parse and resolve nested-names and
999/// typenames.
1000/// It will mainly be called when we expect to treat identifiers as typenames
1001/// (if they are typenames). For example, in C we do not expect identifiers
1002/// inside expressions to be treated as typenames so it will not be called
1003/// for expressions in C.
1004/// The benefit for C/ObjC is that a typename will be annotated and
1005/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1006/// will not be called twice, once to check whether we have a declaration
1007/// specifier, and another one to get the actual type inside
1008/// ParseDeclarationSpecifiers).
1009///
1010/// This returns true if an error occurred.
1011///
1012/// Note that this routine emits an error if you call it with ::new or ::delete
1013/// as the current tokens, so only call it in contexts where these are invalid.
1014bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext) {
1015  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1016          || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) &&
1017         "Cannot be a type or scope token!");
1018
1019  if (Tok.is(tok::kw_typename)) {
1020    // Parse a C++ typename-specifier, e.g., "typename T::type".
1021    //
1022    //   typename-specifier:
1023    //     'typename' '::' [opt] nested-name-specifier identifier
1024    //     'typename' '::' [opt] nested-name-specifier template [opt]
1025    //            simple-template-id
1026    SourceLocation TypenameLoc = ConsumeToken();
1027    CXXScopeSpec SS;
1028    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), false))
1029      return true;
1030    if (!SS.isSet()) {
1031      Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1032      return true;
1033    }
1034
1035    TypeResult Ty;
1036    if (Tok.is(tok::identifier)) {
1037      // FIXME: check whether the next token is '<', first!
1038      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1039                                     *Tok.getIdentifierInfo(),
1040                                     Tok.getLocation());
1041    } else if (Tok.is(tok::annot_template_id)) {
1042      TemplateIdAnnotation *TemplateId
1043        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1044      if (TemplateId->Kind == TNK_Function_template) {
1045        Diag(Tok, diag::err_typename_refers_to_non_type_template)
1046          << Tok.getAnnotationRange();
1047        return true;
1048      }
1049
1050      AnnotateTemplateIdTokenAsType(0);
1051      assert(Tok.is(tok::annot_typename) &&
1052             "AnnotateTemplateIdTokenAsType isn't working properly");
1053      if (Tok.getAnnotationValue())
1054        Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1055                                       SourceLocation(),
1056                                       getTypeAnnotation(Tok));
1057      else
1058        Ty = true;
1059    } else {
1060      Diag(Tok, diag::err_expected_type_name_after_typename)
1061        << SS.getRange();
1062      return true;
1063    }
1064
1065    SourceLocation EndLoc = Tok.getLastLoc();
1066    Tok.setKind(tok::annot_typename);
1067    setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1068    Tok.setAnnotationEndLoc(EndLoc);
1069    Tok.setLocation(TypenameLoc);
1070    PP.AnnotateCachedTokens(Tok);
1071    return false;
1072  }
1073
1074  // Remembers whether the token was originally a scope annotation.
1075  bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1076
1077  CXXScopeSpec SS;
1078  if (getLang().CPlusPlus)
1079    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1080      return true;
1081
1082  if (Tok.is(tok::identifier)) {
1083    // Determine whether the identifier is a type name.
1084    if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1085                                            Tok.getLocation(), getCurScope(),
1086                                            &SS, false,
1087                                            NextToken().is(tok::period))) {
1088      // This is a typename. Replace the current token in-place with an
1089      // annotation type token.
1090      Tok.setKind(tok::annot_typename);
1091      setTypeAnnotation(Tok, Ty);
1092      Tok.setAnnotationEndLoc(Tok.getLocation());
1093      if (SS.isNotEmpty()) // it was a C++ qualified type name.
1094        Tok.setLocation(SS.getBeginLoc());
1095
1096      // In case the tokens were cached, have Preprocessor replace
1097      // them with the annotation token.
1098      PP.AnnotateCachedTokens(Tok);
1099      return false;
1100    }
1101
1102    if (!getLang().CPlusPlus) {
1103      // If we're in C, we can't have :: tokens at all (the lexer won't return
1104      // them).  If the identifier is not a type, then it can't be scope either,
1105      // just early exit.
1106      return false;
1107    }
1108
1109    // If this is a template-id, annotate with a template-id or type token.
1110    if (NextToken().is(tok::less)) {
1111      TemplateTy Template;
1112      UnqualifiedId TemplateName;
1113      TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1114      bool MemberOfUnknownSpecialization;
1115      if (TemplateNameKind TNK
1116          = Actions.isTemplateName(getCurScope(), SS,
1117                                   /*hasTemplateKeyword=*/false, TemplateName,
1118                                   /*ObjectType=*/ ParsedType(),
1119                                   EnteringContext,
1120                                   Template, MemberOfUnknownSpecialization)) {
1121        // Consume the identifier.
1122        ConsumeToken();
1123        if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName)) {
1124          // If an unrecoverable error occurred, we need to return true here,
1125          // because the token stream is in a damaged state.  We may not return
1126          // a valid identifier.
1127          return true;
1128        }
1129      }
1130    }
1131
1132    // The current token, which is either an identifier or a
1133    // template-id, is not part of the annotation. Fall through to
1134    // push that token back into the stream and complete the C++ scope
1135    // specifier annotation.
1136  }
1137
1138  if (Tok.is(tok::annot_template_id)) {
1139    TemplateIdAnnotation *TemplateId
1140      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1141    if (TemplateId->Kind == TNK_Type_template) {
1142      // A template-id that refers to a type was parsed into a
1143      // template-id annotation in a context where we weren't allowed
1144      // to produce a type annotation token. Update the template-id
1145      // annotation token to a type annotation token now.
1146      AnnotateTemplateIdTokenAsType(&SS);
1147      return false;
1148    }
1149  }
1150
1151  if (SS.isEmpty())
1152    return false;
1153
1154  // A C++ scope specifier that isn't followed by a typename.
1155  // Push the current token back into the token stream (or revert it if it is
1156  // cached) and use an annotation scope token for current token.
1157  if (PP.isBacktrackEnabled())
1158    PP.RevertCachedTokens(1);
1159  else
1160    PP.EnterToken(Tok);
1161  Tok.setKind(tok::annot_cxxscope);
1162  Tok.setAnnotationValue(SS.getScopeRep());
1163  Tok.setAnnotationRange(SS.getRange());
1164
1165  // In case the tokens were cached, have Preprocessor replace them
1166  // with the annotation token.  We don't need to do this if we've
1167  // just reverted back to the state we were in before being called.
1168  if (!wasScopeAnnotation)
1169    PP.AnnotateCachedTokens(Tok);
1170  return false;
1171}
1172
1173/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1174/// annotates C++ scope specifiers and template-ids.  This returns
1175/// true if the token was annotated or there was an error that could not be
1176/// recovered from.
1177///
1178/// Note that this routine emits an error if you call it with ::new or ::delete
1179/// as the current tokens, so only call it in contexts where these are invalid.
1180bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1181  assert(getLang().CPlusPlus &&
1182         "Call sites of this function should be guarded by checking for C++");
1183  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1184         "Cannot be a type or scope token!");
1185
1186  CXXScopeSpec SS;
1187  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1188    return true;
1189  if (SS.isEmpty())
1190    return false;
1191
1192  // Push the current token back into the token stream (or revert it if it is
1193  // cached) and use an annotation scope token for current token.
1194  if (PP.isBacktrackEnabled())
1195    PP.RevertCachedTokens(1);
1196  else
1197    PP.EnterToken(Tok);
1198  Tok.setKind(tok::annot_cxxscope);
1199  Tok.setAnnotationValue(SS.getScopeRep());
1200  Tok.setAnnotationRange(SS.getRange());
1201
1202  // In case the tokens were cached, have Preprocessor replace them with the
1203  // annotation token.
1204  PP.AnnotateCachedTokens(Tok);
1205  return false;
1206}
1207
1208bool Parser::isTokenEqualOrMistypedEqualEqual(unsigned DiagID) {
1209  if (Tok.is(tok::equalequal)) {
1210    // We have '==' in a context that we would expect a '='.
1211    // The user probably made a typo, intending to type '='. Emit diagnostic,
1212    // fixit hint to turn '==' -> '=' and continue as if the user typed '='.
1213    Diag(Tok, DiagID)
1214      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
1215                                      getTokenSimpleSpelling(tok::equal));
1216    return true;
1217  }
1218
1219  return Tok.is(tok::equal);
1220}
1221
1222void Parser::CodeCompletionRecovery() {
1223  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1224    if (S->getFlags() & Scope::FnScope) {
1225      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1226      return;
1227    }
1228
1229    if (S->getFlags() & Scope::ClassScope) {
1230      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1231      return;
1232    }
1233  }
1234
1235  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1236}
1237
1238// Anchor the Parser::FieldCallback vtable to this translation unit.
1239// We use a spurious method instead of the destructor because
1240// destroying FieldCallbacks can actually be slightly
1241// performance-sensitive.
1242void Parser::FieldCallback::_anchor() {
1243}
1244
1245// Code-completion pass-through functions
1246
1247void Parser::CodeCompleteDirective(bool InConditional) {
1248  Actions.CodeCompletePreprocessorDirective(InConditional);
1249}
1250
1251void Parser::CodeCompleteInConditionalExclusion() {
1252  Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1253}
1254
1255void Parser::CodeCompleteMacroName(bool IsDefinition) {
1256  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1257}
1258
1259void Parser::CodeCompletePreprocessorExpression() {
1260  Actions.CodeCompletePreprocessorExpression();
1261}
1262
1263void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1264                                       MacroInfo *MacroInfo,
1265                                       unsigned ArgumentIndex) {
1266  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1267                                                ArgumentIndex);
1268}
1269
1270void Parser::CodeCompleteNaturalLanguage() {
1271  Actions.CodeCompleteNaturalLanguage();
1272}
1273