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