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_nopartial = nullptr;
495 
496   Ident__except = nullptr;
497 
498   Ident__exception_code = Ident__exception_info = nullptr;
499   Ident__abnormal_termination = Ident___exception_code = nullptr;
500   Ident___exception_info = Ident___abnormal_termination = nullptr;
501   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
502   Ident_AbnormalTermination = nullptr;
503 
504   if(getLangOpts().Borland) {
505     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
506     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
507     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
508     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
509     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
510     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
511     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
512     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
513     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
514 
515     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
516     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
517     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
518     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
519     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
520     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
521     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
522     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
523     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
524   }
525 
526   Actions.Initialize();
527 
528   // Prime the lexer look-ahead.
529   ConsumeToken();
530 }
531 
532 void Parser::LateTemplateParserCleanupCallback(void *P) {
533   // While this RAII helper doesn't bracket any actual work, the destructor will
534   // clean up annotations that were created during ActOnEndOfTranslationUnit
535   // when incremental processing is enabled.
536   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
537 }
538 
539 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
540 /// action tells us to.  This returns true if the EOF was encountered.
541 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
542   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
543 
544   // Skip over the EOF token, flagging end of previous input for incremental
545   // processing
546   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
547     ConsumeToken();
548 
549   Result = nullptr;
550   switch (Tok.getKind()) {
551   case tok::annot_pragma_unused:
552     HandlePragmaUnused();
553     return false;
554 
555   case tok::annot_module_include:
556     Actions.ActOnModuleInclude(Tok.getLocation(),
557                                reinterpret_cast<Module *>(
558                                    Tok.getAnnotationValue()));
559     ConsumeToken();
560     return false;
561 
562   case tok::annot_module_begin:
563     Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
564                                                     Tok.getAnnotationValue()));
565     ConsumeToken();
566     return false;
567 
568   case tok::annot_module_end:
569     Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
570                                                   Tok.getAnnotationValue()));
571     ConsumeToken();
572     return false;
573 
574   case tok::eof:
575     // Late template parsing can begin.
576     if (getLangOpts().DelayedTemplateParsing)
577       Actions.SetLateTemplateParser(LateTemplateParserCallback,
578                                     PP.isIncrementalProcessingEnabled() ?
579                                     LateTemplateParserCleanupCallback : nullptr,
580                                     this);
581     if (!PP.isIncrementalProcessingEnabled())
582       Actions.ActOnEndOfTranslationUnit();
583     //else don't tell Sema that we ended parsing: more input might come.
584     return true;
585 
586   default:
587     break;
588   }
589 
590   ParsedAttributesWithRange attrs(AttrFactory);
591   MaybeParseCXX11Attributes(attrs);
592   MaybeParseMicrosoftAttributes(attrs);
593 
594   Result = ParseExternalDeclaration(attrs);
595   return false;
596 }
597 
598 /// ParseExternalDeclaration:
599 ///
600 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
601 ///         function-definition
602 ///         declaration
603 /// [GNU]   asm-definition
604 /// [GNU]   __extension__ external-declaration
605 /// [OBJC]  objc-class-definition
606 /// [OBJC]  objc-class-declaration
607 /// [OBJC]  objc-alias-declaration
608 /// [OBJC]  objc-protocol-definition
609 /// [OBJC]  objc-method-definition
610 /// [OBJC]  @end
611 /// [C++]   linkage-specification
612 /// [GNU] asm-definition:
613 ///         simple-asm-expr ';'
614 /// [C++11] empty-declaration
615 /// [C++11] attribute-declaration
616 ///
617 /// [C++11] empty-declaration:
618 ///           ';'
619 ///
620 /// [C++0x/GNU] 'extern' 'template' declaration
621 Parser::DeclGroupPtrTy
622 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
623                                  ParsingDeclSpec *DS) {
624   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
625   ParenBraceBracketBalancer BalancerRAIIObj(*this);
626 
627   if (PP.isCodeCompletionReached()) {
628     cutOffParsing();
629     return nullptr;
630   }
631 
632   Decl *SingleDecl = nullptr;
633   switch (Tok.getKind()) {
634   case tok::annot_pragma_vis:
635     HandlePragmaVisibility();
636     return nullptr;
637   case tok::annot_pragma_pack:
638     HandlePragmaPack();
639     return nullptr;
640   case tok::annot_pragma_msstruct:
641     HandlePragmaMSStruct();
642     return nullptr;
643   case tok::annot_pragma_align:
644     HandlePragmaAlign();
645     return nullptr;
646   case tok::annot_pragma_weak:
647     HandlePragmaWeak();
648     return nullptr;
649   case tok::annot_pragma_weakalias:
650     HandlePragmaWeakAlias();
651     return nullptr;
652   case tok::annot_pragma_redefine_extname:
653     HandlePragmaRedefineExtname();
654     return nullptr;
655   case tok::annot_pragma_fp_contract:
656     HandlePragmaFPContract();
657     return nullptr;
658   case tok::annot_pragma_opencl_extension:
659     HandlePragmaOpenCLExtension();
660     return nullptr;
661   case tok::annot_pragma_openmp:
662     return ParseOpenMPDeclarativeDirective();
663   case tok::annot_pragma_ms_pointers_to_members:
664     HandlePragmaMSPointersToMembers();
665     return nullptr;
666   case tok::annot_pragma_ms_vtordisp:
667     HandlePragmaMSVtorDisp();
668     return nullptr;
669   case tok::annot_pragma_ms_pragma:
670     HandlePragmaMSPragma();
671     return nullptr;
672   case tok::annot_pragma_dump:
673     HandlePragmaDump();
674     return nullptr;
675   case tok::semi:
676     // Either a C++11 empty-declaration or attribute-declaration.
677     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
678                                                attrs.getList(),
679                                                Tok.getLocation());
680     ConsumeExtraSemi(OutsideFunction);
681     break;
682   case tok::r_brace:
683     Diag(Tok, diag::err_extraneous_closing_brace);
684     ConsumeBrace();
685     return nullptr;
686   case tok::eof:
687     Diag(Tok, diag::err_expected_external_declaration);
688     return nullptr;
689   case tok::kw___extension__: {
690     // __extension__ silences extension warnings in the subexpression.
691     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
692     ConsumeToken();
693     return ParseExternalDeclaration(attrs);
694   }
695   case tok::kw_asm: {
696     ProhibitAttributes(attrs);
697 
698     SourceLocation StartLoc = Tok.getLocation();
699     SourceLocation EndLoc;
700 
701     ExprResult Result(ParseSimpleAsm(&EndLoc));
702 
703     // Check if GNU-style InlineAsm is disabled.
704     // Empty asm string is allowed because it will not introduce
705     // any assembly code.
706     if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
707       const auto *SL = cast<StringLiteral>(Result.get());
708       if (!SL->getString().trim().empty())
709         Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
710     }
711 
712     ExpectAndConsume(tok::semi, diag::err_expected_after,
713                      "top-level asm block");
714 
715     if (Result.isInvalid())
716       return nullptr;
717     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
718     break;
719   }
720   case tok::at:
721     return ParseObjCAtDirectives();
722   case tok::minus:
723   case tok::plus:
724     if (!getLangOpts().ObjC1) {
725       Diag(Tok, diag::err_expected_external_declaration);
726       ConsumeToken();
727       return nullptr;
728     }
729     SingleDecl = ParseObjCMethodDefinition();
730     break;
731   case tok::code_completion:
732       Actions.CodeCompleteOrdinaryName(getCurScope(),
733                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
734                                               : Sema::PCC_Namespace);
735     cutOffParsing();
736     return nullptr;
737   case tok::kw_using:
738   case tok::kw_namespace:
739   case tok::kw_typedef:
740   case tok::kw_template:
741   case tok::kw_export:    // As in 'export template'
742   case tok::kw_static_assert:
743   case tok::kw__Static_assert:
744     // A function definition cannot start with any of these keywords.
745     {
746       SourceLocation DeclEnd;
747       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
748     }
749 
750   case tok::kw_static:
751     // Parse (then ignore) 'static' prior to a template instantiation. This is
752     // a GCC extension that we intentionally do not support.
753     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
754       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
755         << 0;
756       SourceLocation DeclEnd;
757       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
758     }
759     goto dont_know;
760 
761   case tok::kw_inline:
762     if (getLangOpts().CPlusPlus) {
763       tok::TokenKind NextKind = NextToken().getKind();
764 
765       // Inline namespaces. Allowed as an extension even in C++03.
766       if (NextKind == tok::kw_namespace) {
767         SourceLocation DeclEnd;
768         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
769       }
770 
771       // Parse (then ignore) 'inline' prior to a template instantiation. This is
772       // a GCC extension that we intentionally do not support.
773       if (NextKind == tok::kw_template) {
774         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
775           << 1;
776         SourceLocation DeclEnd;
777         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
778       }
779     }
780     goto dont_know;
781 
782   case tok::kw_extern:
783     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
784       // Extern templates
785       SourceLocation ExternLoc = ConsumeToken();
786       SourceLocation TemplateLoc = ConsumeToken();
787       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
788              diag::warn_cxx98_compat_extern_template :
789              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
790       SourceLocation DeclEnd;
791       return Actions.ConvertDeclToDeclGroup(
792                   ParseExplicitInstantiation(Declarator::FileContext,
793                                              ExternLoc, TemplateLoc, DeclEnd));
794     }
795     goto dont_know;
796 
797   case tok::kw___if_exists:
798   case tok::kw___if_not_exists:
799     ParseMicrosoftIfExistsExternalDeclaration();
800     return nullptr;
801 
802   default:
803   dont_know:
804     // We can't tell whether this is a function-definition or declaration yet.
805     return ParseDeclarationOrFunctionDefinition(attrs, DS);
806   }
807 
808   // This routine returns a DeclGroup, if the thing we parsed only contains a
809   // single decl, convert it now.
810   return Actions.ConvertDeclToDeclGroup(SingleDecl);
811 }
812 
813 /// \brief Determine whether the current token, if it occurs after a
814 /// declarator, continues a declaration or declaration list.
815 bool Parser::isDeclarationAfterDeclarator() {
816   // Check for '= delete' or '= default'
817   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
818     const Token &KW = NextToken();
819     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
820       return false;
821   }
822 
823   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
824     Tok.is(tok::comma) ||           // int X(),  -> not a function def
825     Tok.is(tok::semi)  ||           // int X();  -> not a function def
826     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
827     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
828     (getLangOpts().CPlusPlus &&
829      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
830 }
831 
832 /// \brief Determine whether the current token, if it occurs after a
833 /// declarator, indicates the start of a function definition.
834 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
835   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
836   if (Tok.is(tok::l_brace))   // int X() {}
837     return true;
838 
839   // Handle K&R C argument lists: int X(f) int f; {}
840   if (!getLangOpts().CPlusPlus &&
841       Declarator.getFunctionTypeInfo().isKNRPrototype())
842     return isDeclarationSpecifier();
843 
844   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
845     const Token &KW = NextToken();
846     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
847   }
848 
849   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
850          Tok.is(tok::kw_try);          // X() try { ... }
851 }
852 
853 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
854 /// a declaration.  We can't tell which we have until we read up to the
855 /// compound-statement in function-definition. TemplateParams, if
856 /// non-NULL, provides the template parameters when we're parsing a
857 /// C++ template-declaration.
858 ///
859 ///       function-definition: [C99 6.9.1]
860 ///         decl-specs      declarator declaration-list[opt] compound-statement
861 /// [C90] function-definition: [C99 6.7.1] - implicit int result
862 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
863 ///
864 ///       declaration: [C99 6.7]
865 ///         declaration-specifiers init-declarator-list[opt] ';'
866 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
867 /// [OMP]   threadprivate-directive                              [TODO]
868 ///
869 Parser::DeclGroupPtrTy
870 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
871                                        ParsingDeclSpec &DS,
872                                        AccessSpecifier AS) {
873   // Parse the common declaration-specifiers piece.
874   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
875 
876   // If we had a free-standing type definition with a missing semicolon, we
877   // may get this far before the problem becomes obvious.
878   if (DS.hasTagDefinition() &&
879       DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
880     return nullptr;
881 
882   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
883   // declaration-specifiers init-declarator-list[opt] ';'
884   if (Tok.is(tok::semi)) {
885     ProhibitAttributes(attrs);
886     ConsumeToken();
887     RecordDecl *AnonRecord = nullptr;
888     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
889                                                        DS, AnonRecord);
890     DS.complete(TheDecl);
891     if (AnonRecord) {
892       Decl* decls[] = {AnonRecord, TheDecl};
893       return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
894     }
895     return Actions.ConvertDeclToDeclGroup(TheDecl);
896   }
897 
898   DS.takeAttributesFrom(attrs);
899 
900   // ObjC2 allows prefix attributes on class interfaces and protocols.
901   // FIXME: This still needs better diagnostics. We should only accept
902   // attributes here, no types, etc.
903   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
904     SourceLocation AtLoc = ConsumeToken(); // the "@"
905     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
906         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
907       Diag(Tok, diag::err_objc_unexpected_attr);
908       SkipUntil(tok::semi); // FIXME: better skip?
909       return nullptr;
910     }
911 
912     DS.abort();
913 
914     const char *PrevSpec = nullptr;
915     unsigned DiagID;
916     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
917                            Actions.getASTContext().getPrintingPolicy()))
918       Diag(AtLoc, DiagID) << PrevSpec;
919 
920     if (Tok.isObjCAtKeyword(tok::objc_protocol))
921       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
922 
923     return Actions.ConvertDeclToDeclGroup(
924             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
925   }
926 
927   // If the declspec consisted only of 'extern' and we have a string
928   // literal following it, this must be a C++ linkage specifier like
929   // 'extern "C"'.
930   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
931       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
932       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
933     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
934     return Actions.ConvertDeclToDeclGroup(TheDecl);
935   }
936 
937   return ParseDeclGroup(DS, Declarator::FileContext);
938 }
939 
940 Parser::DeclGroupPtrTy
941 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
942                                              ParsingDeclSpec *DS,
943                                              AccessSpecifier AS) {
944   if (DS) {
945     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
946   } else {
947     ParsingDeclSpec PDS(*this);
948     // Must temporarily exit the objective-c container scope for
949     // parsing c constructs and re-enter objc container scope
950     // afterwards.
951     ObjCDeclContextSwitch ObjCDC(*this);
952 
953     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
954   }
955 }
956 
957 /// ParseFunctionDefinition - We parsed and verified that the specified
958 /// Declarator is well formed.  If this is a K&R-style function, read the
959 /// parameters declaration-list, then start the compound-statement.
960 ///
961 ///       function-definition: [C99 6.9.1]
962 ///         decl-specs      declarator declaration-list[opt] compound-statement
963 /// [C90] function-definition: [C99 6.7.1] - implicit int result
964 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
965 /// [C++] function-definition: [C++ 8.4]
966 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
967 ///         function-body
968 /// [C++] function-definition: [C++ 8.4]
969 ///         decl-specifier-seq[opt] declarator function-try-block
970 ///
971 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
972                                       const ParsedTemplateInfo &TemplateInfo,
973                                       LateParsedAttrList *LateParsedAttrs) {
974   // Poison SEH identifiers so they are flagged as illegal in function bodies.
975   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
976   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
977 
978   // If this is C90 and the declspecs were completely missing, fudge in an
979   // implicit int.  We do this here because this is the only place where
980   // declaration-specifiers are completely optional in the grammar.
981   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
982     const char *PrevSpec;
983     unsigned DiagID;
984     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
985     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
986                                            D.getIdentifierLoc(),
987                                            PrevSpec, DiagID,
988                                            Policy);
989     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
990   }
991 
992   // If this declaration was formed with a K&R-style identifier list for the
993   // arguments, parse declarations for all of the args next.
994   // int foo(a,b) int a; float b; {}
995   if (FTI.isKNRPrototype())
996     ParseKNRParamDeclarations(D);
997 
998   // We should have either an opening brace or, in a C++ constructor,
999   // we may have a colon.
1000   if (Tok.isNot(tok::l_brace) &&
1001       (!getLangOpts().CPlusPlus ||
1002        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1003         Tok.isNot(tok::equal)))) {
1004     Diag(Tok, diag::err_expected_fn_body);
1005 
1006     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1007     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1008 
1009     // If we didn't find the '{', bail out.
1010     if (Tok.isNot(tok::l_brace))
1011       return nullptr;
1012   }
1013 
1014   // Check to make sure that any normal attributes are allowed to be on
1015   // a definition.  Late parsed attributes are checked at the end.
1016   if (Tok.isNot(tok::equal)) {
1017     AttributeList *DtorAttrs = D.getAttributes();
1018     while (DtorAttrs) {
1019       if (DtorAttrs->isKnownToGCC() &&
1020           !DtorAttrs->isCXX11Attribute()) {
1021         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
1022           << DtorAttrs->getName();
1023       }
1024       DtorAttrs = DtorAttrs->getNext();
1025     }
1026   }
1027 
1028   // In delayed template parsing mode, for function template we consume the
1029   // tokens and store them for late parsing at the end of the translation unit.
1030   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1031       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1032       Actions.canDelayFunctionBody(D)) {
1033     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1034 
1035     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1036     Scope *ParentScope = getCurScope()->getParent();
1037 
1038     D.setFunctionDefinitionKind(FDK_Definition);
1039     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1040                                         TemplateParameterLists);
1041     D.complete(DP);
1042     D.getMutableDeclSpec().abort();
1043 
1044     CachedTokens Toks;
1045     LexTemplateFunctionForLateParsing(Toks);
1046 
1047     if (DP) {
1048       FunctionDecl *FnD = DP->getAsFunction();
1049       Actions.CheckForFunctionRedefinition(FnD);
1050       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1051     }
1052     return DP;
1053   }
1054   else if (CurParsedObjCImpl &&
1055            !TemplateInfo.TemplateParams &&
1056            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1057             Tok.is(tok::colon)) &&
1058       Actions.CurContext->isTranslationUnit()) {
1059     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1060     Scope *ParentScope = getCurScope()->getParent();
1061 
1062     D.setFunctionDefinitionKind(FDK_Definition);
1063     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1064                                               MultiTemplateParamsArg());
1065     D.complete(FuncDecl);
1066     D.getMutableDeclSpec().abort();
1067     if (FuncDecl) {
1068       // Consume the tokens and store them for later parsing.
1069       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1070       CurParsedObjCImpl->HasCFunction = true;
1071       return FuncDecl;
1072     }
1073     // FIXME: Should we really fall through here?
1074   }
1075 
1076   // Enter a scope for the function body.
1077   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1078 
1079   // Tell the actions module that we have entered a function definition with the
1080   // specified Declarator for the function.
1081   Sema::SkipBodyInfo SkipBody;
1082   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1083                                               TemplateInfo.TemplateParams
1084                                                   ? *TemplateInfo.TemplateParams
1085                                                   : MultiTemplateParamsArg(),
1086                                               &SkipBody);
1087 
1088   if (SkipBody.ShouldSkip) {
1089     SkipFunctionBody();
1090     return Res;
1091   }
1092 
1093   // Break out of the ParsingDeclarator context before we parse the body.
1094   D.complete(Res);
1095 
1096   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1097   // safe because we're always the sole owner.
1098   D.getMutableDeclSpec().abort();
1099 
1100   if (TryConsumeToken(tok::equal)) {
1101     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1102 
1103     bool Delete = false;
1104     SourceLocation KWLoc;
1105     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1106       Diag(KWLoc, getLangOpts().CPlusPlus11
1107                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1108                       : diag::ext_defaulted_deleted_function)
1109         << 1 /* deleted */;
1110       Actions.SetDeclDeleted(Res, KWLoc);
1111       Delete = true;
1112     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1113       Diag(KWLoc, getLangOpts().CPlusPlus11
1114                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1115                       : diag::ext_defaulted_deleted_function)
1116         << 0 /* defaulted */;
1117       Actions.SetDeclDefaulted(Res, KWLoc);
1118     } else {
1119       llvm_unreachable("function definition after = not 'delete' or 'default'");
1120     }
1121 
1122     if (Tok.is(tok::comma)) {
1123       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1124         << Delete;
1125       SkipUntil(tok::semi);
1126     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1127                                 Delete ? "delete" : "default")) {
1128       SkipUntil(tok::semi);
1129     }
1130 
1131     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1132     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1133     return Res;
1134   }
1135 
1136   if (Tok.is(tok::kw_try))
1137     return ParseFunctionTryBlock(Res, BodyScope);
1138 
1139   // If we have a colon, then we're probably parsing a C++
1140   // ctor-initializer.
1141   if (Tok.is(tok::colon)) {
1142     ParseConstructorInitializer(Res);
1143 
1144     // Recover from error.
1145     if (!Tok.is(tok::l_brace)) {
1146       BodyScope.Exit();
1147       Actions.ActOnFinishFunctionBody(Res, nullptr);
1148       return Res;
1149     }
1150   } else
1151     Actions.ActOnDefaultCtorInitializers(Res);
1152 
1153   // Late attributes are parsed in the same scope as the function body.
1154   if (LateParsedAttrs)
1155     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1156 
1157   return ParseFunctionStatementBody(Res, BodyScope);
1158 }
1159 
1160 void Parser::SkipFunctionBody() {
1161   if (Tok.is(tok::equal)) {
1162     SkipUntil(tok::semi);
1163     return;
1164   }
1165 
1166   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1167   if (IsFunctionTryBlock)
1168     ConsumeToken();
1169 
1170   CachedTokens Skipped;
1171   if (ConsumeAndStoreFunctionPrologue(Skipped))
1172     SkipMalformedDecl();
1173   else {
1174     SkipUntil(tok::r_brace);
1175     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1176       SkipUntil(tok::l_brace);
1177       SkipUntil(tok::r_brace);
1178     }
1179   }
1180 }
1181 
1182 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1183 /// types for a function with a K&R-style identifier list for arguments.
1184 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1185   // We know that the top-level of this declarator is a function.
1186   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1187 
1188   // Enter function-declaration scope, limiting any declarators to the
1189   // function prototype scope, including parameter declarators.
1190   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1191                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1192 
1193   // Read all the argument declarations.
1194   while (isDeclarationSpecifier()) {
1195     SourceLocation DSStart = Tok.getLocation();
1196 
1197     // Parse the common declaration-specifiers piece.
1198     DeclSpec DS(AttrFactory);
1199     ParseDeclarationSpecifiers(DS);
1200 
1201     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1202     // least one declarator'.
1203     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1204     // the declarations though.  It's trivial to ignore them, really hard to do
1205     // anything else with them.
1206     if (TryConsumeToken(tok::semi)) {
1207       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1208       continue;
1209     }
1210 
1211     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1212     // than register.
1213     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1214         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1215       Diag(DS.getStorageClassSpecLoc(),
1216            diag::err_invalid_storage_class_in_func_decl);
1217       DS.ClearStorageClassSpecs();
1218     }
1219     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1220       Diag(DS.getThreadStorageClassSpecLoc(),
1221            diag::err_invalid_storage_class_in_func_decl);
1222       DS.ClearStorageClassSpecs();
1223     }
1224 
1225     // Parse the first declarator attached to this declspec.
1226     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1227     ParseDeclarator(ParmDeclarator);
1228 
1229     // Handle the full declarator list.
1230     while (1) {
1231       // If attributes are present, parse them.
1232       MaybeParseGNUAttributes(ParmDeclarator);
1233 
1234       // Ask the actions module to compute the type for this declarator.
1235       Decl *Param =
1236         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1237 
1238       if (Param &&
1239           // A missing identifier has already been diagnosed.
1240           ParmDeclarator.getIdentifier()) {
1241 
1242         // Scan the argument list looking for the correct param to apply this
1243         // type.
1244         for (unsigned i = 0; ; ++i) {
1245           // C99 6.9.1p6: those declarators shall declare only identifiers from
1246           // the identifier list.
1247           if (i == FTI.NumParams) {
1248             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1249               << ParmDeclarator.getIdentifier();
1250             break;
1251           }
1252 
1253           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1254             // Reject redefinitions of parameters.
1255             if (FTI.Params[i].Param) {
1256               Diag(ParmDeclarator.getIdentifierLoc(),
1257                    diag::err_param_redefinition)
1258                  << ParmDeclarator.getIdentifier();
1259             } else {
1260               FTI.Params[i].Param = Param;
1261             }
1262             break;
1263           }
1264         }
1265       }
1266 
1267       // If we don't have a comma, it is either the end of the list (a ';') or
1268       // an error, bail out.
1269       if (Tok.isNot(tok::comma))
1270         break;
1271 
1272       ParmDeclarator.clear();
1273 
1274       // Consume the comma.
1275       ParmDeclarator.setCommaLoc(ConsumeToken());
1276 
1277       // Parse the next declarator.
1278       ParseDeclarator(ParmDeclarator);
1279     }
1280 
1281     // Consume ';' and continue parsing.
1282     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1283       continue;
1284 
1285     // Otherwise recover by skipping to next semi or mandatory function body.
1286     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1287       break;
1288     TryConsumeToken(tok::semi);
1289   }
1290 
1291   // The actions module must verify that all arguments were declared.
1292   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1293 }
1294 
1295 
1296 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1297 /// allowed to be a wide string, and is not subject to character translation.
1298 ///
1299 /// [GNU] asm-string-literal:
1300 ///         string-literal
1301 ///
1302 ExprResult Parser::ParseAsmStringLiteral() {
1303   if (!isTokenStringLiteral()) {
1304     Diag(Tok, diag::err_expected_string_literal)
1305       << /*Source='in...'*/0 << "'asm'";
1306     return ExprError();
1307   }
1308 
1309   ExprResult AsmString(ParseStringLiteralExpression());
1310   if (!AsmString.isInvalid()) {
1311     const auto *SL = cast<StringLiteral>(AsmString.get());
1312     if (!SL->isAscii()) {
1313       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1314         << SL->isWide()
1315         << SL->getSourceRange();
1316       return ExprError();
1317     }
1318   }
1319   return AsmString;
1320 }
1321 
1322 /// ParseSimpleAsm
1323 ///
1324 /// [GNU] simple-asm-expr:
1325 ///         'asm' '(' asm-string-literal ')'
1326 ///
1327 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1328   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1329   SourceLocation Loc = ConsumeToken();
1330 
1331   if (Tok.is(tok::kw_volatile)) {
1332     // Remove from the end of 'asm' to the end of 'volatile'.
1333     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1334                              PP.getLocForEndOfToken(Tok.getLocation()));
1335 
1336     Diag(Tok, diag::warn_file_asm_volatile)
1337       << FixItHint::CreateRemoval(RemovalRange);
1338     ConsumeToken();
1339   }
1340 
1341   BalancedDelimiterTracker T(*this, tok::l_paren);
1342   if (T.consumeOpen()) {
1343     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1344     return ExprError();
1345   }
1346 
1347   ExprResult Result(ParseAsmStringLiteral());
1348 
1349   if (!Result.isInvalid()) {
1350     // Close the paren and get the location of the end bracket
1351     T.consumeClose();
1352     if (EndLoc)
1353       *EndLoc = T.getCloseLocation();
1354   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1355     if (EndLoc)
1356       *EndLoc = Tok.getLocation();
1357     ConsumeParen();
1358   }
1359 
1360   return Result;
1361 }
1362 
1363 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1364 /// cleanup pool so that it gets destroyed when parsing the current top level
1365 /// declaration is finished.
1366 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1367   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1368   TemplateIdAnnotation *
1369       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1370   return Id;
1371 }
1372 
1373 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1374   // Push the current token back into the token stream (or revert it if it is
1375   // cached) and use an annotation scope token for current token.
1376   if (PP.isBacktrackEnabled())
1377     PP.RevertCachedTokens(1);
1378   else
1379     PP.EnterToken(Tok);
1380   Tok.setKind(tok::annot_cxxscope);
1381   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1382   Tok.setAnnotationRange(SS.getRange());
1383 
1384   // In case the tokens were cached, have Preprocessor replace them
1385   // with the annotation token.  We don't need to do this if we've
1386   // just reverted back to a prior state.
1387   if (IsNewAnnotation)
1388     PP.AnnotateCachedTokens(Tok);
1389 }
1390 
1391 /// \brief Attempt to classify the name at the current token position. This may
1392 /// form a type, scope or primary expression annotation, or replace the token
1393 /// with a typo-corrected keyword. This is only appropriate when the current
1394 /// name must refer to an entity which has already been declared.
1395 ///
1396 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1397 ///        and might possibly have a dependent nested name specifier.
1398 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1399 ///        no typo correction will be performed.
1400 Parser::AnnotatedNameKind
1401 Parser::TryAnnotateName(bool IsAddressOfOperand,
1402                         std::unique_ptr<CorrectionCandidateCallback> CCC) {
1403   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1404 
1405   const bool EnteringContext = false;
1406   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1407 
1408   CXXScopeSpec SS;
1409   if (getLangOpts().CPlusPlus &&
1410       ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1411     return ANK_Error;
1412 
1413   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1414     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1415                                                   !WasScopeAnnotation))
1416       return ANK_Error;
1417     return ANK_Unresolved;
1418   }
1419 
1420   IdentifierInfo *Name = Tok.getIdentifierInfo();
1421   SourceLocation NameLoc = Tok.getLocation();
1422 
1423   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1424   // typo-correct to tentatively-declared identifiers.
1425   if (isTentativelyDeclared(Name)) {
1426     // Identifier has been tentatively declared, and thus cannot be resolved as
1427     // an expression. Fall back to annotating it as a type.
1428     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1429                                                   !WasScopeAnnotation))
1430       return ANK_Error;
1431     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1432   }
1433 
1434   Token Next = NextToken();
1435 
1436   // Look up and classify the identifier. We don't perform any typo-correction
1437   // after a scope specifier, because in general we can't recover from typos
1438   // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
1439   // jump back into scope specifier parsing).
1440   Sema::NameClassification Classification = Actions.ClassifyName(
1441       getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1442       SS.isEmpty() ? std::move(CCC) : nullptr);
1443 
1444   switch (Classification.getKind()) {
1445   case Sema::NC_Error:
1446     return ANK_Error;
1447 
1448   case Sema::NC_Keyword:
1449     // The identifier was typo-corrected to a keyword.
1450     Tok.setIdentifierInfo(Name);
1451     Tok.setKind(Name->getTokenID());
1452     PP.TypoCorrectToken(Tok);
1453     if (SS.isNotEmpty())
1454       AnnotateScopeToken(SS, !WasScopeAnnotation);
1455     // We've "annotated" this as a keyword.
1456     return ANK_Success;
1457 
1458   case Sema::NC_Unknown:
1459     // It's not something we know about. Leave it unannotated.
1460     break;
1461 
1462   case Sema::NC_Type: {
1463     SourceLocation BeginLoc = NameLoc;
1464     if (SS.isNotEmpty())
1465       BeginLoc = SS.getBeginLoc();
1466 
1467     /// An Objective-C object type followed by '<' is a specialization of
1468     /// a parameterized class type or a protocol-qualified type.
1469     ParsedType Ty = Classification.getType();
1470     if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1471         (Ty.get()->isObjCObjectType() ||
1472          Ty.get()->isObjCObjectPointerType())) {
1473       // Consume the name.
1474       SourceLocation IdentifierLoc = ConsumeToken();
1475       SourceLocation NewEndLoc;
1476       TypeResult NewType
1477           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1478                                                    /*consumeLastToken=*/false,
1479                                                    NewEndLoc);
1480       if (NewType.isUsable())
1481         Ty = NewType.get();
1482     }
1483 
1484     Tok.setKind(tok::annot_typename);
1485     setTypeAnnotation(Tok, Ty);
1486     Tok.setAnnotationEndLoc(Tok.getLocation());
1487     Tok.setLocation(BeginLoc);
1488     PP.AnnotateCachedTokens(Tok);
1489     return ANK_Success;
1490   }
1491 
1492   case Sema::NC_Expression:
1493     Tok.setKind(tok::annot_primary_expr);
1494     setExprAnnotation(Tok, Classification.getExpression());
1495     Tok.setAnnotationEndLoc(NameLoc);
1496     if (SS.isNotEmpty())
1497       Tok.setLocation(SS.getBeginLoc());
1498     PP.AnnotateCachedTokens(Tok);
1499     return ANK_Success;
1500 
1501   case Sema::NC_TypeTemplate:
1502     if (Next.isNot(tok::less)) {
1503       // This may be a type template being used as a template template argument.
1504       if (SS.isNotEmpty())
1505         AnnotateScopeToken(SS, !WasScopeAnnotation);
1506       return ANK_TemplateName;
1507     }
1508     // Fall through.
1509   case Sema::NC_VarTemplate:
1510   case Sema::NC_FunctionTemplate: {
1511     // We have a type, variable or function template followed by '<'.
1512     ConsumeToken();
1513     UnqualifiedId Id;
1514     Id.setIdentifier(Name, NameLoc);
1515     if (AnnotateTemplateIdToken(
1516             TemplateTy::make(Classification.getTemplateName()),
1517             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1518       return ANK_Error;
1519     return ANK_Success;
1520   }
1521 
1522   case Sema::NC_NestedNameSpecifier:
1523     llvm_unreachable("already parsed nested name specifier");
1524   }
1525 
1526   // Unable to classify the name, but maybe we can annotate a scope specifier.
1527   if (SS.isNotEmpty())
1528     AnnotateScopeToken(SS, !WasScopeAnnotation);
1529   return ANK_Unresolved;
1530 }
1531 
1532 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1533   assert(Tok.isNot(tok::identifier));
1534   Diag(Tok, diag::ext_keyword_as_ident)
1535     << PP.getSpelling(Tok)
1536     << DisableKeyword;
1537   if (DisableKeyword)
1538     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1539   Tok.setKind(tok::identifier);
1540   return true;
1541 }
1542 
1543 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1544 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1545 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1546 /// with a single annotation token representing the typename or C++ scope
1547 /// respectively.
1548 /// This simplifies handling of C++ scope specifiers and allows efficient
1549 /// backtracking without the need to re-parse and resolve nested-names and
1550 /// typenames.
1551 /// It will mainly be called when we expect to treat identifiers as typenames
1552 /// (if they are typenames). For example, in C we do not expect identifiers
1553 /// inside expressions to be treated as typenames so it will not be called
1554 /// for expressions in C.
1555 /// The benefit for C/ObjC is that a typename will be annotated and
1556 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1557 /// will not be called twice, once to check whether we have a declaration
1558 /// specifier, and another one to get the actual type inside
1559 /// ParseDeclarationSpecifiers).
1560 ///
1561 /// This returns true if an error occurred.
1562 ///
1563 /// Note that this routine emits an error if you call it with ::new or ::delete
1564 /// as the current tokens, so only call it in contexts where these are invalid.
1565 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1566   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1567           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1568           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1569           Tok.is(tok::kw___super)) &&
1570          "Cannot be a type or scope token!");
1571 
1572   if (Tok.is(tok::kw_typename)) {
1573     // MSVC lets you do stuff like:
1574     //   typename typedef T_::D D;
1575     //
1576     // We will consume the typedef token here and put it back after we have
1577     // parsed the first identifier, transforming it into something more like:
1578     //   typename T_::D typedef D;
1579     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1580       Token TypedefToken;
1581       PP.Lex(TypedefToken);
1582       bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
1583       PP.EnterToken(Tok);
1584       Tok = TypedefToken;
1585       if (!Result)
1586         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1587       return Result;
1588     }
1589 
1590     // Parse a C++ typename-specifier, e.g., "typename T::type".
1591     //
1592     //   typename-specifier:
1593     //     'typename' '::' [opt] nested-name-specifier identifier
1594     //     'typename' '::' [opt] nested-name-specifier template [opt]
1595     //            simple-template-id
1596     SourceLocation TypenameLoc = ConsumeToken();
1597     CXXScopeSpec SS;
1598     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1599                                        /*EnteringContext=*/false, nullptr,
1600                                        /*IsTypename*/ true))
1601       return true;
1602     if (!SS.isSet()) {
1603       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1604           Tok.is(tok::annot_decltype)) {
1605         // Attempt to recover by skipping the invalid 'typename'
1606         if (Tok.is(tok::annot_decltype) ||
1607             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1608              Tok.isAnnotation())) {
1609           unsigned DiagID = diag::err_expected_qualified_after_typename;
1610           // MS compatibility: MSVC permits using known types with typename.
1611           // e.g. "typedef typename T* pointer_type"
1612           if (getLangOpts().MicrosoftExt)
1613             DiagID = diag::warn_expected_qualified_after_typename;
1614           Diag(Tok.getLocation(), DiagID);
1615           return false;
1616         }
1617       }
1618 
1619       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1620       return true;
1621     }
1622 
1623     TypeResult Ty;
1624     if (Tok.is(tok::identifier)) {
1625       // FIXME: check whether the next token is '<', first!
1626       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1627                                      *Tok.getIdentifierInfo(),
1628                                      Tok.getLocation());
1629     } else if (Tok.is(tok::annot_template_id)) {
1630       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1631       if (TemplateId->Kind != TNK_Type_template &&
1632           TemplateId->Kind != TNK_Dependent_template_name) {
1633         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1634           << Tok.getAnnotationRange();
1635         return true;
1636       }
1637 
1638       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1639                                          TemplateId->NumArgs);
1640 
1641       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1642                                      TemplateId->TemplateKWLoc,
1643                                      TemplateId->Template,
1644                                      TemplateId->TemplateNameLoc,
1645                                      TemplateId->LAngleLoc,
1646                                      TemplateArgsPtr,
1647                                      TemplateId->RAngleLoc);
1648     } else {
1649       Diag(Tok, diag::err_expected_type_name_after_typename)
1650         << SS.getRange();
1651       return true;
1652     }
1653 
1654     SourceLocation EndLoc = Tok.getLastLoc();
1655     Tok.setKind(tok::annot_typename);
1656     setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1657     Tok.setAnnotationEndLoc(EndLoc);
1658     Tok.setLocation(TypenameLoc);
1659     PP.AnnotateCachedTokens(Tok);
1660     return false;
1661   }
1662 
1663   // Remembers whether the token was originally a scope annotation.
1664   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1665 
1666   CXXScopeSpec SS;
1667   if (getLangOpts().CPlusPlus)
1668     if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1669       return true;
1670 
1671   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1672                                                    SS, !WasScopeAnnotation);
1673 }
1674 
1675 /// \brief Try to annotate a type or scope token, having already parsed an
1676 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1677 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1678 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1679                                                        bool NeedType,
1680                                                        CXXScopeSpec &SS,
1681                                                        bool IsNewScope) {
1682   if (Tok.is(tok::identifier)) {
1683     IdentifierInfo *CorrectedII = nullptr;
1684     // Determine whether the identifier is a type name.
1685     if (ParsedType Ty = Actions.getTypeName(
1686             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1687             false, NextToken().is(tok::period), nullptr,
1688             /*IsCtorOrDtorName=*/false,
1689             /*NonTrivialTypeSourceInfo*/ true,
1690             NeedType ? &CorrectedII : nullptr)) {
1691       // A FixIt was applied as a result of typo correction
1692       if (CorrectedII)
1693         Tok.setIdentifierInfo(CorrectedII);
1694 
1695       SourceLocation BeginLoc = Tok.getLocation();
1696       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1697         BeginLoc = SS.getBeginLoc();
1698 
1699       /// An Objective-C object type followed by '<' is a specialization of
1700       /// a parameterized class type or a protocol-qualified type.
1701       if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1702           (Ty.get()->isObjCObjectType() ||
1703            Ty.get()->isObjCObjectPointerType())) {
1704         // Consume the name.
1705         SourceLocation IdentifierLoc = ConsumeToken();
1706         SourceLocation NewEndLoc;
1707         TypeResult NewType
1708           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1709                                                    /*consumeLastToken=*/false,
1710                                                    NewEndLoc);
1711         if (NewType.isUsable())
1712           Ty = NewType.get();
1713       }
1714 
1715       // This is a typename. Replace the current token in-place with an
1716       // annotation type token.
1717       Tok.setKind(tok::annot_typename);
1718       setTypeAnnotation(Tok, Ty);
1719       Tok.setAnnotationEndLoc(Tok.getLocation());
1720       Tok.setLocation(BeginLoc);
1721 
1722       // In case the tokens were cached, have Preprocessor replace
1723       // them with the annotation token.
1724       PP.AnnotateCachedTokens(Tok);
1725       return false;
1726     }
1727 
1728     if (!getLangOpts().CPlusPlus) {
1729       // If we're in C, we can't have :: tokens at all (the lexer won't return
1730       // them).  If the identifier is not a type, then it can't be scope either,
1731       // just early exit.
1732       return false;
1733     }
1734 
1735     // If this is a template-id, annotate with a template-id or type token.
1736     if (NextToken().is(tok::less)) {
1737       TemplateTy Template;
1738       UnqualifiedId TemplateName;
1739       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1740       bool MemberOfUnknownSpecialization;
1741       if (TemplateNameKind TNK =
1742               Actions.isTemplateName(getCurScope(), SS,
1743                                      /*hasTemplateKeyword=*/false, TemplateName,
1744                                      /*ObjectType=*/nullptr, EnteringContext,
1745                                      Template, MemberOfUnknownSpecialization)) {
1746         // Consume the identifier.
1747         ConsumeToken();
1748         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1749                                     TemplateName)) {
1750           // If an unrecoverable error occurred, we need to return true here,
1751           // because the token stream is in a damaged state.  We may not return
1752           // a valid identifier.
1753           return true;
1754         }
1755       }
1756     }
1757 
1758     // The current token, which is either an identifier or a
1759     // template-id, is not part of the annotation. Fall through to
1760     // push that token back into the stream and complete the C++ scope
1761     // specifier annotation.
1762   }
1763 
1764   if (Tok.is(tok::annot_template_id)) {
1765     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1766     if (TemplateId->Kind == TNK_Type_template) {
1767       // A template-id that refers to a type was parsed into a
1768       // template-id annotation in a context where we weren't allowed
1769       // to produce a type annotation token. Update the template-id
1770       // annotation token to a type annotation token now.
1771       AnnotateTemplateIdTokenAsType();
1772       return false;
1773     }
1774   }
1775 
1776   if (SS.isEmpty())
1777     return false;
1778 
1779   // A C++ scope specifier that isn't followed by a typename.
1780   AnnotateScopeToken(SS, IsNewScope);
1781   return false;
1782 }
1783 
1784 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1785 /// annotates C++ scope specifiers and template-ids.  This returns
1786 /// true if there was an error that could not be recovered from.
1787 ///
1788 /// Note that this routine emits an error if you call it with ::new or ::delete
1789 /// as the current tokens, so only call it in contexts where these are invalid.
1790 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1791   assert(getLangOpts().CPlusPlus &&
1792          "Call sites of this function should be guarded by checking for C++");
1793   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1794           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1795           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1796          "Cannot be a type or scope token!");
1797 
1798   CXXScopeSpec SS;
1799   if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1800     return true;
1801   if (SS.isEmpty())
1802     return false;
1803 
1804   AnnotateScopeToken(SS, true);
1805   return false;
1806 }
1807 
1808 bool Parser::isTokenEqualOrEqualTypo() {
1809   tok::TokenKind Kind = Tok.getKind();
1810   switch (Kind) {
1811   default:
1812     return false;
1813   case tok::ampequal:            // &=
1814   case tok::starequal:           // *=
1815   case tok::plusequal:           // +=
1816   case tok::minusequal:          // -=
1817   case tok::exclaimequal:        // !=
1818   case tok::slashequal:          // /=
1819   case tok::percentequal:        // %=
1820   case tok::lessequal:           // <=
1821   case tok::lesslessequal:       // <<=
1822   case tok::greaterequal:        // >=
1823   case tok::greatergreaterequal: // >>=
1824   case tok::caretequal:          // ^=
1825   case tok::pipeequal:           // |=
1826   case tok::equalequal:          // ==
1827     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1828         << Kind
1829         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1830   case tok::equal:
1831     return true;
1832   }
1833 }
1834 
1835 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1836   assert(Tok.is(tok::code_completion));
1837   PrevTokLocation = Tok.getLocation();
1838 
1839   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1840     if (S->getFlags() & Scope::FnScope) {
1841       Actions.CodeCompleteOrdinaryName(getCurScope(),
1842                                        Sema::PCC_RecoveryInFunction);
1843       cutOffParsing();
1844       return PrevTokLocation;
1845     }
1846 
1847     if (S->getFlags() & Scope::ClassScope) {
1848       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1849       cutOffParsing();
1850       return PrevTokLocation;
1851     }
1852   }
1853 
1854   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1855   cutOffParsing();
1856   return PrevTokLocation;
1857 }
1858 
1859 // Code-completion pass-through functions
1860 
1861 void Parser::CodeCompleteDirective(bool InConditional) {
1862   Actions.CodeCompletePreprocessorDirective(InConditional);
1863 }
1864 
1865 void Parser::CodeCompleteInConditionalExclusion() {
1866   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1867 }
1868 
1869 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1870   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1871 }
1872 
1873 void Parser::CodeCompletePreprocessorExpression() {
1874   Actions.CodeCompletePreprocessorExpression();
1875 }
1876 
1877 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1878                                        MacroInfo *MacroInfo,
1879                                        unsigned ArgumentIndex) {
1880   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1881                                                 ArgumentIndex);
1882 }
1883 
1884 void Parser::CodeCompleteNaturalLanguage() {
1885   Actions.CodeCompleteNaturalLanguage();
1886 }
1887 
1888 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1889   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1890          "Expected '__if_exists' or '__if_not_exists'");
1891   Result.IsIfExists = Tok.is(tok::kw___if_exists);
1892   Result.KeywordLoc = ConsumeToken();
1893 
1894   BalancedDelimiterTracker T(*this, tok::l_paren);
1895   if (T.consumeOpen()) {
1896     Diag(Tok, diag::err_expected_lparen_after)
1897       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1898     return true;
1899   }
1900 
1901   // Parse nested-name-specifier.
1902   if (getLangOpts().CPlusPlus)
1903     ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
1904                                    /*EnteringContext=*/false);
1905 
1906   // Check nested-name specifier.
1907   if (Result.SS.isInvalid()) {
1908     T.skipToEnd();
1909     return true;
1910   }
1911 
1912   // Parse the unqualified-id.
1913   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1914   if (ParseUnqualifiedId(Result.SS, false, true, true, nullptr, TemplateKWLoc,
1915                          Result.Name)) {
1916     T.skipToEnd();
1917     return true;
1918   }
1919 
1920   if (T.consumeClose())
1921     return true;
1922 
1923   // Check if the symbol exists.
1924   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1925                                                Result.IsIfExists, Result.SS,
1926                                                Result.Name)) {
1927   case Sema::IER_Exists:
1928     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1929     break;
1930 
1931   case Sema::IER_DoesNotExist:
1932     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1933     break;
1934 
1935   case Sema::IER_Dependent:
1936     Result.Behavior = IEB_Dependent;
1937     break;
1938 
1939   case Sema::IER_Error:
1940     return true;
1941   }
1942 
1943   return false;
1944 }
1945 
1946 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1947   IfExistsCondition Result;
1948   if (ParseMicrosoftIfExistsCondition(Result))
1949     return;
1950 
1951   BalancedDelimiterTracker Braces(*this, tok::l_brace);
1952   if (Braces.consumeOpen()) {
1953     Diag(Tok, diag::err_expected) << tok::l_brace;
1954     return;
1955   }
1956 
1957   switch (Result.Behavior) {
1958   case IEB_Parse:
1959     // Parse declarations below.
1960     break;
1961 
1962   case IEB_Dependent:
1963     llvm_unreachable("Cannot have a dependent external declaration");
1964 
1965   case IEB_Skip:
1966     Braces.skipToEnd();
1967     return;
1968   }
1969 
1970   // Parse the declarations.
1971   // FIXME: Support module import within __if_exists?
1972   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1973     ParsedAttributesWithRange attrs(AttrFactory);
1974     MaybeParseCXX11Attributes(attrs);
1975     MaybeParseMicrosoftAttributes(attrs);
1976     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1977     if (Result && !getCurScope()->getParent())
1978       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1979   }
1980   Braces.consumeClose();
1981 }
1982 
1983 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1984   assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1985          "Improper start to module import");
1986   SourceLocation ImportLoc = ConsumeToken();
1987 
1988   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1989 
1990   // Parse the module path.
1991   do {
1992     if (!Tok.is(tok::identifier)) {
1993       if (Tok.is(tok::code_completion)) {
1994         Actions.CodeCompleteModuleImport(ImportLoc, Path);
1995         cutOffParsing();
1996         return nullptr;
1997       }
1998 
1999       Diag(Tok, diag::err_module_expected_ident);
2000       SkipUntil(tok::semi);
2001       return nullptr;
2002     }
2003 
2004     // Record this part of the module path.
2005     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2006     ConsumeToken();
2007 
2008     if (Tok.is(tok::period)) {
2009       ConsumeToken();
2010       continue;
2011     }
2012 
2013     break;
2014   } while (true);
2015 
2016   if (PP.hadModuleLoaderFatalFailure()) {
2017     // With a fatal failure in the module loader, we abort parsing.
2018     cutOffParsing();
2019     return nullptr;
2020   }
2021 
2022   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
2023   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2024   if (Import.isInvalid())
2025     return nullptr;
2026 
2027   return Actions.ConvertDeclToDeclGroup(Import.get());
2028 }
2029 
2030 /// \brief Try recover parser when module annotation appears where it must not
2031 /// be found.
2032 /// \returns false if the recover was successful and parsing may be continued, or
2033 /// true if parser must bail out to top level and handle the token there.
2034 bool Parser::parseMisplacedModuleImport() {
2035   while (true) {
2036     switch (Tok.getKind()) {
2037     case tok::annot_module_end:
2038       // Inform caller that recovery failed, the error must be handled at upper
2039       // level.
2040       return true;
2041     case tok::annot_module_begin:
2042       Actions.diagnoseMisplacedModuleImport(reinterpret_cast<Module *>(
2043         Tok.getAnnotationValue()), Tok.getLocation());
2044       return true;
2045     case tok::annot_module_include:
2046       // Module import found where it should not be, for instance, inside a
2047       // namespace. Recover by importing the module.
2048       Actions.ActOnModuleInclude(Tok.getLocation(),
2049                                  reinterpret_cast<Module *>(
2050                                  Tok.getAnnotationValue()));
2051       ConsumeToken();
2052       // If there is another module import, process it.
2053       continue;
2054     default:
2055       return false;
2056     }
2057   }
2058   return false;
2059 }
2060 
2061 bool BalancedDelimiterTracker::diagnoseOverflow() {
2062   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2063     << P.getLangOpts().BracketDepth;
2064   P.Diag(P.Tok, diag::note_bracket_depth);
2065   P.cutOffParsing();
2066   return true;
2067 }
2068 
2069 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2070                                                 const char *Msg,
2071                                                 tok::TokenKind SkipToTok) {
2072   LOpen = P.Tok.getLocation();
2073   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2074     if (SkipToTok != tok::unknown)
2075       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2076     return true;
2077   }
2078 
2079   if (getDepth() < MaxDepth)
2080     return false;
2081 
2082   return diagnoseOverflow();
2083 }
2084 
2085 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2086   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2087 
2088   if (P.Tok.is(tok::annot_module_end))
2089     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2090   else
2091     P.Diag(P.Tok, diag::err_expected) << Close;
2092   P.Diag(LOpen, diag::note_matching) << Kind;
2093 
2094   // If we're not already at some kind of closing bracket, skip to our closing
2095   // token.
2096   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2097       P.Tok.isNot(tok::r_square) &&
2098       P.SkipUntil(Close, FinalToken,
2099                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2100       P.Tok.is(Close))
2101     LClose = P.ConsumeAnyToken();
2102   return true;
2103 }
2104 
2105 void BalancedDelimiterTracker::skipToEnd() {
2106   P.SkipUntil(Close, Parser::StopBeforeMatch);
2107   consumeClose();
2108 }
2109