clang  14.0.0git
Parser.cpp
Go to the documentation of this file.
1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Parser interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
20 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/Path.h"
24 using namespace clang;
25 
26 
27 namespace {
28 /// 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 } // end anonymous namespace
42 
43 IdentifierInfo *Parser::getSEHExceptKeyword() {
44  // __except is accepted as a (contextual) keyword
45  if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46  Ident__except = PP.getIdentifierInfo("__except");
47 
48  return Ident__except;
49 }
50 
51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52  : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
53  Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
54  ColonIsSacred(false), InMessageExpression(false),
55  TemplateParameterDepth(0), ParsingInObjCContainer(false) {
56  SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57  Tok.startToken();
58  Tok.setKind(tok::eof);
59  Actions.CurScope = nullptr;
60  NumCachedScopes = 0;
61  CurParsedObjCImpl = nullptr;
62 
63  // Add #pragma handlers. These are removed and destroyed in the
64  // destructor.
65  initializePragmaHandlers();
66 
67  CommentSemaHandler.reset(new ActionCommentHandler(actions));
68  PP.addCommentHandler(CommentSemaHandler.get());
69 
70  PP.setCodeCompletionHandler(*this);
71 }
72 
74  return Diags.Report(Loc, DiagID);
75 }
76 
77 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
78  return Diag(Tok.getLocation(), DiagID);
79 }
80 
81 /// Emits a diagnostic suggesting parentheses surrounding a
82 /// given range.
83 ///
84 /// \param Loc The location where we'll emit the diagnostic.
85 /// \param DK The kind of diagnostic to emit.
86 /// \param ParenRange Source range enclosing code that should be parenthesized.
87 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
88  SourceRange ParenRange) {
89  SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
90  if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
91  // We can't display the parentheses, so just dig the
92  // warning/error and return.
93  Diag(Loc, DK);
94  return;
95  }
96 
97  Diag(Loc, DK)
98  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
99  << FixItHint::CreateInsertion(EndLoc, ")");
100 }
101 
102 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
103  switch (ExpectedTok) {
104  case tok::semi:
105  return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
106  default: return false;
107  }
108 }
109 
110 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
111  StringRef Msg) {
112  if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
113  ConsumeAnyToken();
114  return false;
115  }
116 
117  // Detect common single-character typos and resume.
118  if (IsCommonTypo(ExpectedTok, Tok)) {
119  SourceLocation Loc = Tok.getLocation();
120  {
121  DiagnosticBuilder DB = Diag(Loc, DiagID);
123  SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
124  if (DiagID == diag::err_expected)
125  DB << ExpectedTok;
126  else if (DiagID == diag::err_expected_after)
127  DB << Msg << ExpectedTok;
128  else
129  DB << Msg;
130  }
131 
132  // Pretend there wasn't a problem.
133  ConsumeAnyToken();
134  return false;
135  }
136 
137  SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
138  const char *Spelling = nullptr;
139  if (EndLoc.isValid())
140  Spelling = tok::getPunctuatorSpelling(ExpectedTok);
141 
142  DiagnosticBuilder DB =
143  Spelling
144  ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
145  : Diag(Tok, DiagID);
146  if (DiagID == diag::err_expected)
147  DB << ExpectedTok;
148  else if (DiagID == diag::err_expected_after)
149  DB << Msg << ExpectedTok;
150  else
151  DB << Msg;
152 
153  return true;
154 }
155 
156 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
157  if (TryConsumeToken(tok::semi))
158  return false;
159 
160  if (Tok.is(tok::code_completion)) {
161  handleUnexpectedCodeCompletionToken();
162  return false;
163  }
164 
165  if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
166  NextToken().is(tok::semi)) {
167  Diag(Tok, diag::err_extraneous_token_before_semi)
168  << PP.getSpelling(Tok)
170  ConsumeAnyToken(); // The ')' or ']'.
171  ConsumeToken(); // The ';'.
172  return false;
173  }
174 
175  return ExpectAndConsume(tok::semi, DiagID);
176 }
177 
178 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
179  if (!Tok.is(tok::semi)) return;
180 
181  bool HadMultipleSemis = false;
182  SourceLocation StartLoc = Tok.getLocation();
183  SourceLocation EndLoc = Tok.getLocation();
184  ConsumeToken();
185 
186  while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
187  HadMultipleSemis = true;
188  EndLoc = Tok.getLocation();
189  ConsumeToken();
190  }
191 
192  // C++11 allows extra semicolons at namespace scope, but not in any of the
193  // other contexts.
194  if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
195  if (getLangOpts().CPlusPlus11)
196  Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
197  << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
198  else
199  Diag(StartLoc, diag::ext_extra_semi_cxx11)
200  << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
201  return;
202  }
203 
204  if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
205  Diag(StartLoc, diag::ext_extra_semi)
207  Actions.getASTContext().getPrintingPolicy())
208  << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
209  else
210  // A single semicolon is valid after a member function definition.
211  Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
212  << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
213 }
214 
215 bool Parser::expectIdentifier() {
216  if (Tok.is(tok::identifier))
217  return false;
218  if (const auto *II = Tok.getIdentifierInfo()) {
219  if (II->isCPlusPlusKeyword(getLangOpts())) {
220  Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
221  << tok::identifier << Tok.getIdentifierInfo();
222  // Objective-C++: Recover by treating this keyword as a valid identifier.
223  return false;
224  }
225  }
226  Diag(Tok, diag::err_expected) << tok::identifier;
227  return true;
228 }
229 
230 void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
231  tok::TokenKind FirstTokKind, CompoundToken Op) {
232  if (FirstTokLoc.isInvalid())
233  return;
234  SourceLocation SecondTokLoc = Tok.getLocation();
235 
236  // If either token is in a macro, we expect both tokens to come from the same
237  // macro expansion.
238  if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
239  PP.getSourceManager().getFileID(FirstTokLoc) !=
240  PP.getSourceManager().getFileID(SecondTokLoc)) {
241  Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
242  << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
243  << static_cast<int>(Op) << SourceRange(FirstTokLoc);
244  Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
245  << (FirstTokKind == Tok.getKind()) << Tok.getKind()
246  << SourceRange(SecondTokLoc);
247  return;
248  }
249 
250  // We expect the tokens to abut.
251  if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
252  SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
253  if (SpaceLoc.isInvalid())
254  SpaceLoc = FirstTokLoc;
255  Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
256  << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
257  << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
258  return;
259  }
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // Error recovery.
264 //===----------------------------------------------------------------------===//
265 
267  return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
268 }
269 
270 /// SkipUntil - Read tokens until we get to the specified token, then consume
271 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
272 /// token will ever occur, this skips to the next token, or to some likely
273 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
274 /// character.
275 ///
276 /// If SkipUntil finds the specified token, it returns true, otherwise it
277 /// returns false.
279  // We always want this function to skip at least one token if the first token
280  // isn't T and if not at EOF.
281  bool isFirstTokenSkipped = true;
282  while (1) {
283  // If we found one of the tokens, stop and return true.
284  for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
285  if (Tok.is(Toks[i])) {
286  if (HasFlagsSet(Flags, StopBeforeMatch)) {
287  // Noop, don't consume the token.
288  } else {
289  ConsumeAnyToken();
290  }
291  return true;
292  }
293  }
294 
295  // Important special case: The caller has given up and just wants us to
296  // skip the rest of the file. Do this without recursing, since we can
297  // get here precisely because the caller detected too much recursion.
298  if (Toks.size() == 1 && Toks[0] == tok::eof &&
299  !HasFlagsSet(Flags, StopAtSemi) &&
301  while (Tok.isNot(tok::eof))
302  ConsumeAnyToken();
303  return true;
304  }
305 
306  switch (Tok.getKind()) {
307  case tok::eof:
308  // Ran out of tokens.
309  return false;
310 
311  case tok::annot_pragma_openmp:
312  case tok::annot_attr_openmp:
313  case tok::annot_pragma_openmp_end:
314  // Stop before an OpenMP pragma boundary.
315  if (OpenMPDirectiveParsing)
316  return false;
317  ConsumeAnnotationToken();
318  break;
319  case tok::annot_module_begin:
320  case tok::annot_module_end:
321  case tok::annot_module_include:
322  // Stop before we change submodules. They generally indicate a "good"
323  // place to pick up parsing again (except in the special case where
324  // we're trying to skip to EOF).
325  return false;
326 
327  case tok::code_completion:
328  if (!HasFlagsSet(Flags, StopAtCodeCompletion))
329  handleUnexpectedCodeCompletionToken();
330  return false;
331 
332  case tok::l_paren:
333  // Recursively skip properly-nested parens.
334  ConsumeParen();
335  if (HasFlagsSet(Flags, StopAtCodeCompletion))
336  SkipUntil(tok::r_paren, StopAtCodeCompletion);
337  else
338  SkipUntil(tok::r_paren);
339  break;
340  case tok::l_square:
341  // Recursively skip properly-nested square brackets.
342  ConsumeBracket();
343  if (HasFlagsSet(Flags, StopAtCodeCompletion))
344  SkipUntil(tok::r_square, StopAtCodeCompletion);
345  else
346  SkipUntil(tok::r_square);
347  break;
348  case tok::l_brace:
349  // Recursively skip properly-nested braces.
350  ConsumeBrace();
351  if (HasFlagsSet(Flags, StopAtCodeCompletion))
352  SkipUntil(tok::r_brace, StopAtCodeCompletion);
353  else
354  SkipUntil(tok::r_brace);
355  break;
356  case tok::question:
357  // Recursively skip ? ... : pairs; these function as brackets. But
358  // still stop at a semicolon if requested.
359  ConsumeToken();
360  SkipUntil(tok::colon,
361  SkipUntilFlags(unsigned(Flags) &
362  unsigned(StopAtCodeCompletion | StopAtSemi)));
363  break;
364 
365  // Okay, we found a ']' or '}' or ')', which we think should be balanced.
366  // Since the user wasn't looking for this token (if they were, it would
367  // already be handled), this isn't balanced. If there is a LHS token at a
368  // higher level, we will assume that this matches the unbalanced token
369  // and return it. Otherwise, this is a spurious RHS token, which we skip.
370  case tok::r_paren:
371  if (ParenCount && !isFirstTokenSkipped)
372  return false; // Matches something.
373  ConsumeParen();
374  break;
375  case tok::r_square:
376  if (BracketCount && !isFirstTokenSkipped)
377  return false; // Matches something.
378  ConsumeBracket();
379  break;
380  case tok::r_brace:
381  if (BraceCount && !isFirstTokenSkipped)
382  return false; // Matches something.
383  ConsumeBrace();
384  break;
385 
386  case tok::semi:
387  if (HasFlagsSet(Flags, StopAtSemi))
388  return false;
389  LLVM_FALLTHROUGH;
390  default:
391  // Skip this token.
392  ConsumeAnyToken();
393  break;
394  }
395  isFirstTokenSkipped = false;
396  }
397 }
398 
399 //===----------------------------------------------------------------------===//
400 // Scope manipulation
401 //===----------------------------------------------------------------------===//
402 
403 /// EnterScope - Start a new scope.
404 void Parser::EnterScope(unsigned ScopeFlags) {
405  if (NumCachedScopes) {
406  Scope *N = ScopeCache[--NumCachedScopes];
407  N->Init(getCurScope(), ScopeFlags);
408  Actions.CurScope = N;
409  } else {
410  Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
411  }
412 }
413 
414 /// ExitScope - Pop a scope off the scope stack.
416  assert(getCurScope() && "Scope imbalance!");
417 
418  // Inform the actions module that this scope is going away if there are any
419  // decls in it.
420  Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
421 
422  Scope *OldScope = getCurScope();
423  Actions.CurScope = OldScope->getParent();
424 
425  if (NumCachedScopes == ScopeCacheSize)
426  delete OldScope;
427  else
428  ScopeCache[NumCachedScopes++] = OldScope;
429 }
430 
431 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
432 /// this object does nothing.
433 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
434  bool ManageFlags)
435  : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
436  if (CurScope) {
437  OldFlags = CurScope->getFlags();
438  CurScope->setFlags(ScopeFlags);
439  }
440 }
441 
442 /// Restore the flags for the current scope to what they were before this
443 /// object overrode them.
444 Parser::ParseScopeFlags::~ParseScopeFlags() {
445  if (CurScope)
446  CurScope->setFlags(OldFlags);
447 }
448 
449 
450 //===----------------------------------------------------------------------===//
451 // C99 6.9: External Definitions.
452 //===----------------------------------------------------------------------===//
453 
455  // If we still have scopes active, delete the scope tree.
456  delete getCurScope();
457  Actions.CurScope = nullptr;
458 
459  // Free the scope cache.
460  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
461  delete ScopeCache[i];
462 
463  resetPragmaHandlers();
464 
465  PP.removeCommentHandler(CommentSemaHandler.get());
466 
468 
469  DestroyTemplateIds();
470 }
471 
472 /// Initialize - Warm up the parser.
473 ///
475  // Create the translation unit scope. Install it as the current scope.
476  assert(getCurScope() == nullptr && "A scope is already active?");
479 
480  // Initialization for Objective-C context sensitive keywords recognition.
481  // Referenced in Parser::ParseObjCTypeQualifierList.
482  if (getLangOpts().ObjC) {
483  ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
484  ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
485  ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
486  ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
487  ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
488  ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
489  ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
490  ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
491  ObjCTypeQuals[objc_null_unspecified]
492  = &PP.getIdentifierTable().get("null_unspecified");
493  }
494 
495  Ident_instancetype = nullptr;
496  Ident_final = nullptr;
497  Ident_sealed = nullptr;
498  Ident_abstract = nullptr;
499  Ident_override = nullptr;
500  Ident_GNU_final = nullptr;
501  Ident_import = nullptr;
502  Ident_module = nullptr;
503 
504  Ident_super = &PP.getIdentifierTable().get("super");
505 
506  Ident_vector = nullptr;
507  Ident_bool = nullptr;
508  Ident_Bool = nullptr;
509  Ident_pixel = nullptr;
510  if (getLangOpts().AltiVec || getLangOpts().ZVector) {
511  Ident_vector = &PP.getIdentifierTable().get("vector");
512  Ident_bool = &PP.getIdentifierTable().get("bool");
513  Ident_Bool = &PP.getIdentifierTable().get("_Bool");
514  }
515  if (getLangOpts().AltiVec)
516  Ident_pixel = &PP.getIdentifierTable().get("pixel");
517 
518  Ident_introduced = nullptr;
519  Ident_deprecated = nullptr;
520  Ident_obsoleted = nullptr;
521  Ident_unavailable = nullptr;
522  Ident_strict = nullptr;
523  Ident_replacement = nullptr;
524 
525  Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr;
526 
527  Ident__except = nullptr;
528 
529  Ident__exception_code = Ident__exception_info = nullptr;
530  Ident__abnormal_termination = Ident___exception_code = nullptr;
531  Ident___exception_info = Ident___abnormal_termination = nullptr;
532  Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
533  Ident_AbnormalTermination = nullptr;
534 
535  if(getLangOpts().Borland) {
536  Ident__exception_info = PP.getIdentifierInfo("_exception_info");
537  Ident___exception_info = PP.getIdentifierInfo("__exception_info");
538  Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
539  Ident__exception_code = PP.getIdentifierInfo("_exception_code");
540  Ident___exception_code = PP.getIdentifierInfo("__exception_code");
541  Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
542  Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
543  Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
544  Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
545 
546  PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
547  PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
548  PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
549  PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
550  PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
551  PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
552  PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
553  PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
554  PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
555  }
556 
557  if (getLangOpts().CPlusPlusModules) {
558  Ident_import = PP.getIdentifierInfo("import");
559  Ident_module = PP.getIdentifierInfo("module");
560  }
561 
562  Actions.Initialize();
563 
564  // Prime the lexer look-ahead.
565  ConsumeToken();
566 }
567 
568 void Parser::DestroyTemplateIds() {
569  for (TemplateIdAnnotation *Id : TemplateIds)
570  Id->Destroy();
571  TemplateIds.clear();
572 }
573 
574 /// Parse the first top-level declaration in a translation unit.
575 ///
576 /// translation-unit:
577 /// [C] external-declaration
578 /// [C] translation-unit external-declaration
579 /// [C++] top-level-declaration-seq[opt]
580 /// [C++20] global-module-fragment[opt] module-declaration
581 /// top-level-declaration-seq[opt] private-module-fragment[opt]
582 ///
583 /// Note that in C, it is an error if there is no first declaration.
585  Actions.ActOnStartOfTranslationUnit();
586 
587  // C11 6.9p1 says translation units must have at least one top-level
588  // declaration. C++ doesn't have this restriction. We also don't want to
589  // complain if we have a precompiled header, although technically if the PCH
590  // is empty we should still emit the (pedantic) diagnostic.
591  // If the main file is a header, we're only pretending it's a TU; don't warn.
592  bool NoTopLevelDecls = ParseTopLevelDecl(Result, true);
593  if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
595  Diag(diag::ext_empty_translation_unit);
596 
597  return NoTopLevelDecls;
598 }
599 
600 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
601 /// action tells us to. This returns true if the EOF was encountered.
602 ///
603 /// top-level-declaration:
604 /// declaration
605 /// [C++20] module-import-declaration
606 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl) {
607  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
608 
609  // Skip over the EOF token, flagging end of previous input for incremental
610  // processing
611  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
612  ConsumeToken();
613 
614  Result = nullptr;
615  switch (Tok.getKind()) {
616  case tok::annot_pragma_unused:
617  HandlePragmaUnused();
618  return false;
619 
620  case tok::kw_export:
621  switch (NextToken().getKind()) {
622  case tok::kw_module:
623  goto module_decl;
624 
625  // Note: no need to handle kw_import here. We only form kw_import under
626  // the Modules TS, and in that case 'export import' is parsed as an
627  // export-declaration containing an import-declaration.
628 
629  // Recognize context-sensitive C++20 'export module' and 'export import'
630  // declarations.
631  case tok::identifier: {
633  if ((II == Ident_module || II == Ident_import) &&
634  GetLookAheadToken(2).isNot(tok::coloncolon)) {
635  if (II == Ident_module)
636  goto module_decl;
637  else
638  goto import_decl;
639  }
640  break;
641  }
642 
643  default:
644  break;
645  }
646  break;
647 
648  case tok::kw_module:
649  module_decl:
650  Result = ParseModuleDecl(IsFirstDecl);
651  return false;
652 
653  // tok::kw_import is handled by ParseExternalDeclaration. (Under the Modules
654  // TS, an import can occur within an export block.)
655  import_decl: {
656  Decl *ImportDecl = ParseModuleImport(SourceLocation());
657  Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
658  return false;
659  }
660 
661  case tok::annot_module_include:
662  Actions.ActOnModuleInclude(Tok.getLocation(),
663  reinterpret_cast<Module *>(
664  Tok.getAnnotationValue()));
665  ConsumeAnnotationToken();
666  return false;
667 
668  case tok::annot_module_begin:
669  Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
670  Tok.getAnnotationValue()));
671  ConsumeAnnotationToken();
672  return false;
673 
674  case tok::annot_module_end:
675  Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
676  Tok.getAnnotationValue()));
677  ConsumeAnnotationToken();
678  return false;
679 
680  case tok::eof:
681  // Check whether -fmax-tokens= was reached.
682  if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
683  PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
684  << PP.getTokenCount() << PP.getMaxTokens();
685  SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
686  if (OverrideLoc.isValid()) {
687  PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
688  }
689  }
690 
691  // Late template parsing can begin.
692  Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
694  Actions.ActOnEndOfTranslationUnit();
695  //else don't tell Sema that we ended parsing: more input might come.
696  return true;
697 
698  case tok::identifier:
699  // C++2a [basic.link]p3:
700  // A token sequence beginning with 'export[opt] module' or
701  // 'export[opt] import' and not immediately followed by '::'
702  // is never interpreted as the declaration of a top-level-declaration.
703  if ((Tok.getIdentifierInfo() == Ident_module ||
704  Tok.getIdentifierInfo() == Ident_import) &&
705  NextToken().isNot(tok::coloncolon)) {
706  if (Tok.getIdentifierInfo() == Ident_module)
707  goto module_decl;
708  else
709  goto import_decl;
710  }
711  break;
712 
713  default:
714  break;
715  }
716 
717  ParsedAttributesWithRange attrs(AttrFactory);
718  MaybeParseCXX11Attributes(attrs);
719 
720  Result = ParseExternalDeclaration(attrs);
721  return false;
722 }
723 
724 /// ParseExternalDeclaration:
725 ///
726 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
727 /// function-definition
728 /// declaration
729 /// [GNU] asm-definition
730 /// [GNU] __extension__ external-declaration
731 /// [OBJC] objc-class-definition
732 /// [OBJC] objc-class-declaration
733 /// [OBJC] objc-alias-declaration
734 /// [OBJC] objc-protocol-definition
735 /// [OBJC] objc-method-definition
736 /// [OBJC] @end
737 /// [C++] linkage-specification
738 /// [GNU] asm-definition:
739 /// simple-asm-expr ';'
740 /// [C++11] empty-declaration
741 /// [C++11] attribute-declaration
742 ///
743 /// [C++11] empty-declaration:
744 /// ';'
745 ///
746 /// [C++0x/GNU] 'extern' 'template' declaration
747 ///
748 /// [Modules-TS] module-import-declaration
749 ///
751 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
752  ParsingDeclSpec *DS) {
753  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
754  ParenBraceBracketBalancer BalancerRAIIObj(*this);
755 
756  if (PP.isCodeCompletionReached()) {
757  cutOffParsing();
758  return nullptr;
759  }
760 
761  Decl *SingleDecl = nullptr;
762  switch (Tok.getKind()) {
763  case tok::annot_pragma_vis:
764  HandlePragmaVisibility();
765  return nullptr;
766  case tok::annot_pragma_pack:
767  HandlePragmaPack();
768  return nullptr;
769  case tok::annot_pragma_msstruct:
770  HandlePragmaMSStruct();
771  return nullptr;
772  case tok::annot_pragma_align:
773  HandlePragmaAlign();
774  return nullptr;
775  case tok::annot_pragma_weak:
776  HandlePragmaWeak();
777  return nullptr;
778  case tok::annot_pragma_weakalias:
779  HandlePragmaWeakAlias();
780  return nullptr;
781  case tok::annot_pragma_redefine_extname:
782  HandlePragmaRedefineExtname();
783  return nullptr;
784  case tok::annot_pragma_fp_contract:
785  HandlePragmaFPContract();
786  return nullptr;
787  case tok::annot_pragma_fenv_access:
788  case tok::annot_pragma_fenv_access_ms:
789  HandlePragmaFEnvAccess();
790  return nullptr;
791  case tok::annot_pragma_fenv_round:
792  HandlePragmaFEnvRound();
793  return nullptr;
794  case tok::annot_pragma_float_control:
795  HandlePragmaFloatControl();
796  return nullptr;
797  case tok::annot_pragma_fp:
798  HandlePragmaFP();
799  break;
800  case tok::annot_pragma_opencl_extension:
801  HandlePragmaOpenCLExtension();
802  return nullptr;
803  case tok::annot_attr_openmp:
804  case tok::annot_pragma_openmp: {
806  return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
807  }
808  case tok::annot_pragma_ms_pointers_to_members:
809  HandlePragmaMSPointersToMembers();
810  return nullptr;
811  case tok::annot_pragma_ms_vtordisp:
812  HandlePragmaMSVtorDisp();
813  return nullptr;
814  case tok::annot_pragma_ms_pragma:
815  HandlePragmaMSPragma();
816  return nullptr;
817  case tok::annot_pragma_dump:
818  HandlePragmaDump();
819  return nullptr;
820  case tok::annot_pragma_attribute:
821  HandlePragmaAttribute();
822  return nullptr;
823  case tok::semi:
824  // Either a C++11 empty-declaration or attribute-declaration.
825  SingleDecl =
826  Actions.ActOnEmptyDeclaration(getCurScope(), attrs, Tok.getLocation());
827  ConsumeExtraSemi(OutsideFunction);
828  break;
829  case tok::r_brace:
830  Diag(Tok, diag::err_extraneous_closing_brace);
831  ConsumeBrace();
832  return nullptr;
833  case tok::eof:
834  Diag(Tok, diag::err_expected_external_declaration);
835  return nullptr;
836  case tok::kw___extension__: {
837  // __extension__ silences extension warnings in the subexpression.
838  ExtensionRAIIObject O(Diags); // Use RAII to do this.
839  ConsumeToken();
840  return ParseExternalDeclaration(attrs);
841  }
842  case tok::kw_asm: {
843  ProhibitAttributes(attrs);
844 
845  SourceLocation StartLoc = Tok.getLocation();
846  SourceLocation EndLoc;
847 
848  ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
849 
850  // Check if GNU-style InlineAsm is disabled.
851  // Empty asm string is allowed because it will not introduce
852  // any assembly code.
853  if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
854  const auto *SL = cast<StringLiteral>(Result.get());
855  if (!SL->getString().trim().empty())
856  Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
857  }
858 
859  ExpectAndConsume(tok::semi, diag::err_expected_after,
860  "top-level asm block");
861 
862  if (Result.isInvalid())
863  return nullptr;
864  SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
865  break;
866  }
867  case tok::at:
868  return ParseObjCAtDirectives(attrs);
869  case tok::minus:
870  case tok::plus:
871  if (!getLangOpts().ObjC) {
872  Diag(Tok, diag::err_expected_external_declaration);
873  ConsumeToken();
874  return nullptr;
875  }
876  SingleDecl = ParseObjCMethodDefinition();
877  break;
878  case tok::code_completion:
879  cutOffParsing();
880  if (CurParsedObjCImpl) {
881  // Code-complete Objective-C methods even without leading '-'/'+' prefix.
883  /*IsInstanceMethod=*/None,
884  /*ReturnType=*/nullptr);
885  }
886  Actions.CodeCompleteOrdinaryName(
887  getCurScope(),
888  CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
889  return nullptr;
890  case tok::kw_import:
891  SingleDecl = ParseModuleImport(SourceLocation());
892  break;
893  case tok::kw_export:
894  if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
895  SingleDecl = ParseExportDeclaration();
896  break;
897  }
898  // This must be 'export template'. Parse it so we can diagnose our lack
899  // of support.
900  LLVM_FALLTHROUGH;
901  case tok::kw_using:
902  case tok::kw_namespace:
903  case tok::kw_typedef:
904  case tok::kw_template:
905  case tok::kw_static_assert:
906  case tok::kw__Static_assert:
907  // A function definition cannot start with any of these keywords.
908  {
909  SourceLocation DeclEnd;
910  return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
911  }
912 
913  case tok::kw_static:
914  // Parse (then ignore) 'static' prior to a template instantiation. This is
915  // a GCC extension that we intentionally do not support.
916  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
917  Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
918  << 0;
919  SourceLocation DeclEnd;
920  return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
921  }
922  goto dont_know;
923 
924  case tok::kw_inline:
925  if (getLangOpts().CPlusPlus) {
926  tok::TokenKind NextKind = NextToken().getKind();
927 
928  // Inline namespaces. Allowed as an extension even in C++03.
929  if (NextKind == tok::kw_namespace) {
930  SourceLocation DeclEnd;
931  return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
932  }
933 
934  // Parse (then ignore) 'inline' prior to a template instantiation. This is
935  // a GCC extension that we intentionally do not support.
936  if (NextKind == tok::kw_template) {
937  Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
938  << 1;
939  SourceLocation DeclEnd;
940  return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
941  }
942  }
943  goto dont_know;
944 
945  case tok::kw_extern:
946  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
947  // Extern templates
948  SourceLocation ExternLoc = ConsumeToken();
949  SourceLocation TemplateLoc = ConsumeToken();
950  Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
951  diag::warn_cxx98_compat_extern_template :
952  diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
953  SourceLocation DeclEnd;
954  return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
955  DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, attrs));
956  }
957  goto dont_know;
958 
959  case tok::kw___if_exists:
960  case tok::kw___if_not_exists:
961  ParseMicrosoftIfExistsExternalDeclaration();
962  return nullptr;
963 
964  case tok::kw_module:
965  Diag(Tok, diag::err_unexpected_module_decl);
966  SkipUntil(tok::semi);
967  return nullptr;
968 
969  default:
970  dont_know:
971  if (Tok.isEditorPlaceholder()) {
972  ConsumeToken();
973  return nullptr;
974  }
975  // We can't tell whether this is a function-definition or declaration yet.
976  return ParseDeclarationOrFunctionDefinition(attrs, DS);
977  }
978 
979  // This routine returns a DeclGroup, if the thing we parsed only contains a
980  // single decl, convert it now.
981  return Actions.ConvertDeclToDeclGroup(SingleDecl);
982 }
983 
984 /// Determine whether the current token, if it occurs after a
985 /// declarator, continues a declaration or declaration list.
986 bool Parser::isDeclarationAfterDeclarator() {
987  // Check for '= delete' or '= default'
988  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
989  const Token &KW = NextToken();
990  if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
991  return false;
992  }
993 
994  return Tok.is(tok::equal) || // int X()= -> not a function def
995  Tok.is(tok::comma) || // int X(), -> not a function def
996  Tok.is(tok::semi) || // int X(); -> not a function def
997  Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
998  Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
999  (getLangOpts().CPlusPlus &&
1000  Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
1001 }
1002 
1003 /// Determine whether the current token, if it occurs after a
1004 /// declarator, indicates the start of a function definition.
1005 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1006  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1007  if (Tok.is(tok::l_brace)) // int X() {}
1008  return true;
1009 
1010  // Handle K&R C argument lists: int X(f) int f; {}
1011  if (!getLangOpts().CPlusPlus &&
1013  return isDeclarationSpecifier();
1014 
1015  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1016  const Token &KW = NextToken();
1017  return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1018  }
1019 
1020  return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1021  Tok.is(tok::kw_try); // X() try { ... }
1022 }
1023 
1024 /// Parse either a function-definition or a declaration. We can't tell which
1025 /// we have until we read up to the compound-statement in function-definition.
1026 /// TemplateParams, if non-NULL, provides the template parameters when we're
1027 /// parsing a C++ template-declaration.
1028 ///
1029 /// function-definition: [C99 6.9.1]
1030 /// decl-specs declarator declaration-list[opt] compound-statement
1031 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1032 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1033 ///
1034 /// declaration: [C99 6.7]
1035 /// declaration-specifiers init-declarator-list[opt] ';'
1036 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1037 /// [OMP] threadprivate-directive
1038 /// [OMP] allocate-directive [TODO]
1039 ///
1041 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1042  ParsingDeclSpec &DS,
1043  AccessSpecifier AS) {
1044  MaybeParseMicrosoftAttributes(DS.getAttributes());
1045  // Parse the common declaration-specifiers piece.
1046  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1047  DeclSpecContext::DSC_top_level);
1048 
1049  // If we had a free-standing type definition with a missing semicolon, we
1050  // may get this far before the problem becomes obvious.
1051  if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1052  DS, AS, DeclSpecContext::DSC_top_level))
1053  return nullptr;
1054 
1055  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1056  // declaration-specifiers init-declarator-list[opt] ';'
1057  if (Tok.is(tok::semi)) {
1058  auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1059  assert(DeclSpec::isDeclRep(TKind));
1060  switch(TKind) {
1061  case DeclSpec::TST_class:
1062  return 5;
1063  case DeclSpec::TST_struct:
1064  return 6;
1065  case DeclSpec::TST_union:
1066  return 5;
1067  case DeclSpec::TST_enum:
1068  return 4;
1070  return 9;
1071  default:
1072  llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1073  }
1074 
1075  };
1076  // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1077  SourceLocation CorrectLocationForAttributes =
1080  LengthOfTSTToken(DS.getTypeSpecType()))
1081  : SourceLocation();
1082  ProhibitAttributes(attrs, CorrectLocationForAttributes);
1083  ConsumeToken();
1084  RecordDecl *AnonRecord = nullptr;
1085  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1086  DS, AnonRecord);
1087  DS.complete(TheDecl);
1088  if (AnonRecord) {
1089  Decl* decls[] = {AnonRecord, TheDecl};
1090  return Actions.BuildDeclaratorGroup(decls);
1091  }
1092  return Actions.ConvertDeclToDeclGroup(TheDecl);
1093  }
1094 
1095  DS.takeAttributesFrom(attrs);
1096 
1097  // ObjC2 allows prefix attributes on class interfaces and protocols.
1098  // FIXME: This still needs better diagnostics. We should only accept
1099  // attributes here, no types, etc.
1100  if (getLangOpts().ObjC && Tok.is(tok::at)) {
1101  SourceLocation AtLoc = ConsumeToken(); // the "@"
1102  if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1103  !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1104  !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1105  Diag(Tok, diag::err_objc_unexpected_attr);
1106  SkipUntil(tok::semi);
1107  return nullptr;
1108  }
1109 
1110  DS.abort();
1111 
1112  const char *PrevSpec = nullptr;
1113  unsigned DiagID;
1114  if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1115  Actions.getASTContext().getPrintingPolicy()))
1116  Diag(AtLoc, DiagID) << PrevSpec;
1117 
1118  if (Tok.isObjCAtKeyword(tok::objc_protocol))
1119  return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1120 
1121  if (Tok.isObjCAtKeyword(tok::objc_implementation))
1122  return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1123 
1124  return Actions.ConvertDeclToDeclGroup(
1125  ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1126  }
1127 
1128  // If the declspec consisted only of 'extern' and we have a string
1129  // literal following it, this must be a C++ linkage specifier like
1130  // 'extern "C"'.
1131  if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1134  Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1135  return Actions.ConvertDeclToDeclGroup(TheDecl);
1136  }
1137 
1138  return ParseDeclGroup(DS, DeclaratorContext::File);
1139 }
1140 
1142 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
1143  ParsingDeclSpec *DS,
1144  AccessSpecifier AS) {
1145  if (DS) {
1146  return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
1147  } else {
1148  ParsingDeclSpec PDS(*this);
1149  // Must temporarily exit the objective-c container scope for
1150  // parsing c constructs and re-enter objc container scope
1151  // afterwards.
1152  ObjCDeclContextSwitch ObjCDC(*this);
1153 
1154  return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1155  }
1156 }
1157 
1158 /// ParseFunctionDefinition - We parsed and verified that the specified
1159 /// Declarator is well formed. If this is a K&R-style function, read the
1160 /// parameters declaration-list, then start the compound-statement.
1161 ///
1162 /// function-definition: [C99 6.9.1]
1163 /// decl-specs declarator declaration-list[opt] compound-statement
1164 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1165 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1166 /// [C++] function-definition: [C++ 8.4]
1167 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1168 /// function-body
1169 /// [C++] function-definition: [C++ 8.4]
1170 /// decl-specifier-seq[opt] declarator function-try-block
1171 ///
1172 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1173  const ParsedTemplateInfo &TemplateInfo,
1174  LateParsedAttrList *LateParsedAttrs) {
1175  // Poison SEH identifiers so they are flagged as illegal in function bodies.
1176  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1178  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1179 
1180  // If this is C90 and the declspecs were completely missing, fudge in an
1181  // implicit int. We do this here because this is the only place where
1182  // declaration-specifiers are completely optional in the grammar.
1183  if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
1184  const char *PrevSpec;
1185  unsigned DiagID;
1186  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1188  D.getIdentifierLoc(),
1189  PrevSpec, DiagID,
1190  Policy);
1192  }
1193 
1194  // If this declaration was formed with a K&R-style identifier list for the
1195  // arguments, parse declarations for all of the args next.
1196  // int foo(a,b) int a; float b; {}
1197  if (FTI.isKNRPrototype())
1198  ParseKNRParamDeclarations(D);
1199 
1200  // We should have either an opening brace or, in a C++ constructor,
1201  // we may have a colon.
1202  if (Tok.isNot(tok::l_brace) &&
1203  (!getLangOpts().CPlusPlus ||
1204  (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1205  Tok.isNot(tok::equal)))) {
1206  Diag(Tok, diag::err_expected_fn_body);
1207 
1208  // Skip over garbage, until we get to '{'. Don't eat the '{'.
1209  SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1210 
1211  // If we didn't find the '{', bail out.
1212  if (Tok.isNot(tok::l_brace))
1213  return nullptr;
1214  }
1215 
1216  // Check to make sure that any normal attributes are allowed to be on
1217  // a definition. Late parsed attributes are checked at the end.
1218  if (Tok.isNot(tok::equal)) {
1219  for (const ParsedAttr &AL : D.getAttributes())
1220  if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1221  Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1222  }
1223 
1224  // In delayed template parsing mode, for function template we consume the
1225  // tokens and store them for late parsing at the end of the translation unit.
1226  if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1227  TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1228  Actions.canDelayFunctionBody(D)) {
1229  MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1230 
1231  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1233  Scope *ParentScope = getCurScope()->getParent();
1234 
1236  Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1238  D.complete(DP);
1239  D.getMutableDeclSpec().abort();
1240 
1241  if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1242  trySkippingFunctionBody()) {
1243  BodyScope.Exit();
1244  return Actions.ActOnSkippedFunctionBody(DP);
1245  }
1246 
1247  CachedTokens Toks;
1248  LexTemplateFunctionForLateParsing(Toks);
1249 
1250  if (DP) {
1251  FunctionDecl *FnD = DP->getAsFunction();
1252  Actions.CheckForFunctionRedefinition(FnD);
1253  Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1254  }
1255  return DP;
1256  }
1257  else if (CurParsedObjCImpl &&
1258  !TemplateInfo.TemplateParams &&
1259  (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1260  Tok.is(tok::colon)) &&
1261  Actions.CurContext->isTranslationUnit()) {
1262  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1264  Scope *ParentScope = getCurScope()->getParent();
1265 
1267  Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1269  D.complete(FuncDecl);
1270  D.getMutableDeclSpec().abort();
1271  if (FuncDecl) {
1272  // Consume the tokens and store them for later parsing.
1273  StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1274  CurParsedObjCImpl->HasCFunction = true;
1275  return FuncDecl;
1276  }
1277  // FIXME: Should we really fall through here?
1278  }
1279 
1280  // Enter a scope for the function body.
1281  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1283 
1284  // Tell the actions module that we have entered a function definition with the
1285  // specified Declarator for the function.
1286  Sema::SkipBodyInfo SkipBody;
1287  Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1288  TemplateInfo.TemplateParams
1289  ? *TemplateInfo.TemplateParams
1291  &SkipBody);
1292 
1293  if (SkipBody.ShouldSkip) {
1294  SkipFunctionBody();
1295  return Res;
1296  }
1297 
1298  // Break out of the ParsingDeclarator context before we parse the body.
1299  D.complete(Res);
1300 
1301  // Break out of the ParsingDeclSpec context, too. This const_cast is
1302  // safe because we're always the sole owner.
1303  D.getMutableDeclSpec().abort();
1304 
1305  // With abbreviated function templates - we need to explicitly add depth to
1306  // account for the implicit template parameter list induced by the template.
1307  if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
1308  if (Template->isAbbreviated() &&
1309  Template->getTemplateParameters()->getParam(0)->isImplicit())
1310  // First template parameter is implicit - meaning no explicit template
1311  // parameter list was specified.
1312  CurTemplateDepthTracker.addDepth(1);
1313 
1314  if (TryConsumeToken(tok::equal)) {
1315  assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1316 
1317  bool Delete = false;
1318  SourceLocation KWLoc;
1319  if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1320  Diag(KWLoc, getLangOpts().CPlusPlus11
1321  ? diag::warn_cxx98_compat_defaulted_deleted_function
1322  : diag::ext_defaulted_deleted_function)
1323  << 1 /* deleted */;
1324  Actions.SetDeclDeleted(Res, KWLoc);
1325  Delete = true;
1326  } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1327  Diag(KWLoc, getLangOpts().CPlusPlus11
1328  ? diag::warn_cxx98_compat_defaulted_deleted_function
1329  : diag::ext_defaulted_deleted_function)
1330  << 0 /* defaulted */;
1331  Actions.SetDeclDefaulted(Res, KWLoc);
1332  } else {
1333  llvm_unreachable("function definition after = not 'delete' or 'default'");
1334  }
1335 
1336  if (Tok.is(tok::comma)) {
1337  Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1338  << Delete;
1339  SkipUntil(tok::semi);
1340  } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1341  Delete ? "delete" : "default")) {
1342  SkipUntil(tok::semi);
1343  }
1344 
1345  Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1346  Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1347  return Res;
1348  }
1349 
1350  if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1351  trySkippingFunctionBody()) {
1352  BodyScope.Exit();
1353  Actions.ActOnSkippedFunctionBody(Res);
1354  return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1355  }
1356 
1357  if (Tok.is(tok::kw_try))
1358  return ParseFunctionTryBlock(Res, BodyScope);
1359 
1360  // If we have a colon, then we're probably parsing a C++
1361  // ctor-initializer.
1362  if (Tok.is(tok::colon)) {
1363  ParseConstructorInitializer(Res);
1364 
1365  // Recover from error.
1366  if (!Tok.is(tok::l_brace)) {
1367  BodyScope.Exit();
1368  Actions.ActOnFinishFunctionBody(Res, nullptr);
1369  return Res;
1370  }
1371  } else
1372  Actions.ActOnDefaultCtorInitializers(Res);
1373 
1374  // Late attributes are parsed in the same scope as the function body.
1375  if (LateParsedAttrs)
1376  ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1377 
1378  return ParseFunctionStatementBody(Res, BodyScope);
1379 }
1380 
1381 void Parser::SkipFunctionBody() {
1382  if (Tok.is(tok::equal)) {
1383  SkipUntil(tok::semi);
1384  return;
1385  }
1386 
1387  bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1388  if (IsFunctionTryBlock)
1389  ConsumeToken();
1390 
1391  CachedTokens Skipped;
1392  if (ConsumeAndStoreFunctionPrologue(Skipped))
1394  else {
1395  SkipUntil(tok::r_brace);
1396  while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1397  SkipUntil(tok::l_brace);
1398  SkipUntil(tok::r_brace);
1399  }
1400  }
1401 }
1402 
1403 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1404 /// types for a function with a K&R-style identifier list for arguments.
1405 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1406  // We know that the top-level of this declarator is a function.
1408 
1409  // Enter function-declaration scope, limiting any declarators to the
1410  // function prototype scope, including parameter declarators.
1411  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1413 
1414  // Read all the argument declarations.
1415  while (isDeclarationSpecifier()) {
1416  SourceLocation DSStart = Tok.getLocation();
1417 
1418  // Parse the common declaration-specifiers piece.
1419  DeclSpec DS(AttrFactory);
1420  ParseDeclarationSpecifiers(DS);
1421 
1422  // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1423  // least one declarator'.
1424  // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1425  // the declarations though. It's trivial to ignore them, really hard to do
1426  // anything else with them.
1427  if (TryConsumeToken(tok::semi)) {
1428  Diag(DSStart, diag::err_declaration_does_not_declare_param);
1429  continue;
1430  }
1431 
1432  // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1433  // than register.
1437  diag::err_invalid_storage_class_in_func_decl);
1439  }
1442  diag::err_invalid_storage_class_in_func_decl);
1444  }
1445 
1446  // Parse the first declarator attached to this declspec.
1447  Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeList);
1448  ParseDeclarator(ParmDeclarator);
1449 
1450  // Handle the full declarator list.
1451  while (1) {
1452  // If attributes are present, parse them.
1453  MaybeParseGNUAttributes(ParmDeclarator);
1454 
1455  // Ask the actions module to compute the type for this declarator.
1456  Decl *Param =
1457  Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1458 
1459  if (Param &&
1460  // A missing identifier has already been diagnosed.
1461  ParmDeclarator.getIdentifier()) {
1462 
1463  // Scan the argument list looking for the correct param to apply this
1464  // type.
1465  for (unsigned i = 0; ; ++i) {
1466  // C99 6.9.1p6: those declarators shall declare only identifiers from
1467  // the identifier list.
1468  if (i == FTI.NumParams) {
1469  Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1470  << ParmDeclarator.getIdentifier();
1471  break;
1472  }
1473 
1474  if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1475  // Reject redefinitions of parameters.
1476  if (FTI.Params[i].Param) {
1477  Diag(ParmDeclarator.getIdentifierLoc(),
1478  diag::err_param_redefinition)
1479  << ParmDeclarator.getIdentifier();
1480  } else {
1481  FTI.Params[i].Param = Param;
1482  }
1483  break;
1484  }
1485  }
1486  }
1487 
1488  // If we don't have a comma, it is either the end of the list (a ';') or
1489  // an error, bail out.
1490  if (Tok.isNot(tok::comma))
1491  break;
1492 
1493  ParmDeclarator.clear();
1494 
1495  // Consume the comma.
1496  ParmDeclarator.setCommaLoc(ConsumeToken());
1497 
1498  // Parse the next declarator.
1499  ParseDeclarator(ParmDeclarator);
1500  }
1501 
1502  // Consume ';' and continue parsing.
1503  if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1504  continue;
1505 
1506  // Otherwise recover by skipping to next semi or mandatory function body.
1507  if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1508  break;
1509  TryConsumeToken(tok::semi);
1510  }
1511 
1512  // The actions module must verify that all arguments were declared.
1514 }
1515 
1516 
1517 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1518 /// allowed to be a wide string, and is not subject to character translation.
1519 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1520 /// asm label as opposed to an asm statement, because such a construct does not
1521 /// behave well.
1522 ///
1523 /// [GNU] asm-string-literal:
1524 /// string-literal
1525 ///
1526 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1527  if (!isTokenStringLiteral()) {
1528  Diag(Tok, diag::err_expected_string_literal)
1529  << /*Source='in...'*/0 << "'asm'";
1530  return ExprError();
1531  }
1532 
1534  if (!AsmString.isInvalid()) {
1535  const auto *SL = cast<StringLiteral>(AsmString.get());
1536  if (!SL->isAscii()) {
1537  Diag(Tok, diag::err_asm_operand_wide_string_literal)
1538  << SL->isWide()
1539  << SL->getSourceRange();
1540  return ExprError();
1541  }
1542  if (ForAsmLabel && SL->getString().empty()) {
1543  Diag(Tok, diag::err_asm_operand_wide_string_literal)
1544  << 2 /* an empty */ << SL->getSourceRange();
1545  return ExprError();
1546  }
1547  }
1548  return AsmString;
1549 }
1550 
1551 /// ParseSimpleAsm
1552 ///
1553 /// [GNU] simple-asm-expr:
1554 /// 'asm' '(' asm-string-literal ')'
1555 ///
1556 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1557  assert(Tok.is(tok::kw_asm) && "Not an asm!");
1558  SourceLocation Loc = ConsumeToken();
1559 
1560  if (isGNUAsmQualifier(Tok)) {
1561  // Remove from the end of 'asm' to the end of the asm qualifier.
1562  SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1563  PP.getLocForEndOfToken(Tok.getLocation()));
1564  Diag(Tok, diag::err_global_asm_qualifier_ignored)
1565  << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1566  << FixItHint::CreateRemoval(RemovalRange);
1567  ConsumeToken();
1568  }
1569 
1570  BalancedDelimiterTracker T(*this, tok::l_paren);
1571  if (T.consumeOpen()) {
1572  Diag(Tok, diag::err_expected_lparen_after) << "asm";
1573  return ExprError();
1574  }
1575 
1576  ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1577 
1578  if (!Result.isInvalid()) {
1579  // Close the paren and get the location of the end bracket
1580  T.consumeClose();
1581  if (EndLoc)
1582  *EndLoc = T.getCloseLocation();
1583  } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1584  if (EndLoc)
1585  *EndLoc = Tok.getLocation();
1586  ConsumeParen();
1587  }
1588 
1589  return Result;
1590 }
1591 
1592 /// Get the TemplateIdAnnotation from the token and put it in the
1593 /// cleanup pool so that it gets destroyed when parsing the current top level
1594 /// declaration is finished.
1595 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1596  assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1598  Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1599  return Id;
1600 }
1601 
1602 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1603  // Push the current token back into the token stream (or revert it if it is
1604  // cached) and use an annotation scope token for current token.
1605  if (PP.isBacktrackEnabled())
1606  PP.RevertCachedTokens(1);
1607  else
1608  PP.EnterToken(Tok, /*IsReinject=*/true);
1609  Tok.setKind(tok::annot_cxxscope);
1611  Tok.setAnnotationRange(SS.getRange());
1612 
1613  // In case the tokens were cached, have Preprocessor replace them
1614  // with the annotation token. We don't need to do this if we've
1615  // just reverted back to a prior state.
1616  if (IsNewAnnotation)
1617  PP.AnnotateCachedTokens(Tok);
1618 }
1619 
1620 /// Attempt to classify the name at the current token position. This may
1621 /// form a type, scope or primary expression annotation, or replace the token
1622 /// with a typo-corrected keyword. This is only appropriate when the current
1623 /// name must refer to an entity which has already been declared.
1624 ///
1625 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1626 /// no typo correction will be performed.
1627 Parser::AnnotatedNameKind
1628 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) {
1629  assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1630 
1631  const bool EnteringContext = false;
1632  const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1633 
1634  CXXScopeSpec SS;
1635  if (getLangOpts().CPlusPlus &&
1636  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1637  /*ObjectHadErrors=*/false,
1638  EnteringContext))
1639  return ANK_Error;
1640 
1641  if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1642  if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1643  return ANK_Error;
1644  return ANK_Unresolved;
1645  }
1646 
1647  IdentifierInfo *Name = Tok.getIdentifierInfo();
1648  SourceLocation NameLoc = Tok.getLocation();
1649 
1650  // FIXME: Move the tentative declaration logic into ClassifyName so we can
1651  // typo-correct to tentatively-declared identifiers.
1652  if (isTentativelyDeclared(Name)) {
1653  // Identifier has been tentatively declared, and thus cannot be resolved as
1654  // an expression. Fall back to annotating it as a type.
1655  if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1656  return ANK_Error;
1657  return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1658  }
1659 
1660  Token Next = NextToken();
1661 
1662  // Look up and classify the identifier. We don't perform any typo-correction
1663  // after a scope specifier, because in general we can't recover from typos
1664  // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1665  // jump back into scope specifier parsing).
1666  Sema::NameClassification Classification = Actions.ClassifyName(
1667  getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1668 
1669  // If name lookup found nothing and we guessed that this was a template name,
1670  // double-check before committing to that interpretation. C++20 requires that
1671  // we interpret this as a template-id if it can be, but if it can't be, then
1672  // this is an error recovery case.
1673  if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1674  isTemplateArgumentList(1) == TPResult::False) {
1675  // It's not a template-id; re-classify without the '<' as a hint.
1676  Token FakeNext = Next;
1677  FakeNext.setKind(tok::unknown);
1678  Classification =
1679  Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1680  SS.isEmpty() ? CCC : nullptr);
1681  }
1682 
1683  switch (Classification.getKind()) {
1684  case Sema::NC_Error:
1685  return ANK_Error;
1686 
1687  case Sema::NC_Keyword:
1688  // The identifier was typo-corrected to a keyword.
1689  Tok.setIdentifierInfo(Name);
1690  Tok.setKind(Name->getTokenID());
1691  PP.TypoCorrectToken(Tok);
1692  if (SS.isNotEmpty())
1693  AnnotateScopeToken(SS, !WasScopeAnnotation);
1694  // We've "annotated" this as a keyword.
1695  return ANK_Success;
1696 
1697  case Sema::NC_Unknown:
1698  // It's not something we know about. Leave it unannotated.
1699  break;
1700 
1701  case Sema::NC_Type: {
1702  if (TryAltiVecVectorToken())
1703  // vector has been found as a type id when altivec is enabled but
1704  // this is followed by a declaration specifier so this is really the
1705  // altivec vector token. Leave it unannotated.
1706  break;
1707  SourceLocation BeginLoc = NameLoc;
1708  if (SS.isNotEmpty())
1709  BeginLoc = SS.getBeginLoc();
1710 
1711  /// An Objective-C object type followed by '<' is a specialization of
1712  /// a parameterized class type or a protocol-qualified type.
1713  ParsedType Ty = Classification.getType();
1714  if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1715  (Ty.get()->isObjCObjectType() ||
1716  Ty.get()->isObjCObjectPointerType())) {
1717  // Consume the name.
1719  SourceLocation NewEndLoc;
1720  TypeResult NewType
1721  = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1722  /*consumeLastToken=*/false,
1723  NewEndLoc);
1724  if (NewType.isUsable())
1725  Ty = NewType.get();
1726  else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1727  return ANK_Error;
1728  }
1729 
1730  Tok.setKind(tok::annot_typename);
1731  setTypeAnnotation(Tok, Ty);
1732  Tok.setAnnotationEndLoc(Tok.getLocation());
1733  Tok.setLocation(BeginLoc);
1734  PP.AnnotateCachedTokens(Tok);
1735  return ANK_Success;
1736  }
1737 
1738  case Sema::NC_OverloadSet:
1739  Tok.setKind(tok::annot_overload_set);
1740  setExprAnnotation(Tok, Classification.getExpression());
1741  Tok.setAnnotationEndLoc(NameLoc);
1742  if (SS.isNotEmpty())
1743  Tok.setLocation(SS.getBeginLoc());
1744  PP.AnnotateCachedTokens(Tok);
1745  return ANK_Success;
1746 
1747  case Sema::NC_NonType:
1748  if (TryAltiVecVectorToken())
1749  // vector has been found as a non-type id when altivec is enabled but
1750  // this is followed by a declaration specifier so this is really the
1751  // altivec vector token. Leave it unannotated.
1752  break;
1753  Tok.setKind(tok::annot_non_type);
1754  setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1755  Tok.setLocation(NameLoc);
1756  Tok.setAnnotationEndLoc(NameLoc);
1757  PP.AnnotateCachedTokens(Tok);
1758  if (SS.isNotEmpty())
1759  AnnotateScopeToken(SS, !WasScopeAnnotation);
1760  return ANK_Success;
1761 
1764  Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1765  ? tok::annot_non_type_undeclared
1766  : tok::annot_non_type_dependent);
1767  setIdentifierAnnotation(Tok, Name);
1768  Tok.setLocation(NameLoc);
1769  Tok.setAnnotationEndLoc(NameLoc);
1770  PP.AnnotateCachedTokens(Tok);
1771  if (SS.isNotEmpty())
1772  AnnotateScopeToken(SS, !WasScopeAnnotation);
1773  return ANK_Success;
1774 
1775  case Sema::NC_TypeTemplate:
1776  if (Next.isNot(tok::less)) {
1777  // This may be a type template being used as a template template argument.
1778  if (SS.isNotEmpty())
1779  AnnotateScopeToken(SS, !WasScopeAnnotation);
1780  return ANK_TemplateName;
1781  }
1782  LLVM_FALLTHROUGH;
1783  case Sema::NC_VarTemplate:
1786  // We have a type, variable or function template followed by '<'.
1787  ConsumeToken();
1788  UnqualifiedId Id;
1789  Id.setIdentifier(Name, NameLoc);
1790  if (AnnotateTemplateIdToken(
1791  TemplateTy::make(Classification.getTemplateName()),
1792  Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1793  return ANK_Error;
1794  return ANK_Success;
1795  }
1796  case Sema::NC_Concept: {
1797  UnqualifiedId Id;
1798  Id.setIdentifier(Name, NameLoc);
1799  if (Next.is(tok::less))
1800  // We have a concept name followed by '<'. Consume the identifier token so
1801  // we reach the '<' and annotate it.
1802  ConsumeToken();
1803  if (AnnotateTemplateIdToken(
1804  TemplateTy::make(Classification.getTemplateName()),
1805  Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1806  /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true))
1807  return ANK_Error;
1808  return ANK_Success;
1809  }
1810  }
1811 
1812  // Unable to classify the name, but maybe we can annotate a scope specifier.
1813  if (SS.isNotEmpty())
1814  AnnotateScopeToken(SS, !WasScopeAnnotation);
1815  return ANK_Unresolved;
1816 }
1817 
1818 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1819  assert(Tok.isNot(tok::identifier));
1820  Diag(Tok, diag::ext_keyword_as_ident)
1821  << PP.getSpelling(Tok)
1822  << DisableKeyword;
1823  if (DisableKeyword)
1825  Tok.setKind(tok::identifier);
1826  return true;
1827 }
1828 
1829 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1830 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1831 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1832 /// with a single annotation token representing the typename or C++ scope
1833 /// respectively.
1834 /// This simplifies handling of C++ scope specifiers and allows efficient
1835 /// backtracking without the need to re-parse and resolve nested-names and
1836 /// typenames.
1837 /// It will mainly be called when we expect to treat identifiers as typenames
1838 /// (if they are typenames). For example, in C we do not expect identifiers
1839 /// inside expressions to be treated as typenames so it will not be called
1840 /// for expressions in C.
1841 /// The benefit for C/ObjC is that a typename will be annotated and
1842 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1843 /// will not be called twice, once to check whether we have a declaration
1844 /// specifier, and another one to get the actual type inside
1845 /// ParseDeclarationSpecifiers).
1846 ///
1847 /// This returns true if an error occurred.
1848 ///
1849 /// Note that this routine emits an error if you call it with ::new or ::delete
1850 /// as the current tokens, so only call it in contexts where these are invalid.
1852  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1853  Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1854  Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1855  Tok.is(tok::kw___super)) &&
1856  "Cannot be a type or scope token!");
1857 
1858  if (Tok.is(tok::kw_typename)) {
1859  // MSVC lets you do stuff like:
1860  // typename typedef T_::D D;
1861  //
1862  // We will consume the typedef token here and put it back after we have
1863  // parsed the first identifier, transforming it into something more like:
1864  // typename T_::D typedef D;
1865  if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1866  Token TypedefToken;
1867  PP.Lex(TypedefToken);
1868  bool Result = TryAnnotateTypeOrScopeToken();
1869  PP.EnterToken(Tok, /*IsReinject=*/true);
1870  Tok = TypedefToken;
1871  if (!Result)
1872  Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1873  return Result;
1874  }
1875 
1876  // Parse a C++ typename-specifier, e.g., "typename T::type".
1877  //
1878  // typename-specifier:
1879  // 'typename' '::' [opt] nested-name-specifier identifier
1880  // 'typename' '::' [opt] nested-name-specifier template [opt]
1881  // simple-template-id
1882  SourceLocation TypenameLoc = ConsumeToken();
1883  CXXScopeSpec SS;
1884  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1885  /*ObjectHadErrors=*/false,
1886  /*EnteringContext=*/false, nullptr,
1887  /*IsTypename*/ true))
1888  return true;
1889  if (SS.isEmpty()) {
1890  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1891  Tok.is(tok::annot_decltype)) {
1892  // Attempt to recover by skipping the invalid 'typename'
1893  if (Tok.is(tok::annot_decltype) ||
1894  (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
1895  unsigned DiagID = diag::err_expected_qualified_after_typename;
1896  // MS compatibility: MSVC permits using known types with typename.
1897  // e.g. "typedef typename T* pointer_type"
1898  if (getLangOpts().MicrosoftExt)
1899  DiagID = diag::warn_expected_qualified_after_typename;
1900  Diag(Tok.getLocation(), DiagID);
1901  return false;
1902  }
1903  }
1904  if (Tok.isEditorPlaceholder())
1905  return true;
1906 
1907  Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1908  return true;
1909  }
1910 
1911  TypeResult Ty;
1912  if (Tok.is(tok::identifier)) {
1913  // FIXME: check whether the next token is '<', first!
1914  Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1915  *Tok.getIdentifierInfo(),
1916  Tok.getLocation());
1917  } else if (Tok.is(tok::annot_template_id)) {
1918  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1919  if (!TemplateId->mightBeType()) {
1920  Diag(Tok, diag::err_typename_refers_to_non_type_template)
1921  << Tok.getAnnotationRange();
1922  return true;
1923  }
1924 
1925  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1926  TemplateId->NumArgs);
1927 
1928  Ty = TemplateId->isInvalid()
1929  ? TypeError()
1930  : Actions.ActOnTypenameType(
1931  getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
1932  TemplateId->Template, TemplateId->Name,
1933  TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
1934  TemplateArgsPtr, TemplateId->RAngleLoc);
1935  } else {
1936  Diag(Tok, diag::err_expected_type_name_after_typename)
1937  << SS.getRange();
1938  return true;
1939  }
1940 
1941  SourceLocation EndLoc = Tok.getLastLoc();
1942  Tok.setKind(tok::annot_typename);
1943  setTypeAnnotation(Tok, Ty);
1944  Tok.setAnnotationEndLoc(EndLoc);
1945  Tok.setLocation(TypenameLoc);
1946  PP.AnnotateCachedTokens(Tok);
1947  return false;
1948  }
1949 
1950  // Remembers whether the token was originally a scope annotation.
1951  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1952 
1953  CXXScopeSpec SS;
1954  if (getLangOpts().CPlusPlus)
1955  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1956  /*ObjectHadErrors=*/false,
1957  /*EnteringContext*/ false))
1958  return true;
1959 
1960  return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
1961 }
1962 
1963 /// Try to annotate a type or scope token, having already parsed an
1964 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1965 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1967  bool IsNewScope) {
1968  if (Tok.is(tok::identifier)) {
1969  // Determine whether the identifier is a type name.
1970  if (ParsedType Ty = Actions.getTypeName(
1971  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1972  false, NextToken().is(tok::period), nullptr,
1973  /*IsCtorOrDtorName=*/false,
1974  /*NonTrivialTypeSourceInfo*/true,
1975  /*IsClassTemplateDeductionContext*/true)) {
1976  SourceLocation BeginLoc = Tok.getLocation();
1977  if (SS.isNotEmpty()) // it was a C++ qualified type name.
1978  BeginLoc = SS.getBeginLoc();
1979 
1980  /// An Objective-C object type followed by '<' is a specialization of
1981  /// a parameterized class type or a protocol-qualified type.
1982  if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1983  (Ty.get()->isObjCObjectType() ||
1984  Ty.get()->isObjCObjectPointerType())) {
1985  // Consume the name.
1987  SourceLocation NewEndLoc;
1988  TypeResult NewType
1989  = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1990  /*consumeLastToken=*/false,
1991  NewEndLoc);
1992  if (NewType.isUsable())
1993  Ty = NewType.get();
1994  else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1995  return false;
1996  }
1997 
1998  // This is a typename. Replace the current token in-place with an
1999  // annotation type token.
2000  Tok.setKind(tok::annot_typename);
2001  setTypeAnnotation(Tok, Ty);
2002  Tok.setAnnotationEndLoc(Tok.getLocation());
2003  Tok.setLocation(BeginLoc);
2004 
2005  // In case the tokens were cached, have Preprocessor replace
2006  // them with the annotation token.
2007  PP.AnnotateCachedTokens(Tok);
2008  return false;
2009  }
2010 
2011  if (!getLangOpts().CPlusPlus) {
2012  // If we're in C, we can't have :: tokens at all (the lexer won't return
2013  // them). If the identifier is not a type, then it can't be scope either,
2014  // just early exit.
2015  return false;
2016  }
2017 
2018  // If this is a template-id, annotate with a template-id or type token.
2019  // FIXME: This appears to be dead code. We already have formed template-id
2020  // tokens when parsing the scope specifier; this can never form a new one.
2021  if (NextToken().is(tok::less)) {
2022  TemplateTy Template;
2024  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2025  bool MemberOfUnknownSpecialization;
2026  if (TemplateNameKind TNK = Actions.isTemplateName(
2027  getCurScope(), SS,
2028  /*hasTemplateKeyword=*/false, TemplateName,
2029  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2030  MemberOfUnknownSpecialization)) {
2031  // Only annotate an undeclared template name as a template-id if the
2032  // following tokens have the form of a template argument list.
2033  if (TNK != TNK_Undeclared_template ||
2034  isTemplateArgumentList(1) != TPResult::False) {
2035  // Consume the identifier.
2036  ConsumeToken();
2037  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2038  TemplateName)) {
2039  // If an unrecoverable error occurred, we need to return true here,
2040  // because the token stream is in a damaged state. We may not
2041  // return a valid identifier.
2042  return true;
2043  }
2044  }
2045  }
2046  }
2047 
2048  // The current token, which is either an identifier or a
2049  // template-id, is not part of the annotation. Fall through to
2050  // push that token back into the stream and complete the C++ scope
2051  // specifier annotation.
2052  }
2053 
2054  if (Tok.is(tok::annot_template_id)) {
2055  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2056  if (TemplateId->Kind == TNK_Type_template) {
2057  // A template-id that refers to a type was parsed into a
2058  // template-id annotation in a context where we weren't allowed
2059  // to produce a type annotation token. Update the template-id
2060  // annotation token to a type annotation token now.
2061  AnnotateTemplateIdTokenAsType(SS);
2062  return false;
2063  }
2064  }
2065 
2066  if (SS.isEmpty())
2067  return false;
2068 
2069  // A C++ scope specifier that isn't followed by a typename.
2070  AnnotateScopeToken(SS, IsNewScope);
2071  return false;
2072 }
2073 
2074 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2075 /// annotates C++ scope specifiers and template-ids. This returns
2076 /// true if there was an error that could not be recovered from.
2077 ///
2078 /// Note that this routine emits an error if you call it with ::new or ::delete
2079 /// as the current tokens, so only call it in contexts where these are invalid.
2080 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2081  assert(getLangOpts().CPlusPlus &&
2082  "Call sites of this function should be guarded by checking for C++");
2083  assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2084 
2085  CXXScopeSpec SS;
2086  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2087  /*ObjectHadErrors=*/false,
2088  EnteringContext))
2089  return true;
2090  if (SS.isEmpty())
2091  return false;
2092 
2093  AnnotateScopeToken(SS, true);
2094  return false;
2095 }
2096 
2097 bool Parser::isTokenEqualOrEqualTypo() {
2098  tok::TokenKind Kind = Tok.getKind();
2099  switch (Kind) {
2100  default:
2101  return false;
2102  case tok::ampequal: // &=
2103  case tok::starequal: // *=
2104  case tok::plusequal: // +=
2105  case tok::minusequal: // -=
2106  case tok::exclaimequal: // !=
2107  case tok::slashequal: // /=
2108  case tok::percentequal: // %=
2109  case tok::lessequal: // <=
2110  case tok::lesslessequal: // <<=
2111  case tok::greaterequal: // >=
2112  case tok::greatergreaterequal: // >>=
2113  case tok::caretequal: // ^=
2114  case tok::pipeequal: // |=
2115  case tok::equalequal: // ==
2116  Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2117  << Kind
2119  LLVM_FALLTHROUGH;
2120  case tok::equal:
2121  return true;
2122  }
2123 }
2124 
2125 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2126  assert(Tok.is(tok::code_completion));
2127  PrevTokLocation = Tok.getLocation();
2128 
2129  for (Scope *S = getCurScope(); S; S = S->getParent()) {
2130  if (S->getFlags() & Scope::FnScope) {
2131  cutOffParsing();
2134  return PrevTokLocation;
2135  }
2136 
2137  if (S->getFlags() & Scope::ClassScope) {
2138  cutOffParsing();
2140  return PrevTokLocation;
2141  }
2142  }
2143 
2144  cutOffParsing();
2146  return PrevTokLocation;
2147 }
2148 
2149 // Code-completion pass-through functions
2150 
2151 void Parser::CodeCompleteDirective(bool InConditional) {
2152  Actions.CodeCompletePreprocessorDirective(InConditional);
2153 }
2154 
2155 void Parser::CodeCompleteInConditionalExclusion() {
2157 }
2158 
2159 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2160  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2161 }
2162 
2163 void Parser::CodeCompletePreprocessorExpression() {
2165 }
2166 
2167 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2169  unsigned ArgumentIndex) {
2171  ArgumentIndex);
2172 }
2173 
2174 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2175  Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2176 }
2177 
2178 void Parser::CodeCompleteNaturalLanguage() {
2179  Actions.CodeCompleteNaturalLanguage();
2180 }
2181 
2182 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2183  assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2184  "Expected '__if_exists' or '__if_not_exists'");
2185  Result.IsIfExists = Tok.is(tok::kw___if_exists);
2186  Result.KeywordLoc = ConsumeToken();
2187 
2188  BalancedDelimiterTracker T(*this, tok::l_paren);
2189  if (T.consumeOpen()) {
2190  Diag(Tok, diag::err_expected_lparen_after)
2191  << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2192  return true;
2193  }
2194 
2195  // Parse nested-name-specifier.
2196  if (getLangOpts().CPlusPlus)
2197  ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2198  /*ObjectHadErrors=*/false,
2199  /*EnteringContext=*/false);
2200 
2201  // Check nested-name specifier.
2202  if (Result.SS.isInvalid()) {
2203  T.skipToEnd();
2204  return true;
2205  }
2206 
2207  // Parse the unqualified-id.
2208  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2209  if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2210  /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2211  /*AllowDestructorName*/ true,
2212  /*AllowConstructorName*/ true,
2213  /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2214  Result.Name)) {
2215  T.skipToEnd();
2216  return true;
2217  }
2218 
2219  if (T.consumeClose())
2220  return true;
2221 
2222  // Check if the symbol exists.
2223  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2224  Result.IsIfExists, Result.SS,
2225  Result.Name)) {
2226  case Sema::IER_Exists:
2227  Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2228  break;
2229 
2231  Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2232  break;
2233 
2234  case Sema::IER_Dependent:
2235  Result.Behavior = IEB_Dependent;
2236  break;
2237 
2238  case Sema::IER_Error:
2239  return true;
2240  }
2241 
2242  return false;
2243 }
2244 
2245 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2246  IfExistsCondition Result;
2247  if (ParseMicrosoftIfExistsCondition(Result))
2248  return;
2249 
2250  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2251  if (Braces.consumeOpen()) {
2252  Diag(Tok, diag::err_expected) << tok::l_brace;
2253  return;
2254  }
2255 
2256  switch (Result.Behavior) {
2257  case IEB_Parse:
2258  // Parse declarations below.
2259  break;
2260 
2261  case IEB_Dependent:
2262  llvm_unreachable("Cannot have a dependent external declaration");
2263 
2264  case IEB_Skip:
2265  Braces.skipToEnd();
2266  return;
2267  }
2268 
2269  // Parse the declarations.
2270  // FIXME: Support module import within __if_exists?
2271  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2272  ParsedAttributesWithRange attrs(AttrFactory);
2273  MaybeParseCXX11Attributes(attrs);
2274  DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2275  if (Result && !getCurScope()->getParent())
2276  Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2277  }
2278  Braces.consumeClose();
2279 }
2280 
2281 /// Parse a declaration beginning with the 'module' keyword or C++20
2282 /// context-sensitive keyword (optionally preceded by 'export').
2283 ///
2284 /// module-declaration: [Modules TS + P0629R0]
2285 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2286 ///
2287 /// global-module-fragment: [C++2a]
2288 /// 'module' ';' top-level-declaration-seq[opt]
2289 /// module-declaration: [C++2a]
2290 /// 'export'[opt] 'module' module-name module-partition[opt]
2291 /// attribute-specifier-seq[opt] ';'
2292 /// private-module-fragment: [C++2a]
2293 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2294 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) {
2295  SourceLocation StartLoc = Tok.getLocation();
2296 
2297  Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2300 
2301  assert(
2302  (Tok.is(tok::kw_module) ||
2303  (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2304  "not a module declaration");
2305  SourceLocation ModuleLoc = ConsumeToken();
2306 
2307  // Attributes appear after the module name, not before.
2308  // FIXME: Suggest moving the attributes later with a fixit.
2309  DiagnoseAndSkipCXX11Attributes();
2310 
2311  // Parse a global-module-fragment, if present.
2312  if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2313  SourceLocation SemiLoc = ConsumeToken();
2314  if (!IsFirstDecl) {
2315  Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2316  << SourceRange(StartLoc, SemiLoc);
2317  return nullptr;
2318  }
2319  if (MDK == Sema::ModuleDeclKind::Interface) {
2320  Diag(StartLoc, diag::err_module_fragment_exported)
2321  << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2322  }
2323  return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2324  }
2325 
2326  // Parse a private-module-fragment, if present.
2327  if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2328  NextToken().is(tok::kw_private)) {
2329  if (MDK == Sema::ModuleDeclKind::Interface) {
2330  Diag(StartLoc, diag::err_module_fragment_exported)
2331  << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2332  }
2333  ConsumeToken();
2334  SourceLocation PrivateLoc = ConsumeToken();
2335  DiagnoseAndSkipCXX11Attributes();
2336  ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2337  return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2338  }
2339 
2341  if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2342  return nullptr;
2343 
2344  // Parse the optional module-partition.
2345  if (Tok.is(tok::colon)) {
2346  SourceLocation ColonLoc = ConsumeToken();
2348  if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false))
2349  return nullptr;
2350 
2351  // FIXME: Support module partition declarations.
2352  Diag(ColonLoc, diag::err_unsupported_module_partition)
2353  << SourceRange(ColonLoc, Partition.back().second);
2354  // Recover by parsing as a non-partition.
2355  }
2356 
2357  // We don't support any module attributes yet; just parse them and diagnose.
2358  ParsedAttributesWithRange Attrs(AttrFactory);
2359  MaybeParseCXX11Attributes(Attrs);
2360  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2361 
2362  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2363 
2364  return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl);
2365 }
2366 
2367 /// Parse a module import declaration. This is essentially the same for
2368 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2369 /// and the trailing optional attributes (in C++).
2370 ///
2371 /// [ObjC] @import declaration:
2372 /// '@' 'import' module-name ';'
2373 /// [ModTS] module-import-declaration:
2374 /// 'import' module-name attribute-specifier-seq[opt] ';'
2375 /// [C++2a] module-import-declaration:
2376 /// 'export'[opt] 'import' module-name
2377 /// attribute-specifier-seq[opt] ';'
2378 /// 'export'[opt] 'import' module-partition
2379 /// attribute-specifier-seq[opt] ';'
2380 /// 'export'[opt] 'import' header-name
2381 /// attribute-specifier-seq[opt] ';'
2382 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
2383  SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2384 
2385  SourceLocation ExportLoc;
2386  TryConsumeToken(tok::kw_export, ExportLoc);
2387 
2388  assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2389  : Tok.isObjCAtKeyword(tok::objc_import)) &&
2390  "Improper start to module import");
2391  bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2392  SourceLocation ImportLoc = ConsumeToken();
2393 
2395  Module *HeaderUnit = nullptr;
2396 
2397  if (Tok.is(tok::header_name)) {
2398  // This is a header import that the preprocessor decided we should skip
2399  // because it was malformed in some way. Parse and ignore it; it's already
2400  // been diagnosed.
2401  ConsumeToken();
2402  } else if (Tok.is(tok::annot_header_unit)) {
2403  // This is a header import that the preprocessor mapped to a module import.
2404  HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2405  ConsumeAnnotationToken();
2406  } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
2407  SourceLocation ColonLoc = ConsumeToken();
2408  if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2409  return nullptr;
2410 
2411  // FIXME: Support module partition import.
2412  Diag(ColonLoc, diag::err_unsupported_module_partition)
2413  << SourceRange(ColonLoc, Path.back().second);
2414  return nullptr;
2415  } else {
2416  if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2417  return nullptr;
2418  }
2419 
2420  ParsedAttributesWithRange Attrs(AttrFactory);
2421  MaybeParseCXX11Attributes(Attrs);
2422  // We don't support any module import attributes yet.
2423  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2424 
2425  if (PP.hadModuleLoaderFatalFailure()) {
2426  // With a fatal failure in the module loader, we abort parsing.
2427  cutOffParsing();
2428  return nullptr;
2429  }
2430 
2431  DeclResult Import;
2432  if (HeaderUnit)
2433  Import =
2434  Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2435  else if (!Path.empty())
2436  Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path);
2437  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2438  if (Import.isInvalid())
2439  return nullptr;
2440 
2441  // Using '@import' in framework headers requires modules to be enabled so that
2442  // the header is parseable. Emit a warning to make the user aware.
2443  if (IsObjCAtImport && AtLoc.isValid()) {
2444  auto &SrcMgr = PP.getSourceManager();
2445  auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
2446  if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
2447  .endswith(".framework"))
2448  Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2449  }
2450 
2451  return Import.get();
2452 }
2453 
2454 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2455 /// grammar).
2456 ///
2457 /// module-name:
2458 /// module-name-qualifier[opt] identifier
2459 /// module-name-qualifier:
2460 /// module-name-qualifier[opt] identifier '.'
2461 bool Parser::ParseModuleName(
2462  SourceLocation UseLoc,
2463  SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2464  bool IsImport) {
2465  // Parse the module path.
2466  while (true) {
2467  if (!Tok.is(tok::identifier)) {
2468  if (Tok.is(tok::code_completion)) {
2469  cutOffParsing();
2470  Actions.CodeCompleteModuleImport(UseLoc, Path);
2471  return true;
2472  }
2473 
2474  Diag(Tok, diag::err_module_expected_ident) << IsImport;
2475  SkipUntil(tok::semi);
2476  return true;
2477  }
2478 
2479  // Record this part of the module path.
2480  Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2481  ConsumeToken();
2482 
2483  if (Tok.isNot(tok::period))
2484  return false;
2485 
2486  ConsumeToken();
2487  }
2488 }
2489 
2490 /// Try recover parser when module annotation appears where it must not
2491 /// be found.
2492 /// \returns false if the recover was successful and parsing may be continued, or
2493 /// true if parser must bail out to top level and handle the token there.
2494 bool Parser::parseMisplacedModuleImport() {
2495  while (true) {
2496  switch (Tok.getKind()) {
2497  case tok::annot_module_end:
2498  // If we recovered from a misplaced module begin, we expect to hit a
2499  // misplaced module end too. Stay in the current context when this
2500  // happens.
2501  if (MisplacedModuleBeginCount) {
2502  --MisplacedModuleBeginCount;
2503  Actions.ActOnModuleEnd(Tok.getLocation(),
2504  reinterpret_cast<Module *>(
2505  Tok.getAnnotationValue()));
2506  ConsumeAnnotationToken();
2507  continue;
2508  }
2509  // Inform caller that recovery failed, the error must be handled at upper
2510  // level. This will generate the desired "missing '}' at end of module"
2511  // diagnostics on the way out.
2512  return true;
2513  case tok::annot_module_begin:
2514  // Recover by entering the module (Sema will diagnose).
2515  Actions.ActOnModuleBegin(Tok.getLocation(),
2516  reinterpret_cast<Module *>(
2517  Tok.getAnnotationValue()));
2518  ConsumeAnnotationToken();
2519  ++MisplacedModuleBeginCount;
2520  continue;
2521  case tok::annot_module_include:
2522  // Module import found where it should not be, for instance, inside a
2523  // namespace. Recover by importing the module.
2524  Actions.ActOnModuleInclude(Tok.getLocation(),
2525  reinterpret_cast<Module *>(
2526  Tok.getAnnotationValue()));
2527  ConsumeAnnotationToken();
2528  // If there is another module import, process it.
2529  continue;
2530  default:
2531  return false;
2532  }
2533  }
2534  return false;
2535 }
2536 
2537 bool BalancedDelimiterTracker::diagnoseOverflow() {
2538  P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2539  << P.getLangOpts().BracketDepth;
2540  P.Diag(P.Tok, diag::note_bracket_depth);
2541  P.cutOffParsing();
2542  return true;
2543 }
2544 
2546  const char *Msg,
2547  tok::TokenKind SkipToTok) {
2548  LOpen = P.Tok.getLocation();
2549  if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2550  if (SkipToTok != tok::unknown)
2551  P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2552  return true;
2553  }
2554 
2555  if (getDepth() < P.getLangOpts().BracketDepth)
2556  return false;
2557 
2558  return diagnoseOverflow();
2559 }
2560 
2561 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2562  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2563 
2564  if (P.Tok.is(tok::annot_module_end))
2565  P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2566  else
2567  P.Diag(P.Tok, diag::err_expected) << Close;
2568  P.Diag(LOpen, diag::note_matching) << Kind;
2569 
2570  // If we're not already at some kind of closing bracket, skip to our closing
2571  // token.
2572  if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2573  P.Tok.isNot(tok::r_square) &&
2574  P.SkipUntil(Close, FinalToken,
2576  P.Tok.is(Close))
2577  LClose = P.ConsumeAnyToken();
2578  return true;
2579 }
2580 
2583  consumeClose();
2584 }
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
clang::Sema::IER_Error
@ IER_Error
An error occurred.
Definition: Sema.h:5625
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1316
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:951
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:423
clang::Token::getAnnotationRange
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
Definition: Token.h:160
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::Sema::NC_FunctionTemplate
@ NC_FunctionTemplate
The name was classified as a function template name.
Definition: Sema.h:2446
clang::Sema::ActOnGlobalModuleFragmentDecl
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
Definition: SemaModule.cpp:58
clang::Sema::MarkAsLateParsedTemplate
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
Definition: SemaTemplate.cpp:10932
clang::ParsingDeclSpec
A class for parsing a DeclSpec.
Definition: RAIIObjectsForParser.h:175
clang::Scope::FunctionPrototypeScope
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:81
clang::Sema::PCC_Namespace
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
Definition: Sema.h:12383
clang::Sema::NC_NonType
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:2427
clang::Token::hasLeadingSpace
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:272
clang::DiagnosticBuilder
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1264
clang::TemplateIdAnnotation
Information about a template-id annotation token.
Definition: ParsedTemplate.h:150
clang::Scope::FnScope
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:47
clang::Token::isObjCAtKeyword
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:57
clang::DeclaratorContext::File
@ File
clang::DeclSpec::TST_enum
static const TST TST_enum
Definition: DeclSpec.h:283
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
clang::Sema::ActOnEndOfTranslationUnit
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:1081
clang::Preprocessor::setCodeCompletionHandler
void setCodeCompletionHandler(CodeCompletionHandler &Handler)
Set the code completion handler to the given object.
Definition: Preprocessor.h:1283
clang::Preprocessor::isIncrementalProcessingEnabled
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
Definition: Preprocessor.h:1641
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:96
clang::Preprocessor::Lex
void Lex(Token &Result)
Lex the next token for this preprocessor.
Definition: Preprocessor.cpp:888
clang::Parser::SkipUntil
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1205
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1576
clang::Decl::getAsFunction
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
clang::TemplateNameKind
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
clang::DeclSpec::getAttributes
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:796
llvm::SmallVector< Token, 4 >
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:592
clang::Preprocessor::getMaxTokens
unsigned getMaxTokens() const
Get the max number of tokens before issuing a -Wmax-tokens warning.
Definition: Preprocessor.h:1070
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::Sema::ModuleDeclKind::Interface
@ Interface
'export module X;'
clang::TNK_Undeclared_template
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:136
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:221
clang::ParsingDeclSpec::complete
void complete(Decl *D)
Definition: RAIIObjectsForParser.h:190
clang::Sema::SetDeclDefaulted
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
Definition: SemaDeclCXX.cpp:17125
IsCommonTypo
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
Definition: Parser.cpp:102
clang::Token::getIdentifierInfo
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:179
clang::tok::getPunctuatorSpelling
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!' or '', and returns NULL for literal and...
Definition: TokenKinds.cpp:31
clang::Sema::PCC_ObjCImplementation
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
Definition: Sema.h:12391
clang::Sema::getTypeName
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:285
clang::Token::setAnnotationEndLoc
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:144
clang::Token::isAtStartOfLine
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:268
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:60
clang::Sema::CodeCompleteInPreprocessorConditionalExclusion
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S)
Definition: SemaCodeComplete.cpp:9493
clang::DeclSpec::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:507
clang::DeclSpec::SCS_unspecified
@ SCS_unspecified
Definition: DeclSpec.h:234
clang::Sema::CodeCompletePreprocessorExpression
void CodeCompletePreprocessorExpression()
Definition: SemaCodeComplete.cpp:9525
clang::DeclSpec::getParsedSpecifiers
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:452
RAIIObjectsForParser.h
clang::MacroInfo
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
clang::Sema::ActOnPrivateModuleFragmentDecl
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc)
The parser has processed a private-module-fragment declaration that begins the definition of the priv...
Definition: SemaModule.cpp:246
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:188
clang::Sema::NameClassification::getTemplateName
TemplateName getTemplateName() const
Definition: Sema.h:2544
DeclSpec.h
clang::Preprocessor::EnterToken
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
Definition: Preprocessor.h:1558
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:64
clang::Token::setAnnotationRange
void setAnnotationRange(SourceRange R)
Definition: Token.h:163
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:59
clang::Sema::NameClassification::getKind
NameClassificationKind getKind() const
Definition: Sema.h:2527
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:186
clang::BalancedDelimiterTracker
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Definition: RAIIObjectsForParser.h:385
clang::CommentHandler
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Definition: Preprocessor.h:2490
clang::ParsingDeclarator::getMutableDeclSpec
ParsingDeclSpec & getMutableDeclSpec() const
Definition: RAIIObjectsForParser.h:212
clang::DeclSpec::getSpecifierName
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:542
clang::Preprocessor::isCodeCompletionReached
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
Definition: Preprocessor.h:1684
clang::Declarator::getIdentifierLoc
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2195
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:967
clang::DeclSpec::getTypeSpecTypeLoc
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:515
clang::DeclSpec::TSCS_unspecified
static const TSCS TSCS_unspecified
Definition: DeclSpec.h:247
clang::Scope::getParent
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:234
clang::TypeError
TypeResult TypeError()
Definition: Ownership.h:280
clang::Sema::ActOnTranslationUnitScope
void ActOnTranslationUnitScope(Scope *S)
Definition: Sema.cpp:112
clang::Sema::NC_Unknown
@ NC_Unknown
This name is not a type or template in this context, but might be something else.
Definition: Sema.h:2417
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
clang::Preprocessor::AnnotateCachedTokens
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
Definition: Preprocessor.h:1580
clang::AS_none
@ AS_none
Definition: Specifiers.h:112
clang::Sema::ActOnModuleDecl
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Definition: SemaModule.cpp:91
clang::Sema::ActOnFinishFunctionBody
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:14441
clang::ParenBraceBracketBalancer
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Definition: RAIIObjectsForParser.h:343
clang::Sema::CheckForFunctionRedefinition
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14100
clang::Sema::CodeCompleteIncludedFile
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Definition: SemaCodeComplete.cpp:9564
llvm::MutableArrayRef
Definition: LLVM.h:35
clang::Sema::NC_OverloadSet
@ NC_OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition: Sema.h:2440
clang::ASTContext::getExternalSource
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1158
clang::Preprocessor::SetPoisonReason
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
Definition: Preprocessor.cpp:731
clang::Sema::SaveNestedNameSpecifierAnnotation
void * SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS)
Given a C++ nested-name-specifier, produce an annotation value that the parser can use later to recon...
Definition: SemaCXXScopeSpec.cpp:1007
clang::Module
Describes a module or submodule.
Definition: Module.h:96
clang::Preprocessor::TypoCorrectToken
void TypoCorrectToken(const Token &Tok)
Update the current token to represent the provided identifier, in order to cache an action performed ...
Definition: Preprocessor.h:1630
DeclTemplate.h
clang::Sema::SkipBodyInfo::ShouldSkip
bool ShouldSkip
Definition: Sema.h:2375
clang::Sema::CodeCompletePreprocessorDirective
void CodeCompletePreprocessorDirective(bool InConditional)
Definition: SemaCodeComplete.cpp:9323
clang::Sema::ActOnModuleImport
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path)
The parser has processed a module import declaration.
Definition: SemaModule.cpp:307
clang::ImportDecl
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4447
clang::Sema::NameClassification
Definition: Sema.h:2453
clang::Sema::PCC_Class
@ PCC_Class
Code completion occurs within a class, struct, or union.
Definition: Sema.h:12385
clang::DeclSpec::getTypeSpecType
TST getTypeSpecType() const
Definition: DeclSpec.h:477
Id
int Id
Definition: ASTDiff.cpp:191
clang::Sema::CodeCompleteObjCMethodDecl
void CodeCompleteObjCMethodDecl(Scope *S, Optional< bool > IsInstanceMethod, ParsedType ReturnType)
Definition: SemaCodeComplete.cpp:9061
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::Parser::ParseUnqualifiedId
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
Definition: ParseExprCXX.cpp:2780
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
Definition: ParsedTemplate.h:183
clang::Parser::SkipUntilFlags
SkipUntilFlags
Control flags for SkipUntil functions.
Definition: Parser.h:1183
clang::DeclSpec::TST_interface
static const TST TST_interface
Definition: DeclSpec.h:286
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:222
clang::DeclaratorChunk::FunctionTypeInfo::isKNRPrototype
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
Definition: DeclSpec.h:1421
clang::Parser::StopAtCodeCompletion
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1187
clang::Preprocessor::addCommentHandler
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
Definition: Preprocessor.cpp:1384
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:92
clang::MultiTemplateParamsArg
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:276
clang::Sema::ActOnSkippedFunctionBody
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:14431
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:48
clang::Token::getAnnotationValue
void * getAnnotationValue() const
Definition: Token.h:226
clang::Sema::PCC_RecoveryInFunction
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
Definition: Sema.h:12415
clang::BalancedDelimiterTracker::expectAndConsume
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2545
clang::Sema::IER_DoesNotExist
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:5618
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1277
clang::DeclSpec::ClearStorageClassSpecs
void ClearStorageClassSpecs()
Definition: DeclSpec.h:455
clang::Scope::Init
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
Definition: Scope.cpp:87
clang::Parser::StopBeforeMatch
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1186
clang::Scope::CompoundStmtScope
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:130
clang::Scope::FunctionDeclarationScope
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:87
clang::Sema::NameClassification::getExpression
ExprResult getExpression() const
Definition: Sema.h:2529
clang::Sema::Initialize
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:248
clang::Parser::SkipMalformedDecl
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:1891
clang::DeclSpec::TST_class
static const TST TST_class
Definition: DeclSpec.h:287
clang::Preprocessor::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Definition: Preprocessor.h:1744
clang::Parser::ExitScope
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition: Parser.cpp:415
clang::Parser::getLangOpts
const LangOptions & getLangOpts() const
Definition: Parser.h:437
clang::Sema::ClassifyName
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:861
clang::DeclSpec::hasTagDefinition
bool hasTagDefinition() const
Definition: DeclSpec.cpp:443
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:97
clang::Sema::ModuleDeclKind::Implementation
@ Implementation
'module X;'
clang::Parser::ConsumeAnyToken
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:510
clang::Preprocessor::isBacktrackEnabled
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
Definition: Preprocessor.h:1444
clang::DeclContext::isTranslationUnit
bool isTranslationUnit() const
Definition: DeclBase.h:1935
clang::Sema::NC_DependentNonType
@ NC_DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:2435
clang::Parser::TryAnnotateCXXScopeToken
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2080
clang::ParsedAttr
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:209
clang::SourceManager::getFileID
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Definition: SourceManager.h:1103
clang::Token::setAnnotationValue
void setAnnotationValue(void *val)
Definition: Token.h:230
clang::ParsingDeclarator::complete
void complete(Decl *D)
Definition: RAIIObjectsForParser.h:221
clang::Sema::NameClassification::getNonTypeDecl
NamedDecl * getNonTypeDecl() const
Definition: Sema.h:2539
clang::Sema::CodeCompleteOrdinaryName
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
Definition: SemaCodeComplete.cpp:4176
clang::Sema::ActOnModuleInclude
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a include or similar preprocessing directive...
Definition: SemaModule.cpp:404
clang::TemplateIdAnnotation::Kind
TemplateNameKind Kind
The kind of template that Template refers to.
Definition: ParsedTemplate.h:175
ASTContext.h
clang::Declarator::setFunctionDefinitionKind
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2573
clang::Sema::SkipBodyInfo
Definition: Sema.h:2371
clang::DeclSpec::getStorageClassSpec
SCS getStorageClassSpec() const
Definition: DeclSpec.h:441
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:104
clang::Parser::MightBeCXXScopeToken
bool MightBeCXXScopeToken()
Definition: Parser.h:847
clang::DeclSpec::TST_union
static const TST TST_union
Definition: DeclSpec.h:284
clang::Sema::CheckMicrosoftIfExistsSymbol
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
Definition: SemaExprCXX.cpp:8634
clang::DeclSpec::SCS_register
@ SCS_register
Definition: DeclSpec.h:239
clang::Parser::getCurScope
Scope * getCurScope() const
Definition: Parser.h:444
clang::DeclaratorChunk::FunctionTypeInfo::Params
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1341
clang::Sema::CodeCompleteModuleImport
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path)
Definition: SemaCodeComplete.cpp:4128
clang::Parser::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:73
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::DeclSpec::getThreadStorageClassSpecLoc
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:451
getKind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:998
clang::Declarator::isFunctionDeclarator
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2299
clang::Sema::CodeCompleteNaturalLanguage
void CodeCompleteNaturalLanguage()
Definition: SemaCodeComplete.cpp:9701
clang::Parser::ParseStringLiteralExpression
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1255
clang::Parser::StopAtSemi
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1184
clang::ParsedAttributesWithRange
Definition: ParsedAttr.h:1071
clang::Parser::ObjCDeclContextSwitch
friend class ObjCDeclContextSwitch
Definition: Parser.h:65
clang::Declarator::SetRangeBegin
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
Definition: DeclSpec.h:1953
clang::ASTConsumer::HandleTopLevelDecl
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
clang::Sema::ConvertDeclToDeclGroup
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:56
clang::Sema::ActOnTypenameType
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
Definition: SemaTemplate.cpp:10365
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6794
clang::Sema::ActOnFinishKNRParamDeclarations
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:13974
clang::OpaquePtr
Wrapper for void* pointer.
Definition: Ownership.h:50
clang::Sema::NameClassification::getTemplateNameKind
TemplateNameKind getTemplateNameKind() const
Definition: Sema.h:2551
clang::DeclSpec::TST_int
static const TST TST_int
Definition: DeclSpec.h:267
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
Definition: ParsedTemplate.h:179
clang::DeclSpec::getStorageClassSpecLoc
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:450
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:964
IsHeaderFile
static bool IsHeaderFile(const std::string &Filename)
Definition: RewriteModernObjC.cpp:628
clang::Sema::canDelayFunctionBody
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:14389
clang::diff::Delete
@ Delete
Definition: ASTDiff.h:29
clang::AccessSpecifier
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:108
clang::Preprocessor::getSpelling
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
Definition: Preprocessor.h:1759
clang::Preprocessor::getTokenCount
unsigned getTokenCount() const
Get the number of tokens processed so far.
Definition: Preprocessor.h:1067
clang::Sema::IER_Dependent
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:5622
clang::ImplicitInt
@ ImplicitInt
Definition: LangStandard.h:57
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::TemplateIdAnnotation::TemplateNameLoc
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
Definition: ParsedTemplate.h:160
clang::Declarator::getFunctionTypeInfo
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2330
clang::Parser::ConsumeToken
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:482
clang::Preprocessor::hadModuleLoaderFatalFailure
bool hadModuleLoaderFatalFailure() const
Definition: Preprocessor.h:984
false
#define false
Definition: stdbool.h:17
clang::DeclSpec::isDeclRep
static bool isDeclRep(TST T)
Definition: DeclSpec.h:416
clang::TemplateIdAnnotation::mightBeType
bool mightBeType() const
Determine whether this might be a type template.
Definition: ParsedTemplate.h:224
clang::ParsingDeclSpec::abort
void abort()
Definition: RAIIObjectsForParser.h:194
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::TNK_Type_template
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
clang::Sema::NC_TypeTemplate
@ NC_TypeTemplate
The name was classified as a template whose specializations are types.
Definition: Sema.h:2442
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:192
clang::Preprocessor::isCodeCompletionEnabled
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
Definition: Preprocessor.h:1666
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:687
clang::Scope::ClassScope
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:65
llvm::ArrayRef
Definition: LLVM.h:34
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:89
clang::ParsingDeclarator::getDeclSpec
const ParsingDeclSpec & getDeclSpec() const
Definition: RAIIObjectsForParser.h:208
Scope.h
clang::Parser::~Parser
~Parser() override
Definition: Parser.cpp:454
clang::Parser::EnterScope
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:404
clang::Parser::DeclGroupPtrTy
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:453
clang::Sema::ActOnComment
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2261
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:355
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
Definition: Parser.cpp:1966
clang::Sema::NC_Type
@ NC_Type
The name was classified as a type.
Definition: Sema.h:2423
clang::FunctionDefinitionKind::Definition
@ Definition
clang::Parser::ParseTopLevelDecl
bool ParseTopLevelDecl()
Definition: Parser.h:472
ASTConsumer.h
clang::Parser::TryConsumeToken
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:490
clang::Sema::NameClassification::getType
ParsedType getType() const
Definition: Sema.h:2534
clang::PoisonSEHIdentifiersRAIIObject
Definition: RAIIObjectsForParser.h:359
clang::Sema::ActOnFileScopeAsmDecl
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:18481
clang::Parser::Initialize
void Initialize()
Initialize - Warm up the parser.
Definition: Parser.cpp:474
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::Sema::NC_UndeclaredTemplate
@ NC_UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition: Sema.h:2448
clang::Sema::ActOnStartOfTranslationUnit
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:1001
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::Token::isEditorPlaceholder
bool isEditorPlaceholder() const
Returns true if this token is an editor placeholder.
Definition: Token.h:310
clang::Sema::NC_Concept
@ NC_Concept
The name was classified as a concept name.
Definition: Sema.h:2450
clang::OpaquePtr< TemplateName >::make
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:60
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:105
clang::Sema::BuildDeclaratorGroup
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:13608
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Token::isAnnotation
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:120
clang::Preprocessor::removeCommentHandler
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
Definition: Preprocessor.cpp:1391
clang::ActionResult< Expr * >
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:6798
clang::ExtensionRAIIObject
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
Definition: RAIIObjectsForParser.h:252
clang::Decl::getBody
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1010
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:134
clang::Sema::ActOnModuleEnd
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaModule.cpp:462
clang::DeclSpec::TST_unspecified
static const TST TST_unspecified
Definition: DeclSpec.h:260
clang::TemplateIdAnnotation::TemplateKWLoc
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
Definition: ParsedTemplate.h:156
clang::DeclSpec::takeAttributesFrom
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:799
clang::Sema::NC_Keyword
@ NC_Keyword
The name has been typo-corrected to a keyword.
Definition: Sema.h:2421
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:113
clang::Preprocessor::clearCodeCompletionHandler
void clearCodeCompletionHandler()
Clear out the code completion handler.
Definition: Preprocessor.h:1293
clang::BalancedDelimiterTracker::skipToEnd
void skipToEnd()
Definition: Parser.cpp:2581
clang
Definition: CalledOnceCheck.h:17
clang::Preprocessor::getMaxTokensOverrideLoc
SourceLocation getMaxTokensOverrideLoc() const
Definition: Preprocessor.h:1077
clang::Sema::NC_UndeclaredNonType
@ NC_UndeclaredNonType
The name was classified as an ADL-only function name.
Definition: Sema.h:2431
clang::TemplateIdAnnotation::Name
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
Definition: ParsedTemplate.h:163
clang::Parser::TryAnnotateTypeOrScopeToken
bool TryAnnotateTypeOrScopeToken()
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1851
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:193
clang::Sema::IER_Exists
@ IER_Exists
The symbol exists.
Definition: Sema.h:5615
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1804
clang::Sema::CodeCompletePreprocessorMacroName
void CodeCompletePreprocessorMacroName(bool IsDefinition)
Definition: SemaCodeComplete.cpp:9498
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:112
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1030
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:122
clang::Sema::ActOnDefaultCtorInitializers
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
Definition: SemaDeclCXX.cpp:5695
clang::Preprocessor::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
Definition: Preprocessor.h:1868
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:93
clang::Sema::SetDeclDeleted
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
Definition: SemaDeclCXX.cpp:17073
ParseDiagnostic.h
clang::BalancedDelimiterTracker::consumeClose
bool consumeClose()
Definition: RAIIObjectsForParser.h:446
clang::TemplateIdAnnotation::isInvalid
bool isInvalid() const
Definition: ParsedTemplate.h:234
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:99
clang::DeclaratorContext::KNRTypeList
@ KNRTypeList
clang::Token::getLastLoc
SourceLocation getLastLoc() const
Definition: Token.h:149
clang::DeclSpec::TST_struct
static const TST TST_struct
Definition: DeclSpec.h:285
clang::Sema::CodeCompletePreprocessorMacroArgument
void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument)
Definition: SemaCodeComplete.cpp:9550
clang::Sema::SetLateTemplateParser
void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P)
Definition: Sema.h:909
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:49
clang::ParsingDeclarator
A class for parsing a declarator.
Definition: RAIIObjectsForParser.h:200
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
llvm::SmallVectorImpl
Definition: LLVM.h:39
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:59
FileManager.h
clang::Sema::HandleDeclarator
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:5787
clang::DeclSpec::isEmpty
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:635
true
#define true
Definition: stdbool.h:16
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:190
clang::IdentifierInfo::revertTokenIDToIdentifier
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
Definition: IdentifierTable.h:272
clang::Declarator::getAttributes
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2524
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:69
clang::Sema::canSkipFunctionBody
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:14413
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:73
clang::Sema::NC_VarTemplate
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:2444
clang::IdentifierLoc
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:187
clang::Parser::NextToken
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:793
clang::Sema::ModuleDeclKind
ModuleDeclKind
Definition: Sema.h:2909
clang::Sema::ActOnPopScope
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:1974
clang::Parser::Parser
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition: Parser.cpp:51
clang::Sema::NC_Error
@ NC_Error
Classification failed; an error has been produced.
Definition: Sema.h:2419
clang::Sema::isTemplateName
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Definition: SemaTemplate.cpp:170
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1856
clang::DeclaratorChunk::ParamInfo::Ident
IdentifierInfo * Ident
Definition: DeclSpec.h:1253
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3859
clang::TemplateIdAnnotation::Template
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Definition: ParsedTemplate.h:170
clang::Sema::ActOnStartOfFunctionDef
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14011
clang::Parser::TemplateParameterLists
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:456
clang::Preprocessor::RevertCachedTokens
void RevertCachedTokens(unsigned N)
When backtracking is enabled and tokens are cached, this allows to revert a specific number of tokens...
Definition: Preprocessor.h:1542
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::CXXScopeSpec::isNotEmpty
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:192
clang::DeclSpec::SetTypeSpecType
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:824
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1243
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:133
HasFlagsSet
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
Definition: Parser.cpp:266
clang::Sema::ActOnParamDeclarator
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:13724
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:229
clang::Sema::ActOnModuleBegin
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaModule.cpp:438
clang::DeclSpec::SCS_extern
@ SCS_extern
Definition: DeclSpec.h:236
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1523
ParsedTemplate.h
clang::Sema::ParsedFreeStandingDeclSpec
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4431
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:195
clang::Parser::ParseFirstTopLevelDecl
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result)
Parse the first top-level declaration in a translation unit.
Definition: Parser.cpp:584
clang::TypeSpecifierType
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:52
clang::Sema::getASTConsumer
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1577
clang::DeclSpec::PQ_StorageClassSpecifier
@ PQ_StorageClassSpecifier
Definition: DeclSpec.h:319
Parser.h
clang::Sema::ActOnEmptyDeclaration
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
Definition: SemaDeclCXX.cpp:16168
clang::DeclSpec::getThreadStorageClassSpec
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:442