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