clang  16.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, StringRef TokenUsed) {
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 , TokenUsed);
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 (true) {
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  [[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  Sema::ModuleImportState &ImportState) {
586  Actions.ActOnStartOfTranslationUnit();
587 
588  // For C++20 modules, a module decl must be the first in the TU. We also
589  // need to track module imports.
591  bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
592 
593  // C11 6.9p1 says translation units must have at least one top-level
594  // declaration. C++ doesn't have this restriction. We also don't want to
595  // complain if we have a precompiled header, although technically if the PCH
596  // is empty we should still emit the (pedantic) diagnostic.
597  // If the main file is a header, we're only pretending it's a TU; don't warn.
598  if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
600  Diag(diag::ext_empty_translation_unit);
601 
602  return NoTopLevelDecls;
603 }
604 
605 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
606 /// action tells us to. This returns true if the EOF was encountered.
607 ///
608 /// top-level-declaration:
609 /// declaration
610 /// [C++20] module-import-declaration
612  Sema::ModuleImportState &ImportState) {
613  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
614 
615  // Skip over the EOF token, flagging end of previous input for incremental
616  // processing
617  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
618  ConsumeToken();
619 
620  Result = nullptr;
621  switch (Tok.getKind()) {
622  case tok::annot_pragma_unused:
623  HandlePragmaUnused();
624  return false;
625 
626  case tok::kw_export:
627  switch (NextToken().getKind()) {
628  case tok::kw_module:
629  goto module_decl;
630 
631  // Note: no need to handle kw_import here. We only form kw_import under
632  // the Modules TS, and in that case 'export import' is parsed as an
633  // export-declaration containing an import-declaration.
634 
635  // Recognize context-sensitive C++20 'export module' and 'export import'
636  // declarations.
637  case tok::identifier: {
639  if ((II == Ident_module || II == Ident_import) &&
640  GetLookAheadToken(2).isNot(tok::coloncolon)) {
641  if (II == Ident_module)
642  goto module_decl;
643  else
644  goto import_decl;
645  }
646  break;
647  }
648 
649  default:
650  break;
651  }
652  break;
653 
654  case tok::kw_module:
655  module_decl:
656  Result = ParseModuleDecl(ImportState);
657  return false;
658 
659  case tok::kw_import:
660  import_decl: {
661  Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
662  Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
663  return false;
664  }
665 
666  case tok::annot_module_include: {
667  auto Loc = Tok.getLocation();
668  Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
669  // FIXME: We need a better way to disambiguate C++ clang modules and
670  // standard C++ modules.
671  if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
672  Actions.ActOnModuleInclude(Loc, Mod);
673  else {
674  DeclResult Import =
675  Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
676  Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
677  Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
678  }
679  ConsumeAnnotationToken();
680  return false;
681  }
682 
683  case tok::annot_module_begin:
684  Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
685  Tok.getAnnotationValue()));
686  ConsumeAnnotationToken();
688  return false;
689 
690  case tok::annot_module_end:
691  Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
692  Tok.getAnnotationValue()));
693  ConsumeAnnotationToken();
695  return false;
696 
697  case tok::eof:
698  // Check whether -fmax-tokens= was reached.
699  if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
700  PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
701  << PP.getTokenCount() << PP.getMaxTokens();
702  SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
703  if (OverrideLoc.isValid()) {
704  PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
705  }
706  }
707 
708  // Late template parsing can begin.
709  Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
711  Actions.ActOnEndOfTranslationUnit();
712  //else don't tell Sema that we ended parsing: more input might come.
713  return true;
714 
715  case tok::identifier:
716  // C++2a [basic.link]p3:
717  // A token sequence beginning with 'export[opt] module' or
718  // 'export[opt] import' and not immediately followed by '::'
719  // is never interpreted as the declaration of a top-level-declaration.
720  if ((Tok.getIdentifierInfo() == Ident_module ||
721  Tok.getIdentifierInfo() == Ident_import) &&
722  NextToken().isNot(tok::coloncolon)) {
723  if (Tok.getIdentifierInfo() == Ident_module)
724  goto module_decl;
725  else
726  goto import_decl;
727  }
728  break;
729 
730  default:
731  break;
732  }
733 
734  ParsedAttributes DeclAttrs(AttrFactory);
735  ParsedAttributes DeclSpecAttrs(AttrFactory);
736  // GNU attributes are applied to the declaration specification while the
737  // standard attributes are applied to the declaration. We parse the two
738  // attribute sets into different containters so we can apply them during
739  // the regular parsing process.
740  while (MaybeParseCXX11Attributes(DeclAttrs) ||
741  MaybeParseGNUAttributes(DeclSpecAttrs))
742  ;
743 
744  Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
745  // An empty Result might mean a line with ';' or some parsing error, ignore
746  // it.
747  if (Result) {
748  if (ImportState == Sema::ModuleImportState::FirstDecl)
749  // First decl was not modular.
751  else if (ImportState == Sema::ModuleImportState::ImportAllowed)
752  // Non-imports disallow further imports.
754  }
755  return false;
756 }
757 
758 /// ParseExternalDeclaration:
759 ///
760 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
761 /// declaration.
762 ///
763 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
764 /// function-definition
765 /// declaration
766 /// [GNU] asm-definition
767 /// [GNU] __extension__ external-declaration
768 /// [OBJC] objc-class-definition
769 /// [OBJC] objc-class-declaration
770 /// [OBJC] objc-alias-declaration
771 /// [OBJC] objc-protocol-definition
772 /// [OBJC] objc-method-definition
773 /// [OBJC] @end
774 /// [C++] linkage-specification
775 /// [GNU] asm-definition:
776 /// simple-asm-expr ';'
777 /// [C++11] empty-declaration
778 /// [C++11] attribute-declaration
779 ///
780 /// [C++11] empty-declaration:
781 /// ';'
782 ///
783 /// [C++0x/GNU] 'extern' 'template' declaration
784 ///
785 /// [Modules-TS] module-import-declaration
786 ///
788 Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
789  ParsedAttributes &DeclSpecAttrs,
790  ParsingDeclSpec *DS) {
791  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
792  ParenBraceBracketBalancer BalancerRAIIObj(*this);
793 
794  if (PP.isCodeCompletionReached()) {
795  cutOffParsing();
796  return nullptr;
797  }
798 
799  Decl *SingleDecl = nullptr;
800  switch (Tok.getKind()) {
801  case tok::annot_pragma_vis:
802  HandlePragmaVisibility();
803  return nullptr;
804  case tok::annot_pragma_pack:
805  HandlePragmaPack();
806  return nullptr;
807  case tok::annot_pragma_msstruct:
808  HandlePragmaMSStruct();
809  return nullptr;
810  case tok::annot_pragma_align:
811  HandlePragmaAlign();
812  return nullptr;
813  case tok::annot_pragma_weak:
814  HandlePragmaWeak();
815  return nullptr;
816  case tok::annot_pragma_weakalias:
817  HandlePragmaWeakAlias();
818  return nullptr;
819  case tok::annot_pragma_redefine_extname:
820  HandlePragmaRedefineExtname();
821  return nullptr;
822  case tok::annot_pragma_fp_contract:
823  HandlePragmaFPContract();
824  return nullptr;
825  case tok::annot_pragma_fenv_access:
826  case tok::annot_pragma_fenv_access_ms:
827  HandlePragmaFEnvAccess();
828  return nullptr;
829  case tok::annot_pragma_fenv_round:
830  HandlePragmaFEnvRound();
831  return nullptr;
832  case tok::annot_pragma_float_control:
833  HandlePragmaFloatControl();
834  return nullptr;
835  case tok::annot_pragma_fp:
836  HandlePragmaFP();
837  break;
838  case tok::annot_pragma_opencl_extension:
839  HandlePragmaOpenCLExtension();
840  return nullptr;
841  case tok::annot_attr_openmp:
842  case tok::annot_pragma_openmp: {
844  return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
845  }
846  case tok::annot_pragma_ms_pointers_to_members:
847  HandlePragmaMSPointersToMembers();
848  return nullptr;
849  case tok::annot_pragma_ms_vtordisp:
850  HandlePragmaMSVtorDisp();
851  return nullptr;
852  case tok::annot_pragma_ms_pragma:
853  HandlePragmaMSPragma();
854  return nullptr;
855  case tok::annot_pragma_dump:
856  HandlePragmaDump();
857  return nullptr;
858  case tok::annot_pragma_attribute:
859  HandlePragmaAttribute();
860  return nullptr;
861  case tok::semi:
862  // Either a C++11 empty-declaration or attribute-declaration.
863  SingleDecl =
864  Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
865  ConsumeExtraSemi(OutsideFunction);
866  break;
867  case tok::r_brace:
868  Diag(Tok, diag::err_extraneous_closing_brace);
869  ConsumeBrace();
870  return nullptr;
871  case tok::eof:
872  Diag(Tok, diag::err_expected_external_declaration);
873  return nullptr;
874  case tok::kw___extension__: {
875  // __extension__ silences extension warnings in the subexpression.
876  ExtensionRAIIObject O(Diags); // Use RAII to do this.
877  ConsumeToken();
878  return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
879  }
880  case tok::kw_asm: {
881  ProhibitAttributes(Attrs);
882 
883  SourceLocation StartLoc = Tok.getLocation();
884  SourceLocation EndLoc;
885 
886  ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
887 
888  // Check if GNU-style InlineAsm is disabled.
889  // Empty asm string is allowed because it will not introduce
890  // any assembly code.
891  if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
892  const auto *SL = cast<StringLiteral>(Result.get());
893  if (!SL->getString().trim().empty())
894  Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
895  }
896 
897  ExpectAndConsume(tok::semi, diag::err_expected_after,
898  "top-level asm block");
899 
900  if (Result.isInvalid())
901  return nullptr;
902  SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
903  break;
904  }
905  case tok::at:
906  return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
907  case tok::minus:
908  case tok::plus:
909  if (!getLangOpts().ObjC) {
910  Diag(Tok, diag::err_expected_external_declaration);
911  ConsumeToken();
912  return nullptr;
913  }
914  SingleDecl = ParseObjCMethodDefinition();
915  break;
916  case tok::code_completion:
917  cutOffParsing();
918  if (CurParsedObjCImpl) {
919  // Code-complete Objective-C methods even without leading '-'/'+' prefix.
921  /*IsInstanceMethod=*/None,
922  /*ReturnType=*/nullptr);
923  }
924  Actions.CodeCompleteOrdinaryName(
925  getCurScope(),
926  CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
927  return nullptr;
928  case tok::kw_import: {
930  if (getLangOpts().CPlusPlusModules) {
931  llvm_unreachable("not expecting a c++20 import here");
932  ProhibitAttributes(Attrs);
933  }
934  SingleDecl = ParseModuleImport(SourceLocation(), IS);
935  } break;
936  case tok::kw_export:
937  if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
938  ProhibitAttributes(Attrs);
939  SingleDecl = ParseExportDeclaration();
940  break;
941  }
942  // This must be 'export template'. Parse it so we can diagnose our lack
943  // of support.
944  [[fallthrough]];
945  case tok::kw_using:
946  case tok::kw_namespace:
947  case tok::kw_typedef:
948  case tok::kw_template:
949  case tok::kw_static_assert:
950  case tok::kw__Static_assert:
951  // A function definition cannot start with any of these keywords.
952  {
953  SourceLocation DeclEnd;
954  return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
955  DeclSpecAttrs);
956  }
957 
958  case tok::kw_cbuffer:
959  case tok::kw_tbuffer:
960  if (getLangOpts().HLSL) {
961  SourceLocation DeclEnd;
962  return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
963  DeclSpecAttrs);
964  }
965  goto dont_know;
966 
967  case tok::kw_static:
968  // Parse (then ignore) 'static' prior to a template instantiation. This is
969  // a GCC extension that we intentionally do not support.
970  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
971  Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
972  << 0;
973  SourceLocation DeclEnd;
974  return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
975  DeclSpecAttrs);
976  }
977  goto dont_know;
978 
979  case tok::kw_inline:
980  if (getLangOpts().CPlusPlus) {
981  tok::TokenKind NextKind = NextToken().getKind();
982 
983  // Inline namespaces. Allowed as an extension even in C++03.
984  if (NextKind == tok::kw_namespace) {
985  SourceLocation DeclEnd;
986  return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
987  DeclSpecAttrs);
988  }
989 
990  // Parse (then ignore) 'inline' prior to a template instantiation. This is
991  // a GCC extension that we intentionally do not support.
992  if (NextKind == tok::kw_template) {
993  Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
994  << 1;
995  SourceLocation DeclEnd;
996  return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
997  DeclSpecAttrs);
998  }
999  }
1000  goto dont_know;
1001 
1002  case tok::kw_extern:
1003  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1004  // Extern templates
1005  SourceLocation ExternLoc = ConsumeToken();
1006  SourceLocation TemplateLoc = ConsumeToken();
1007  Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
1008  diag::warn_cxx98_compat_extern_template :
1009  diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1010  SourceLocation DeclEnd;
1011  return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
1012  DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs));
1013  }
1014  goto dont_know;
1015 
1016  case tok::kw___if_exists:
1017  case tok::kw___if_not_exists:
1018  ParseMicrosoftIfExistsExternalDeclaration();
1019  return nullptr;
1020 
1021  case tok::kw_module:
1022  Diag(Tok, diag::err_unexpected_module_decl);
1023  SkipUntil(tok::semi);
1024  return nullptr;
1025 
1026  default:
1027  dont_know:
1028  if (Tok.isEditorPlaceholder()) {
1029  ConsumeToken();
1030  return nullptr;
1031  }
1032  // We can't tell whether this is a function-definition or declaration yet.
1033  return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1034  }
1035 
1036  // This routine returns a DeclGroup, if the thing we parsed only contains a
1037  // single decl, convert it now.
1038  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1039 }
1040 
1041 /// Determine whether the current token, if it occurs after a
1042 /// declarator, continues a declaration or declaration list.
1043 bool Parser::isDeclarationAfterDeclarator() {
1044  // Check for '= delete' or '= default'
1045  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1046  const Token &KW = NextToken();
1047  if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
1048  return false;
1049  }
1050 
1051  return Tok.is(tok::equal) || // int X()= -> not a function def
1052  Tok.is(tok::comma) || // int X(), -> not a function def
1053  Tok.is(tok::semi) || // int X(); -> not a function def
1054  Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
1055  Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
1056  (getLangOpts().CPlusPlus &&
1057  Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
1058 }
1059 
1060 /// Determine whether the current token, if it occurs after a
1061 /// declarator, indicates the start of a function definition.
1062 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1063  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1064  if (Tok.is(tok::l_brace)) // int X() {}
1065  return true;
1066 
1067  // Handle K&R C argument lists: int X(f) int f; {}
1068  if (!getLangOpts().CPlusPlus &&
1070  return isDeclarationSpecifier(ImplicitTypenameContext::No);
1071 
1072  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1073  const Token &KW = NextToken();
1074  return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1075  }
1076 
1077  return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1078  Tok.is(tok::kw_try); // X() try { ... }
1079 }
1080 
1081 /// Parse either a function-definition or a declaration. We can't tell which
1082 /// we have until we read up to the compound-statement in function-definition.
1083 /// TemplateParams, if non-NULL, provides the template parameters when we're
1084 /// parsing a C++ template-declaration.
1085 ///
1086 /// function-definition: [C99 6.9.1]
1087 /// decl-specs declarator declaration-list[opt] compound-statement
1088 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1089 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1090 ///
1091 /// declaration: [C99 6.7]
1092 /// declaration-specifiers init-declarator-list[opt] ';'
1093 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1094 /// [OMP] threadprivate-directive
1095 /// [OMP] allocate-directive [TODO]
1096 ///
1097 Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1098  ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1099  ParsingDeclSpec &DS, AccessSpecifier AS) {
1100  // Because we assume that the DeclSpec has not yet been initialised, we simply
1101  // overwrite the source range and attribute the provided leading declspec
1102  // attributes.
1103  assert(DS.getSourceRange().isInvalid() &&
1104  "expected uninitialised source range");
1105  DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1106  DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1107  DS.takeAttributesFrom(DeclSpecAttrs);
1108 
1109  MaybeParseMicrosoftAttributes(DS.getAttributes());
1110  // Parse the common declaration-specifiers piece.
1111  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1112  DeclSpecContext::DSC_top_level);
1113 
1114  // If we had a free-standing type definition with a missing semicolon, we
1115  // may get this far before the problem becomes obvious.
1116  if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1117  DS, AS, DeclSpecContext::DSC_top_level))
1118  return nullptr;
1119 
1120  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1121  // declaration-specifiers init-declarator-list[opt] ';'
1122  if (Tok.is(tok::semi)) {
1123  auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1124  assert(DeclSpec::isDeclRep(TKind));
1125  switch(TKind) {
1126  case DeclSpec::TST_class:
1127  return 5;
1128  case DeclSpec::TST_struct:
1129  return 6;
1130  case DeclSpec::TST_union:
1131  return 5;
1132  case DeclSpec::TST_enum:
1133  return 4;
1135  return 9;
1136  default:
1137  llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1138  }
1139 
1140  };
1141  // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1142  SourceLocation CorrectLocationForAttributes =
1145  LengthOfTSTToken(DS.getTypeSpecType()))
1146  : SourceLocation();
1147  ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1148  ConsumeToken();
1149  RecordDecl *AnonRecord = nullptr;
1150  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1151  getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1152  DS.complete(TheDecl);
1153  if (AnonRecord) {
1154  Decl* decls[] = {AnonRecord, TheDecl};
1155  return Actions.BuildDeclaratorGroup(decls);
1156  }
1157  return Actions.ConvertDeclToDeclGroup(TheDecl);
1158  }
1159 
1160  // ObjC2 allows prefix attributes on class interfaces and protocols.
1161  // FIXME: This still needs better diagnostics. We should only accept
1162  // attributes here, no types, etc.
1163  if (getLangOpts().ObjC && Tok.is(tok::at)) {
1164  SourceLocation AtLoc = ConsumeToken(); // the "@"
1165  if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1166  !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1167  !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1168  Diag(Tok, diag::err_objc_unexpected_attr);
1169  SkipUntil(tok::semi);
1170  return nullptr;
1171  }
1172 
1173  DS.abort();
1174  DS.takeAttributesFrom(Attrs);
1175 
1176  const char *PrevSpec = nullptr;
1177  unsigned DiagID;
1178  if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1179  Actions.getASTContext().getPrintingPolicy()))
1180  Diag(AtLoc, DiagID) << PrevSpec;
1181 
1182  if (Tok.isObjCAtKeyword(tok::objc_protocol))
1183  return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1184 
1185  if (Tok.isObjCAtKeyword(tok::objc_implementation))
1186  return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1187 
1188  return Actions.ConvertDeclToDeclGroup(
1189  ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1190  }
1191 
1192  // If the declspec consisted only of 'extern' and we have a string
1193  // literal following it, this must be a C++ linkage specifier like
1194  // 'extern "C"'.
1195  if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1198  ProhibitAttributes(Attrs);
1199  Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1200  return Actions.ConvertDeclToDeclGroup(TheDecl);
1201  }
1202 
1203  return ParseDeclGroup(DS, DeclaratorContext::File, Attrs);
1204 }
1205 
1206 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1207  ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1208  ParsingDeclSpec *DS, AccessSpecifier AS) {
1209  if (DS) {
1210  return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1211  } else {
1212  ParsingDeclSpec PDS(*this);
1213  // Must temporarily exit the objective-c container scope for
1214  // parsing c constructs and re-enter objc container scope
1215  // afterwards.
1216  ObjCDeclContextSwitch ObjCDC(*this);
1217 
1218  return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1219  }
1220 }
1221 
1222 /// ParseFunctionDefinition - We parsed and verified that the specified
1223 /// Declarator is well formed. If this is a K&R-style function, read the
1224 /// parameters declaration-list, then start the compound-statement.
1225 ///
1226 /// function-definition: [C99 6.9.1]
1227 /// decl-specs declarator declaration-list[opt] compound-statement
1228 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1229 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1230 /// [C++] function-definition: [C++ 8.4]
1231 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1232 /// function-body
1233 /// [C++] function-definition: [C++ 8.4]
1234 /// decl-specifier-seq[opt] declarator function-try-block
1235 ///
1236 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1237  const ParsedTemplateInfo &TemplateInfo,
1238  LateParsedAttrList *LateParsedAttrs) {
1239  // Poison SEH identifiers so they are flagged as illegal in function bodies.
1240  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1242  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1243 
1244  // If this is C89 and the declspecs were completely missing, fudge in an
1245  // implicit int. We do this here because this is the only place where
1246  // declaration-specifiers are completely optional in the grammar.
1247  if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1248  Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
1249  << D.getDeclSpec().getSourceRange();
1250  const char *PrevSpec;
1251  unsigned DiagID;
1254  D.getIdentifierLoc(),
1255  PrevSpec, DiagID,
1256  Policy);
1258  }
1259 
1260  // If this declaration was formed with a K&R-style identifier list for the
1261  // arguments, parse declarations for all of the args next.
1262  // int foo(a,b) int a; float b; {}
1263  if (FTI.isKNRPrototype())
1264  ParseKNRParamDeclarations(D);
1265 
1266  // We should have either an opening brace or, in a C++ constructor,
1267  // we may have a colon.
1268  if (Tok.isNot(tok::l_brace) &&
1269  (!getLangOpts().CPlusPlus ||
1270  (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1271  Tok.isNot(tok::equal)))) {
1272  Diag(Tok, diag::err_expected_fn_body);
1273 
1274  // Skip over garbage, until we get to '{'. Don't eat the '{'.
1275  SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1276 
1277  // If we didn't find the '{', bail out.
1278  if (Tok.isNot(tok::l_brace))
1279  return nullptr;
1280  }
1281 
1282  // Check to make sure that any normal attributes are allowed to be on
1283  // a definition. Late parsed attributes are checked at the end.
1284  if (Tok.isNot(tok::equal)) {
1285  for (const ParsedAttr &AL : D.getAttributes())
1286  if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1287  Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1288  }
1289 
1290  // In delayed template parsing mode, for function template we consume the
1291  // tokens and store them for late parsing at the end of the translation unit.
1292  if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1293  TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1294  Actions.canDelayFunctionBody(D)) {
1295  MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1296 
1297  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1299  Scope *ParentScope = getCurScope()->getParent();
1300 
1302  Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1304  D.complete(DP);
1305  D.getMutableDeclSpec().abort();
1306 
1307  if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1308  trySkippingFunctionBody()) {
1309  BodyScope.Exit();
1310  return Actions.ActOnSkippedFunctionBody(DP);
1311  }
1312 
1313  CachedTokens Toks;
1314  LexTemplateFunctionForLateParsing(Toks);
1315 
1316  if (DP) {
1317  FunctionDecl *FnD = DP->getAsFunction();
1318  Actions.CheckForFunctionRedefinition(FnD);
1319  Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1320  }
1321  return DP;
1322  }
1323  else if (CurParsedObjCImpl &&
1324  !TemplateInfo.TemplateParams &&
1325  (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1326  Tok.is(tok::colon)) &&
1327  Actions.CurContext->isTranslationUnit()) {
1328  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1330  Scope *ParentScope = getCurScope()->getParent();
1331 
1333  Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1335  D.complete(FuncDecl);
1336  D.getMutableDeclSpec().abort();
1337  if (FuncDecl) {
1338  // Consume the tokens and store them for later parsing.
1339  StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1340  CurParsedObjCImpl->HasCFunction = true;
1341  return FuncDecl;
1342  }
1343  // FIXME: Should we really fall through here?
1344  }
1345 
1346  // Enter a scope for the function body.
1347  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1349 
1350  // Parse function body eagerly if it is either '= delete;' or '= default;' as
1351  // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1353  SourceLocation KWLoc;
1354  if (TryConsumeToken(tok::equal)) {
1355  assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1356 
1357  if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1358  Diag(KWLoc, getLangOpts().CPlusPlus11
1359  ? diag::warn_cxx98_compat_defaulted_deleted_function
1360  : diag::ext_defaulted_deleted_function)
1361  << 1 /* deleted */;
1362  BodyKind = Sema::FnBodyKind::Delete;
1363  } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1364  Diag(KWLoc, getLangOpts().CPlusPlus11
1365  ? diag::warn_cxx98_compat_defaulted_deleted_function
1366  : diag::ext_defaulted_deleted_function)
1367  << 0 /* defaulted */;
1368  BodyKind = Sema::FnBodyKind::Default;
1369  } else {
1370  llvm_unreachable("function definition after = not 'delete' or 'default'");
1371  }
1372 
1373  if (Tok.is(tok::comma)) {
1374  Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1375  << (BodyKind == Sema::FnBodyKind::Delete);
1376  SkipUntil(tok::semi);
1377  } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1378  BodyKind == Sema::FnBodyKind::Delete
1379  ? "delete"
1380  : "default")) {
1381  SkipUntil(tok::semi);
1382  }
1383  }
1384 
1385  // Tell the actions module that we have entered a function definition with the
1386  // specified Declarator for the function.
1387  Sema::SkipBodyInfo SkipBody;
1388  Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1389  TemplateInfo.TemplateParams
1390  ? *TemplateInfo.TemplateParams
1392  &SkipBody, BodyKind);
1393 
1394  if (SkipBody.ShouldSkip) {
1395  // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1396  if (BodyKind == Sema::FnBodyKind::Other)
1397  SkipFunctionBody();
1398 
1399  return Res;
1400  }
1401 
1402  // Break out of the ParsingDeclarator context before we parse the body.
1403  D.complete(Res);
1404 
1405  // Break out of the ParsingDeclSpec context, too. This const_cast is
1406  // safe because we're always the sole owner.
1407  D.getMutableDeclSpec().abort();
1408 
1409  if (BodyKind != Sema::FnBodyKind::Other) {
1410  Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind);
1411  Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1412  Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1413  return Res;
1414  }
1415 
1416  // With abbreviated function templates - we need to explicitly add depth to
1417  // account for the implicit template parameter list induced by the template.
1418  if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
1419  if (Template->isAbbreviated() &&
1420  Template->getTemplateParameters()->getParam(0)->isImplicit())
1421  // First template parameter is implicit - meaning no explicit template
1422  // parameter list was specified.
1423  CurTemplateDepthTracker.addDepth(1);
1424 
1425  if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1426  trySkippingFunctionBody()) {
1427  BodyScope.Exit();
1428  Actions.ActOnSkippedFunctionBody(Res);
1429  return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1430  }
1431 
1432  if (Tok.is(tok::kw_try))
1433  return ParseFunctionTryBlock(Res, BodyScope);
1434 
1435  // If we have a colon, then we're probably parsing a C++
1436  // ctor-initializer.
1437  if (Tok.is(tok::colon)) {
1438  ParseConstructorInitializer(Res);
1439 
1440  // Recover from error.
1441  if (!Tok.is(tok::l_brace)) {
1442  BodyScope.Exit();
1443  Actions.ActOnFinishFunctionBody(Res, nullptr);
1444  return Res;
1445  }
1446  } else
1447  Actions.ActOnDefaultCtorInitializers(Res);
1448 
1449  // Late attributes are parsed in the same scope as the function body.
1450  if (LateParsedAttrs)
1451  ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1452 
1453  return ParseFunctionStatementBody(Res, BodyScope);
1454 }
1455 
1456 void Parser::SkipFunctionBody() {
1457  if (Tok.is(tok::equal)) {
1458  SkipUntil(tok::semi);
1459  return;
1460  }
1461 
1462  bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1463  if (IsFunctionTryBlock)
1464  ConsumeToken();
1465 
1466  CachedTokens Skipped;
1467  if (ConsumeAndStoreFunctionPrologue(Skipped))
1469  else {
1470  SkipUntil(tok::r_brace);
1471  while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1472  SkipUntil(tok::l_brace);
1473  SkipUntil(tok::r_brace);
1474  }
1475  }
1476 }
1477 
1478 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1479 /// types for a function with a K&R-style identifier list for arguments.
1480 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1481  // We know that the top-level of this declarator is a function.
1483 
1484  // Enter function-declaration scope, limiting any declarators to the
1485  // function prototype scope, including parameter declarators.
1486  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1488 
1489  // Read all the argument declarations.
1490  while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1491  SourceLocation DSStart = Tok.getLocation();
1492 
1493  // Parse the common declaration-specifiers piece.
1494  DeclSpec DS(AttrFactory);
1495  ParseDeclarationSpecifiers(DS);
1496 
1497  // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1498  // least one declarator'.
1499  // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1500  // the declarations though. It's trivial to ignore them, really hard to do
1501  // anything else with them.
1502  if (TryConsumeToken(tok::semi)) {
1503  Diag(DSStart, diag::err_declaration_does_not_declare_param);
1504  continue;
1505  }
1506 
1507  // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1508  // than register.
1512  diag::err_invalid_storage_class_in_func_decl);
1514  }
1517  diag::err_invalid_storage_class_in_func_decl);
1519  }
1520 
1521  // Parse the first declarator attached to this declspec.
1522  Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1524  ParseDeclarator(ParmDeclarator);
1525 
1526  // Handle the full declarator list.
1527  while (true) {
1528  // If attributes are present, parse them.
1529  MaybeParseGNUAttributes(ParmDeclarator);
1530 
1531  // Ask the actions module to compute the type for this declarator.
1532  Decl *Param =
1533  Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1534 
1535  if (Param &&
1536  // A missing identifier has already been diagnosed.
1537  ParmDeclarator.getIdentifier()) {
1538 
1539  // Scan the argument list looking for the correct param to apply this
1540  // type.
1541  for (unsigned i = 0; ; ++i) {
1542  // C99 6.9.1p6: those declarators shall declare only identifiers from
1543  // the identifier list.
1544  if (i == FTI.NumParams) {
1545  Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1546  << ParmDeclarator.getIdentifier();
1547  break;
1548  }
1549 
1550  if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1551  // Reject redefinitions of parameters.
1552  if (FTI.Params[i].Param) {
1553  Diag(ParmDeclarator.getIdentifierLoc(),
1554  diag::err_param_redefinition)
1555  << ParmDeclarator.getIdentifier();
1556  } else {
1557  FTI.Params[i].Param = Param;
1558  }
1559  break;
1560  }
1561  }
1562  }
1563 
1564  // If we don't have a comma, it is either the end of the list (a ';') or
1565  // an error, bail out.
1566  if (Tok.isNot(tok::comma))
1567  break;
1568 
1569  ParmDeclarator.clear();
1570 
1571  // Consume the comma.
1572  ParmDeclarator.setCommaLoc(ConsumeToken());
1573 
1574  // Parse the next declarator.
1575  ParseDeclarator(ParmDeclarator);
1576  }
1577 
1578  // Consume ';' and continue parsing.
1579  if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1580  continue;
1581 
1582  // Otherwise recover by skipping to next semi or mandatory function body.
1583  if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1584  break;
1585  TryConsumeToken(tok::semi);
1586  }
1587 
1588  // The actions module must verify that all arguments were declared.
1590 }
1591 
1592 
1593 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1594 /// allowed to be a wide string, and is not subject to character translation.
1595 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1596 /// asm label as opposed to an asm statement, because such a construct does not
1597 /// behave well.
1598 ///
1599 /// [GNU] asm-string-literal:
1600 /// string-literal
1601 ///
1602 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1603  if (!isTokenStringLiteral()) {
1604  Diag(Tok, diag::err_expected_string_literal)
1605  << /*Source='in...'*/0 << "'asm'";
1606  return ExprError();
1607  }
1608 
1610  if (!AsmString.isInvalid()) {
1611  const auto *SL = cast<StringLiteral>(AsmString.get());
1612  if (!SL->isOrdinary()) {
1613  Diag(Tok, diag::err_asm_operand_wide_string_literal)
1614  << SL->isWide()
1615  << SL->getSourceRange();
1616  return ExprError();
1617  }
1618  if (ForAsmLabel && SL->getString().empty()) {
1619  Diag(Tok, diag::err_asm_operand_wide_string_literal)
1620  << 2 /* an empty */ << SL->getSourceRange();
1621  return ExprError();
1622  }
1623  }
1624  return AsmString;
1625 }
1626 
1627 /// ParseSimpleAsm
1628 ///
1629 /// [GNU] simple-asm-expr:
1630 /// 'asm' '(' asm-string-literal ')'
1631 ///
1632 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1633  assert(Tok.is(tok::kw_asm) && "Not an asm!");
1634  SourceLocation Loc = ConsumeToken();
1635 
1636  if (isGNUAsmQualifier(Tok)) {
1637  // Remove from the end of 'asm' to the end of the asm qualifier.
1638  SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1639  PP.getLocForEndOfToken(Tok.getLocation()));
1640  Diag(Tok, diag::err_global_asm_qualifier_ignored)
1641  << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1642  << FixItHint::CreateRemoval(RemovalRange);
1643  ConsumeToken();
1644  }
1645 
1646  BalancedDelimiterTracker T(*this, tok::l_paren);
1647  if (T.consumeOpen()) {
1648  Diag(Tok, diag::err_expected_lparen_after) << "asm";
1649  return ExprError();
1650  }
1651 
1652  ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1653 
1654  if (!Result.isInvalid()) {
1655  // Close the paren and get the location of the end bracket
1656  T.consumeClose();
1657  if (EndLoc)
1658  *EndLoc = T.getCloseLocation();
1659  } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1660  if (EndLoc)
1661  *EndLoc = Tok.getLocation();
1662  ConsumeParen();
1663  }
1664 
1665  return Result;
1666 }
1667 
1668 /// Get the TemplateIdAnnotation from the token and put it in the
1669 /// cleanup pool so that it gets destroyed when parsing the current top level
1670 /// declaration is finished.
1671 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1672  assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1674  Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1675  return Id;
1676 }
1677 
1678 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1679  // Push the current token back into the token stream (or revert it if it is
1680  // cached) and use an annotation scope token for current token.
1681  if (PP.isBacktrackEnabled())
1682  PP.RevertCachedTokens(1);
1683  else
1684  PP.EnterToken(Tok, /*IsReinject=*/true);
1685  Tok.setKind(tok::annot_cxxscope);
1687  Tok.setAnnotationRange(SS.getRange());
1688 
1689  // In case the tokens were cached, have Preprocessor replace them
1690  // with the annotation token. We don't need to do this if we've
1691  // just reverted back to a prior state.
1692  if (IsNewAnnotation)
1693  PP.AnnotateCachedTokens(Tok);
1694 }
1695 
1696 /// Attempt to classify the name at the current token position. This may
1697 /// form a type, scope or primary expression annotation, or replace the token
1698 /// with a typo-corrected keyword. This is only appropriate when the current
1699 /// name must refer to an entity which has already been declared.
1700 ///
1701 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1702 /// no typo correction will be performed.
1703 /// \param AllowImplicitTypename Whether we are in a context where a dependent
1704 /// nested-name-specifier without typename is treated as a type (e.g.
1705 /// T::type).
1706 Parser::AnnotatedNameKind
1707 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1708  ImplicitTypenameContext AllowImplicitTypename) {
1709  assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1710 
1711  const bool EnteringContext = false;
1712  const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1713 
1714  CXXScopeSpec SS;
1715  if (getLangOpts().CPlusPlus &&
1716  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1717  /*ObjectHasErrors=*/false,
1718  EnteringContext))
1719  return ANK_Error;
1720 
1721  if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1722  if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1723  AllowImplicitTypename))
1724  return ANK_Error;
1725  return ANK_Unresolved;
1726  }
1727 
1728  IdentifierInfo *Name = Tok.getIdentifierInfo();
1729  SourceLocation NameLoc = Tok.getLocation();
1730 
1731  // FIXME: Move the tentative declaration logic into ClassifyName so we can
1732  // typo-correct to tentatively-declared identifiers.
1733  if (isTentativelyDeclared(Name) && SS.isEmpty()) {
1734  // Identifier has been tentatively declared, and thus cannot be resolved as
1735  // an expression. Fall back to annotating it as a type.
1736  if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1737  AllowImplicitTypename))
1738  return ANK_Error;
1739  return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1740  }
1741 
1742  Token Next = NextToken();
1743 
1744  // Look up and classify the identifier. We don't perform any typo-correction
1745  // after a scope specifier, because in general we can't recover from typos
1746  // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1747  // jump back into scope specifier parsing).
1748  Sema::NameClassification Classification = Actions.ClassifyName(
1749  getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1750 
1751  // If name lookup found nothing and we guessed that this was a template name,
1752  // double-check before committing to that interpretation. C++20 requires that
1753  // we interpret this as a template-id if it can be, but if it can't be, then
1754  // this is an error recovery case.
1755  if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1756  isTemplateArgumentList(1) == TPResult::False) {
1757  // It's not a template-id; re-classify without the '<' as a hint.
1758  Token FakeNext = Next;
1759  FakeNext.setKind(tok::unknown);
1760  Classification =
1761  Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1762  SS.isEmpty() ? CCC : nullptr);
1763  }
1764 
1765  switch (Classification.getKind()) {
1766  case Sema::NC_Error:
1767  return ANK_Error;
1768 
1769  case Sema::NC_Keyword:
1770  // The identifier was typo-corrected to a keyword.
1771  Tok.setIdentifierInfo(Name);
1772  Tok.setKind(Name->getTokenID());
1773  PP.TypoCorrectToken(Tok);
1774  if (SS.isNotEmpty())
1775  AnnotateScopeToken(SS, !WasScopeAnnotation);
1776  // We've "annotated" this as a keyword.
1777  return ANK_Success;
1778 
1779  case Sema::NC_Unknown:
1780  // It's not something we know about. Leave it unannotated.
1781  break;
1782 
1783  case Sema::NC_Type: {
1784  if (TryAltiVecVectorToken())
1785  // vector has been found as a type id when altivec is enabled but
1786  // this is followed by a declaration specifier so this is really the
1787  // altivec vector token. Leave it unannotated.
1788  break;
1789  SourceLocation BeginLoc = NameLoc;
1790  if (SS.isNotEmpty())
1791  BeginLoc = SS.getBeginLoc();
1792 
1793  /// An Objective-C object type followed by '<' is a specialization of
1794  /// a parameterized class type or a protocol-qualified type.
1795  ParsedType Ty = Classification.getType();
1796  if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1797  (Ty.get()->isObjCObjectType() ||
1798  Ty.get()->isObjCObjectPointerType())) {
1799  // Consume the name.
1801  SourceLocation NewEndLoc;
1802  TypeResult NewType
1803  = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1804  /*consumeLastToken=*/false,
1805  NewEndLoc);
1806  if (NewType.isUsable())
1807  Ty = NewType.get();
1808  else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1809  return ANK_Error;
1810  }
1811 
1812  Tok.setKind(tok::annot_typename);
1813  setTypeAnnotation(Tok, Ty);
1814  Tok.setAnnotationEndLoc(Tok.getLocation());
1815  Tok.setLocation(BeginLoc);
1816  PP.AnnotateCachedTokens(Tok);
1817  return ANK_Success;
1818  }
1819 
1820  case Sema::NC_OverloadSet:
1821  Tok.setKind(tok::annot_overload_set);
1822  setExprAnnotation(Tok, Classification.getExpression());
1823  Tok.setAnnotationEndLoc(NameLoc);
1824  if (SS.isNotEmpty())
1825  Tok.setLocation(SS.getBeginLoc());
1826  PP.AnnotateCachedTokens(Tok);
1827  return ANK_Success;
1828 
1829  case Sema::NC_NonType:
1830  if (TryAltiVecVectorToken())
1831  // vector has been found as a non-type id when altivec is enabled but
1832  // this is followed by a declaration specifier so this is really the
1833  // altivec vector token. Leave it unannotated.
1834  break;
1835  Tok.setKind(tok::annot_non_type);
1836  setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1837  Tok.setLocation(NameLoc);
1838  Tok.setAnnotationEndLoc(NameLoc);
1839  PP.AnnotateCachedTokens(Tok);
1840  if (SS.isNotEmpty())
1841  AnnotateScopeToken(SS, !WasScopeAnnotation);
1842  return ANK_Success;
1843 
1846  Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1847  ? tok::annot_non_type_undeclared
1848  : tok::annot_non_type_dependent);
1849  setIdentifierAnnotation(Tok, Name);
1850  Tok.setLocation(NameLoc);
1851  Tok.setAnnotationEndLoc(NameLoc);
1852  PP.AnnotateCachedTokens(Tok);
1853  if (SS.isNotEmpty())
1854  AnnotateScopeToken(SS, !WasScopeAnnotation);
1855  return ANK_Success;
1856 
1857  case Sema::NC_TypeTemplate:
1858  if (Next.isNot(tok::less)) {
1859  // This may be a type template being used as a template template argument.
1860  if (SS.isNotEmpty())
1861  AnnotateScopeToken(SS, !WasScopeAnnotation);
1862  return ANK_TemplateName;
1863  }
1864  [[fallthrough]];
1865  case Sema::NC_VarTemplate:
1868  // We have a type, variable or function template followed by '<'.
1869  ConsumeToken();
1870  UnqualifiedId Id;
1871  Id.setIdentifier(Name, NameLoc);
1872  if (AnnotateTemplateIdToken(
1873  TemplateTy::make(Classification.getTemplateName()),
1874  Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1875  return ANK_Error;
1876  return ANK_Success;
1877  }
1878  case Sema::NC_Concept: {
1879  UnqualifiedId Id;
1880  Id.setIdentifier(Name, NameLoc);
1881  if (Next.is(tok::less))
1882  // We have a concept name followed by '<'. Consume the identifier token so
1883  // we reach the '<' and annotate it.
1884  ConsumeToken();
1885  if (AnnotateTemplateIdToken(
1886  TemplateTy::make(Classification.getTemplateName()),
1887  Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1888  /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true))
1889  return ANK_Error;
1890  return ANK_Success;
1891  }
1892  }
1893 
1894  // Unable to classify the name, but maybe we can annotate a scope specifier.
1895  if (SS.isNotEmpty())
1896  AnnotateScopeToken(SS, !WasScopeAnnotation);
1897  return ANK_Unresolved;
1898 }
1899 
1900 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1901  assert(Tok.isNot(tok::identifier));
1902  Diag(Tok, diag::ext_keyword_as_ident)
1903  << PP.getSpelling(Tok)
1904  << DisableKeyword;
1905  if (DisableKeyword)
1907  Tok.setKind(tok::identifier);
1908  return true;
1909 }
1910 
1911 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1912 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1913 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1914 /// with a single annotation token representing the typename or C++ scope
1915 /// respectively.
1916 /// This simplifies handling of C++ scope specifiers and allows efficient
1917 /// backtracking without the need to re-parse and resolve nested-names and
1918 /// typenames.
1919 /// It will mainly be called when we expect to treat identifiers as typenames
1920 /// (if they are typenames). For example, in C we do not expect identifiers
1921 /// inside expressions to be treated as typenames so it will not be called
1922 /// for expressions in C.
1923 /// The benefit for C/ObjC is that a typename will be annotated and
1924 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1925 /// will not be called twice, once to check whether we have a declaration
1926 /// specifier, and another one to get the actual type inside
1927 /// ParseDeclarationSpecifiers).
1928 ///
1929 /// This returns true if an error occurred.
1930 ///
1931 /// Note that this routine emits an error if you call it with ::new or ::delete
1932 /// as the current tokens, so only call it in contexts where these are invalid.
1934  ImplicitTypenameContext AllowImplicitTypename) {
1935  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1936  Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1937  Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1938  Tok.is(tok::kw___super)) &&
1939  "Cannot be a type or scope token!");
1940 
1941  if (Tok.is(tok::kw_typename)) {
1942  // MSVC lets you do stuff like:
1943  // typename typedef T_::D D;
1944  //
1945  // We will consume the typedef token here and put it back after we have
1946  // parsed the first identifier, transforming it into something more like:
1947  // typename T_::D typedef D;
1948  if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1949  Token TypedefToken;
1950  PP.Lex(TypedefToken);
1951  bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
1952  PP.EnterToken(Tok, /*IsReinject=*/true);
1953  Tok = TypedefToken;
1954  if (!Result)
1955  Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1956  return Result;
1957  }
1958 
1959  // Parse a C++ typename-specifier, e.g., "typename T::type".
1960  //
1961  // typename-specifier:
1962  // 'typename' '::' [opt] nested-name-specifier identifier
1963  // 'typename' '::' [opt] nested-name-specifier template [opt]
1964  // simple-template-id
1965  SourceLocation TypenameLoc = ConsumeToken();
1966  CXXScopeSpec SS;
1967  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1968  /*ObjectHasErrors=*/false,
1969  /*EnteringContext=*/false, nullptr,
1970  /*IsTypename*/ true))
1971  return true;
1972  if (SS.isEmpty()) {
1973  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1974  Tok.is(tok::annot_decltype)) {
1975  // Attempt to recover by skipping the invalid 'typename'
1976  if (Tok.is(tok::annot_decltype) ||
1977  (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
1978  Tok.isAnnotation())) {
1979  unsigned DiagID = diag::err_expected_qualified_after_typename;
1980  // MS compatibility: MSVC permits using known types with typename.
1981  // e.g. "typedef typename T* pointer_type"
1982  if (getLangOpts().MicrosoftExt)
1983  DiagID = diag::warn_expected_qualified_after_typename;
1984  Diag(Tok.getLocation(), DiagID);
1985  return false;
1986  }
1987  }
1988  if (Tok.isEditorPlaceholder())
1989  return true;
1990 
1991  Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1992  return true;
1993  }
1994 
1995  TypeResult Ty;
1996  if (Tok.is(tok::identifier)) {
1997  // FIXME: check whether the next token is '<', first!
1998  Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1999  *Tok.getIdentifierInfo(),
2000  Tok.getLocation());
2001  } else if (Tok.is(tok::annot_template_id)) {
2002  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2003  if (!TemplateId->mightBeType()) {
2004  Diag(Tok, diag::err_typename_refers_to_non_type_template)
2005  << Tok.getAnnotationRange();
2006  return true;
2007  }
2008 
2009  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2010  TemplateId->NumArgs);
2011 
2012  Ty = TemplateId->isInvalid()
2013  ? TypeError()
2014  : Actions.ActOnTypenameType(
2015  getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
2016  TemplateId->Template, TemplateId->Name,
2017  TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
2018  TemplateArgsPtr, TemplateId->RAngleLoc);
2019  } else {
2020  Diag(Tok, diag::err_expected_type_name_after_typename)
2021  << SS.getRange();
2022  return true;
2023  }
2024 
2025  SourceLocation EndLoc = Tok.getLastLoc();
2026  Tok.setKind(tok::annot_typename);
2027  setTypeAnnotation(Tok, Ty);
2028  Tok.setAnnotationEndLoc(EndLoc);
2029  Tok.setLocation(TypenameLoc);
2030  PP.AnnotateCachedTokens(Tok);
2031  return false;
2032  }
2033 
2034  // Remembers whether the token was originally a scope annotation.
2035  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2036 
2037  CXXScopeSpec SS;
2038  if (getLangOpts().CPlusPlus)
2039  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2040  /*ObjectHasErrors=*/false,
2041  /*EnteringContext*/ false))
2042  return true;
2043 
2044  return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2045  AllowImplicitTypename);
2046 }
2047 
2048 /// Try to annotate a type or scope token, having already parsed an
2049 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
2050 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
2052  CXXScopeSpec &SS, bool IsNewScope,
2053  ImplicitTypenameContext AllowImplicitTypename) {
2054  if (Tok.is(tok::identifier)) {
2055  // Determine whether the identifier is a type name.
2056  if (ParsedType Ty = Actions.getTypeName(
2057  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
2058  false, NextToken().is(tok::period), nullptr,
2059  /*IsCtorOrDtorName=*/false,
2060  /*NonTrivialTypeSourceInfo=*/true,
2061  /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2062  SourceLocation BeginLoc = Tok.getLocation();
2063  if (SS.isNotEmpty()) // it was a C++ qualified type name.
2064  BeginLoc = SS.getBeginLoc();
2065 
2066  /// An Objective-C object type followed by '<' is a specialization of
2067  /// a parameterized class type or a protocol-qualified type.
2068  if (getLangOpts().ObjC && NextToken().is(tok::less) &&
2069  (Ty.get()->isObjCObjectType() ||
2070  Ty.get()->isObjCObjectPointerType())) {
2071  // Consume the name.
2073  SourceLocation NewEndLoc;
2074  TypeResult NewType
2075  = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
2076  /*consumeLastToken=*/false,
2077  NewEndLoc);
2078  if (NewType.isUsable())
2079  Ty = NewType.get();
2080  else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
2081  return false;
2082  }
2083 
2084  // This is a typename. Replace the current token in-place with an
2085  // annotation type token.
2086  Tok.setKind(tok::annot_typename);
2087  setTypeAnnotation(Tok, Ty);
2088  Tok.setAnnotationEndLoc(Tok.getLocation());
2089  Tok.setLocation(BeginLoc);
2090 
2091  // In case the tokens were cached, have Preprocessor replace
2092  // them with the annotation token.
2093  PP.AnnotateCachedTokens(Tok);
2094  return false;
2095  }
2096 
2097  if (!getLangOpts().CPlusPlus) {
2098  // If we're in C, the only place we can have :: tokens is C2x
2099  // attribute which is parsed elsewhere. If the identifier is not a type,
2100  // then it can't be scope either, just early exit.
2101  return false;
2102  }
2103 
2104  // If this is a template-id, annotate with a template-id or type token.
2105  // FIXME: This appears to be dead code. We already have formed template-id
2106  // tokens when parsing the scope specifier; this can never form a new one.
2107  if (NextToken().is(tok::less)) {
2108  TemplateTy Template;
2110  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2111  bool MemberOfUnknownSpecialization;
2112  if (TemplateNameKind TNK = Actions.isTemplateName(
2113  getCurScope(), SS,
2114  /*hasTemplateKeyword=*/false, TemplateName,
2115  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2116  MemberOfUnknownSpecialization)) {
2117  // Only annotate an undeclared template name as a template-id if the
2118  // following tokens have the form of a template argument list.
2119  if (TNK != TNK_Undeclared_template ||
2120  isTemplateArgumentList(1) != TPResult::False) {
2121  // Consume the identifier.
2122  ConsumeToken();
2123  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2124  TemplateName)) {
2125  // If an unrecoverable error occurred, we need to return true here,
2126  // because the token stream is in a damaged state. We may not
2127  // return a valid identifier.
2128  return true;
2129  }
2130  }
2131  }
2132  }
2133 
2134  // The current token, which is either an identifier or a
2135  // template-id, is not part of the annotation. Fall through to
2136  // push that token back into the stream and complete the C++ scope
2137  // specifier annotation.
2138  }
2139 
2140  if (Tok.is(tok::annot_template_id)) {
2141  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2142  if (TemplateId->Kind == TNK_Type_template) {
2143  // A template-id that refers to a type was parsed into a
2144  // template-id annotation in a context where we weren't allowed
2145  // to produce a type annotation token. Update the template-id
2146  // annotation token to a type annotation token now.
2147  AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2148  return false;
2149  }
2150  }
2151 
2152  if (SS.isEmpty())
2153  return false;
2154 
2155  // A C++ scope specifier that isn't followed by a typename.
2156  AnnotateScopeToken(SS, IsNewScope);
2157  return false;
2158 }
2159 
2160 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2161 /// annotates C++ scope specifiers and template-ids. This returns
2162 /// true if there was an error that could not be recovered from.
2163 ///
2164 /// Note that this routine emits an error if you call it with ::new or ::delete
2165 /// as the current tokens, so only call it in contexts where these are invalid.
2166 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2167  assert(getLangOpts().CPlusPlus &&
2168  "Call sites of this function should be guarded by checking for C++");
2169  assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2170 
2171  CXXScopeSpec SS;
2172  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2173  /*ObjectHasErrors=*/false,
2174  EnteringContext))
2175  return true;
2176  if (SS.isEmpty())
2177  return false;
2178 
2179  AnnotateScopeToken(SS, true);
2180  return false;
2181 }
2182 
2183 bool Parser::isTokenEqualOrEqualTypo() {
2184  tok::TokenKind Kind = Tok.getKind();
2185  switch (Kind) {
2186  default:
2187  return false;
2188  case tok::ampequal: // &=
2189  case tok::starequal: // *=
2190  case tok::plusequal: // +=
2191  case tok::minusequal: // -=
2192  case tok::exclaimequal: // !=
2193  case tok::slashequal: // /=
2194  case tok::percentequal: // %=
2195  case tok::lessequal: // <=
2196  case tok::lesslessequal: // <<=
2197  case tok::greaterequal: // >=
2198  case tok::greatergreaterequal: // >>=
2199  case tok::caretequal: // ^=
2200  case tok::pipeequal: // |=
2201  case tok::equalequal: // ==
2202  Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2203  << Kind
2205  [[fallthrough]];
2206  case tok::equal:
2207  return true;
2208  }
2209 }
2210 
2211 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2212  assert(Tok.is(tok::code_completion));
2213  PrevTokLocation = Tok.getLocation();
2214 
2215  for (Scope *S = getCurScope(); S; S = S->getParent()) {
2216  if (S->isFunctionScope()) {
2217  cutOffParsing();
2220  return PrevTokLocation;
2221  }
2222 
2223  if (S->isClassScope()) {
2224  cutOffParsing();
2226  return PrevTokLocation;
2227  }
2228  }
2229 
2230  cutOffParsing();
2232  return PrevTokLocation;
2233 }
2234 
2235 // Code-completion pass-through functions
2236 
2237 void Parser::CodeCompleteDirective(bool InConditional) {
2238  Actions.CodeCompletePreprocessorDirective(InConditional);
2239 }
2240 
2241 void Parser::CodeCompleteInConditionalExclusion() {
2243 }
2244 
2245 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2246  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2247 }
2248 
2249 void Parser::CodeCompletePreprocessorExpression() {
2251 }
2252 
2253 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2255  unsigned ArgumentIndex) {
2257  ArgumentIndex);
2258 }
2259 
2260 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2261  Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2262 }
2263 
2264 void Parser::CodeCompleteNaturalLanguage() {
2265  Actions.CodeCompleteNaturalLanguage();
2266 }
2267 
2268 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2269  assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2270  "Expected '__if_exists' or '__if_not_exists'");
2271  Result.IsIfExists = Tok.is(tok::kw___if_exists);
2272  Result.KeywordLoc = ConsumeToken();
2273 
2274  BalancedDelimiterTracker T(*this, tok::l_paren);
2275  if (T.consumeOpen()) {
2276  Diag(Tok, diag::err_expected_lparen_after)
2277  << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2278  return true;
2279  }
2280 
2281  // Parse nested-name-specifier.
2282  if (getLangOpts().CPlusPlus)
2283  ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2284  /*ObjectHasErrors=*/false,
2285  /*EnteringContext=*/false);
2286 
2287  // Check nested-name specifier.
2288  if (Result.SS.isInvalid()) {
2289  T.skipToEnd();
2290  return true;
2291  }
2292 
2293  // Parse the unqualified-id.
2294  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2295  if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2296  /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2297  /*AllowDestructorName*/ true,
2298  /*AllowConstructorName*/ true,
2299  /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2300  Result.Name)) {
2301  T.skipToEnd();
2302  return true;
2303  }
2304 
2305  if (T.consumeClose())
2306  return true;
2307 
2308  // Check if the symbol exists.
2309  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2310  Result.IsIfExists, Result.SS,
2311  Result.Name)) {
2312  case Sema::IER_Exists:
2313  Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2314  break;
2315 
2317  Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2318  break;
2319 
2320  case Sema::IER_Dependent:
2321  Result.Behavior = IEB_Dependent;
2322  break;
2323 
2324  case Sema::IER_Error:
2325  return true;
2326  }
2327 
2328  return false;
2329 }
2330 
2331 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2332  IfExistsCondition Result;
2333  if (ParseMicrosoftIfExistsCondition(Result))
2334  return;
2335 
2336  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2337  if (Braces.consumeOpen()) {
2338  Diag(Tok, diag::err_expected) << tok::l_brace;
2339  return;
2340  }
2341 
2342  switch (Result.Behavior) {
2343  case IEB_Parse:
2344  // Parse declarations below.
2345  break;
2346 
2347  case IEB_Dependent:
2348  llvm_unreachable("Cannot have a dependent external declaration");
2349 
2350  case IEB_Skip:
2351  Braces.skipToEnd();
2352  return;
2353  }
2354 
2355  // Parse the declarations.
2356  // FIXME: Support module import within __if_exists?
2357  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2358  ParsedAttributes Attrs(AttrFactory);
2359  MaybeParseCXX11Attributes(Attrs);
2360  ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2361  DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
2362  if (Result && !getCurScope()->getParent())
2363  Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2364  }
2365  Braces.consumeClose();
2366 }
2367 
2368 /// Parse a declaration beginning with the 'module' keyword or C++20
2369 /// context-sensitive keyword (optionally preceded by 'export').
2370 ///
2371 /// module-declaration: [Modules TS + P0629R0]
2372 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2373 ///
2374 /// global-module-fragment: [C++2a]
2375 /// 'module' ';' top-level-declaration-seq[opt]
2376 /// module-declaration: [C++2a]
2377 /// 'export'[opt] 'module' module-name module-partition[opt]
2378 /// attribute-specifier-seq[opt] ';'
2379 /// private-module-fragment: [C++2a]
2380 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2382 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2383  SourceLocation StartLoc = Tok.getLocation();
2384 
2385  Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2388 
2389  assert(
2390  (Tok.is(tok::kw_module) ||
2391  (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2392  "not a module declaration");
2393  SourceLocation ModuleLoc = ConsumeToken();
2394 
2395  // Attributes appear after the module name, not before.
2396  // FIXME: Suggest moving the attributes later with a fixit.
2397  DiagnoseAndSkipCXX11Attributes();
2398 
2399  // Parse a global-module-fragment, if present.
2400  if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2401  SourceLocation SemiLoc = ConsumeToken();
2402  if (ImportState != Sema::ModuleImportState::FirstDecl) {
2403  Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2404  << SourceRange(StartLoc, SemiLoc);
2405  return nullptr;
2406  }
2407  if (MDK == Sema::ModuleDeclKind::Interface) {
2408  Diag(StartLoc, diag::err_module_fragment_exported)
2409  << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2410  }
2412  return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2413  }
2414 
2415  // Parse a private-module-fragment, if present.
2416  if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2417  NextToken().is(tok::kw_private)) {
2418  if (MDK == Sema::ModuleDeclKind::Interface) {
2419  Diag(StartLoc, diag::err_module_fragment_exported)
2420  << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2421  }
2422  ConsumeToken();
2423  SourceLocation PrivateLoc = ConsumeToken();
2424  DiagnoseAndSkipCXX11Attributes();
2425  ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2427  return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2428  }
2429 
2431  if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2432  return nullptr;
2433 
2434  // Parse the optional module-partition.
2436  if (Tok.is(tok::colon)) {
2437  SourceLocation ColonLoc = ConsumeToken();
2438  if (!getLangOpts().CPlusPlusModules)
2439  Diag(ColonLoc, diag::err_unsupported_module_partition)
2440  << SourceRange(ColonLoc, Partition.back().second);
2441  // Recover by ignoring the partition name.
2442  else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
2443  return nullptr;
2444  }
2445 
2446  // We don't support any module attributes yet; just parse them and diagnose.
2447  ParsedAttributes Attrs(AttrFactory);
2448  MaybeParseCXX11Attributes(Attrs);
2449  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2450  /*DiagnoseEmptyAttrs=*/false,
2451  /*WarnOnUnknownAttrs=*/true);
2452 
2453  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2454 
2455  return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2456  ImportState);
2457 }
2458 
2459 /// Parse a module import declaration. This is essentially the same for
2460 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2461 /// trailing optional attributes (in C++).
2462 ///
2463 /// [ObjC] @import declaration:
2464 /// '@' 'import' module-name ';'
2465 /// [ModTS] module-import-declaration:
2466 /// 'import' module-name attribute-specifier-seq[opt] ';'
2467 /// [C++20] module-import-declaration:
2468 /// 'export'[opt] 'import' module-name
2469 /// attribute-specifier-seq[opt] ';'
2470 /// 'export'[opt] 'import' module-partition
2471 /// attribute-specifier-seq[opt] ';'
2472 /// 'export'[opt] 'import' header-name
2473 /// attribute-specifier-seq[opt] ';'
2474 Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2475  Sema::ModuleImportState &ImportState) {
2476  SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2477 
2478  SourceLocation ExportLoc;
2479  TryConsumeToken(tok::kw_export, ExportLoc);
2480 
2481  assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2482  : Tok.isObjCAtKeyword(tok::objc_import)) &&
2483  "Improper start to module import");
2484  bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2485  SourceLocation ImportLoc = ConsumeToken();
2486 
2487  // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2489  bool IsPartition = false;
2490  Module *HeaderUnit = nullptr;
2491  if (Tok.is(tok::header_name)) {
2492  // This is a header import that the preprocessor decided we should skip
2493  // because it was malformed in some way. Parse and ignore it; it's already
2494  // been diagnosed.
2495  ConsumeToken();
2496  } else if (Tok.is(tok::annot_header_unit)) {
2497  // This is a header import that the preprocessor mapped to a module import.
2498  HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2499  ConsumeAnnotationToken();
2500  } else if (Tok.is(tok::colon)) {
2501  SourceLocation ColonLoc = ConsumeToken();
2502  if (!getLangOpts().CPlusPlusModules)
2503  Diag(ColonLoc, diag::err_unsupported_module_partition)
2504  << SourceRange(ColonLoc, Path.back().second);
2505  // Recover by leaving partition empty.
2506  else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
2507  return nullptr;
2508  else
2509  IsPartition = true;
2510  } else {
2511  if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
2512  return nullptr;
2513  }
2514 
2515  ParsedAttributes Attrs(AttrFactory);
2516  MaybeParseCXX11Attributes(Attrs);
2517  // We don't support any module import attributes yet.
2518  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2519  /*DiagnoseEmptyAttrs=*/false,
2520  /*WarnOnUnknownAttrs=*/true);
2521 
2522  if (PP.hadModuleLoaderFatalFailure()) {
2523  // With a fatal failure in the module loader, we abort parsing.
2524  cutOffParsing();
2525  return nullptr;
2526  }
2527 
2528  // Diagnose mis-imports.
2529  bool SeenError = true;
2530  switch (ImportState) {
2532  SeenError = false;
2533  break;
2536  // We can only import a partition within a module purview.
2537  if (IsPartition)
2538  Diag(ImportLoc, diag::err_partition_import_outside_module);
2539  else
2540  SeenError = false;
2541  break;
2543  // We can only have pre-processor directives in the global module
2544  // fragment. We cannot import a named modules here, however we have a
2545  // header unit import.
2546  if (!HeaderUnit || HeaderUnit->Kind != Module::ModuleKind::ModuleHeaderUnit)
2547  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0;
2548  else
2549  SeenError = false;
2550  break;
2552  if (getLangOpts().CPlusPlusModules)
2553  Diag(ImportLoc, diag::err_import_not_allowed_here);
2554  else
2555  SeenError = false;
2556  break;
2558  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1;
2559  break;
2560  }
2561  if (SeenError) {
2562  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2563  return nullptr;
2564  }
2565 
2566  DeclResult Import;
2567  if (HeaderUnit)
2568  Import =
2569  Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2570  else if (!Path.empty())
2571  Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2572  IsPartition);
2573  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2574  if (Import.isInvalid())
2575  return nullptr;
2576 
2577  // Using '@import' in framework headers requires modules to be enabled so that
2578  // the header is parseable. Emit a warning to make the user aware.
2579  if (IsObjCAtImport && AtLoc.isValid()) {
2580  auto &SrcMgr = PP.getSourceManager();
2581  auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2582  if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2583  .endswith(".framework"))
2584  Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2585  }
2586 
2587  return Import.get();
2588 }
2589 
2590 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2591 /// grammar).
2592 ///
2593 /// module-name:
2594 /// module-name-qualifier[opt] identifier
2595 /// module-name-qualifier:
2596 /// module-name-qualifier[opt] identifier '.'
2597 bool Parser::ParseModuleName(
2598  SourceLocation UseLoc,
2599  SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2600  bool IsImport) {
2601  // Parse the module path.
2602  while (true) {
2603  if (!Tok.is(tok::identifier)) {
2604  if (Tok.is(tok::code_completion)) {
2605  cutOffParsing();
2606  Actions.CodeCompleteModuleImport(UseLoc, Path);
2607  return true;
2608  }
2609 
2610  Diag(Tok, diag::err_module_expected_ident) << IsImport;
2611  SkipUntil(tok::semi);
2612  return true;
2613  }
2614 
2615  // Record this part of the module path.
2616  Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2617  ConsumeToken();
2618 
2619  if (Tok.isNot(tok::period))
2620  return false;
2621 
2622  ConsumeToken();
2623  }
2624 }
2625 
2626 /// Try recover parser when module annotation appears where it must not
2627 /// be found.
2628 /// \returns false if the recover was successful and parsing may be continued, or
2629 /// true if parser must bail out to top level and handle the token there.
2630 bool Parser::parseMisplacedModuleImport() {
2631  while (true) {
2632  switch (Tok.getKind()) {
2633  case tok::annot_module_end:
2634  // If we recovered from a misplaced module begin, we expect to hit a
2635  // misplaced module end too. Stay in the current context when this
2636  // happens.
2637  if (MisplacedModuleBeginCount) {
2638  --MisplacedModuleBeginCount;
2639  Actions.ActOnModuleEnd(Tok.getLocation(),
2640  reinterpret_cast<Module *>(
2641  Tok.getAnnotationValue()));
2642  ConsumeAnnotationToken();
2643  continue;
2644  }
2645  // Inform caller that recovery failed, the error must be handled at upper
2646  // level. This will generate the desired "missing '}' at end of module"
2647  // diagnostics on the way out.
2648  return true;
2649  case tok::annot_module_begin:
2650  // Recover by entering the module (Sema will diagnose).
2651  Actions.ActOnModuleBegin(Tok.getLocation(),
2652  reinterpret_cast<Module *>(
2653  Tok.getAnnotationValue()));
2654  ConsumeAnnotationToken();
2655  ++MisplacedModuleBeginCount;
2656  continue;
2657  case tok::annot_module_include:
2658  // Module import found where it should not be, for instance, inside a
2659  // namespace. Recover by importing the module.
2660  Actions.ActOnModuleInclude(Tok.getLocation(),
2661  reinterpret_cast<Module *>(
2662  Tok.getAnnotationValue()));
2663  ConsumeAnnotationToken();
2664  // If there is another module import, process it.
2665  continue;
2666  default:
2667  return false;
2668  }
2669  }
2670  return false;
2671 }
2672 
2673 bool BalancedDelimiterTracker::diagnoseOverflow() {
2674  P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2675  << P.getLangOpts().BracketDepth;
2676  P.Diag(P.Tok, diag::note_bracket_depth);
2677  P.cutOffParsing();
2678  return true;
2679 }
2680 
2682  const char *Msg,
2683  tok::TokenKind SkipToTok) {
2684  LOpen = P.Tok.getLocation();
2685  if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2686  if (SkipToTok != tok::unknown)
2687  P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2688  return true;
2689  }
2690 
2691  if (getDepth() < P.getLangOpts().BracketDepth)
2692  return false;
2693 
2694  return diagnoseOverflow();
2695 }
2696 
2697 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2698  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2699 
2700  if (P.Tok.is(tok::annot_module_end))
2701  P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2702  else
2703  P.Diag(P.Tok, diag::err_expected) << Close;
2704  P.Diag(LOpen, diag::note_matching) << Kind;
2705 
2706  // If we're not already at some kind of closing bracket, skip to our closing
2707  // token.
2708  if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2709  P.Tok.isNot(tok::r_square) &&
2710  P.SkipUntil(Close, FinalToken,
2712  P.Tok.is(Close))
2713  LClose = P.ConsumeAnyToken();
2714  return true;
2715 }
2716 
2719  consumeClose();
2720 }
clang::Sema::ActOnModuleImport
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path, bool IsPartition=false)
The parser has processed a module import declaration.
Definition: SemaModule.cpp:471
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:5971
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1338
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:973
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:421
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:2630
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:75
clang::Sema::ModuleImportState::NotACXX20Module
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
clang::Sema::MarkAsLateParsedTemplate
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
Definition: SemaTemplate.cpp:11303
clang::ParsingDeclSpec
A class for parsing a DeclSpec.
Definition: RAIIObjectsForParser.h:175
clang::SourceRange::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:226
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:13096
clang::Sema::NC_NonType
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:2611
clang::Token::hasLeadingSpace
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:274
clang::DiagnosticBuilder
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1266
clang::TemplateIdAnnotation
Information about a template-id annotation token.
Definition: ParsedTemplate.h:149
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:58
clang::DeclaratorContext::File
@ File
clang::DeclSpec::TST_enum
static const TST TST_enum
Definition: DeclSpec.h:284
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::Sema::ActOnEndOfTranslationUnit
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:1106
clang::Preprocessor::setCodeCompletionHandler
void setCodeCompletionHandler(CodeCompletionHandler &Handler)
Set the code completion handler to the given object.
Definition: Preprocessor.h:1423
clang::ParsedAttributesView::none
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:927
clang::Preprocessor::isIncrementalProcessingEnabled
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
Definition: Preprocessor.h:1781
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:97
clang::Preprocessor::Lex
void Lex(Token &Result)
Lex the next token for this preprocessor.
Definition: Preprocessor.cpp:881
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:1231
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1637
clang::Sema::FnBodyKind
FnBodyKind
Definition: Sema.h:3027
clang::Decl::getAsFunction
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
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:818
llvm::SmallVector< Token, 4 >
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:597
clang::Preprocessor::getMaxTokens
unsigned getMaxTokens() const
Get the max number of tokens before issuing a -Wmax-tokens warning.
Definition: Preprocessor.h:1175
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Sema::ModuleDeclKind::Interface
@ Interface
'export module X;'
clang::ImplicitTypenameContext
ImplicitTypenameContext
Definition: DeclSpec.h:1817
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:134
clang::Parser::ParseFirstTopLevelDecl
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
Definition: Parser.cpp:584
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::ParsingDeclSpec::complete
void complete(Decl *D)
Definition: RAIIObjectsForParser.h:190
IsCommonTypo
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
Definition: Parser.cpp:102
clang::Token::getIdentifierInfo
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:181
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:13104
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:270
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:60
clang::Sema::FnBodyKind::Other
@ Other
C++ [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bloc...
clang::Sema::CodeCompleteInPreprocessorConditionalExclusion
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S)
Definition: SemaCodeComplete.cpp:9863
clang::DeclSpec::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:525
clang::DeclSpec::SCS_unspecified
@ SCS_unspecified
Definition: DeclSpec.h:235
clang::Sema::CodeCompletePreprocessorExpression
void CodeCompletePreprocessorExpression()
Definition: SemaCodeComplete.cpp:9895
clang::DeclSpec::getParsedSpecifiers
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:455
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:407
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:190
clang::Sema::NameClassification::getTemplateName
TemplateName getTemplateName() const
Definition: Sema.h:2728
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:1698
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:65
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:57
clang::Sema::NameClassification::getKind
NameClassificationKind getKind() const
Definition: Sema.h:2711
clang::Sema::ModuleImportState::FirstDecl
@ FirstDecl
Parsing the first decl in a TU.
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:185
clang::ImplicitTypenameContext::No
@ No
clang::BalancedDelimiterTracker
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Definition: RAIIObjectsForParser.h:388
clang::CommentHandler
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Definition: Preprocessor.h:2697
clang::ParsingDeclarator::getMutableDeclSpec
ParsingDeclSpec & getMutableDeclSpec() const
Definition: RAIIObjectsForParser.h:214
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:545
clang::Preprocessor::isCodeCompletionReached
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
Definition: Preprocessor.h:1824
clang::Declarator::getIdentifierLoc
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2257
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:1072
clang::DeclSpec::getTypeSpecTypeLoc
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:533
clang::DeclSpec::TSCS_unspecified
static const TSCS TSCS_unspecified
Definition: DeclSpec.h:248
clang::Scope::getParent
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:244
clang::TypeError
TypeResult TypeError()
Definition: Ownership.h:280
clang::Sema::ActOnTranslationUnitScope
void ActOnTranslationUnitScope(Scope *S)
Definition: Sema.cpp:125
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:2601
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:1720
clang::AS_none
@ AS_none
Definition: Specifiers.h:115
clang::DeclSpec::SetRangeStart
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:658
clang::Sema::ActOnFinishFunctionBody
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15164
clang::ParenBraceBracketBalancer
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Definition: RAIIObjectsForParser.h:346
clang::Sema::CheckForFunctionRedefinition
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14817
clang::Sema::CodeCompleteIncludedFile
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Definition: SemaCodeComplete.cpp:9933
clang::Sema::ActOnModuleDecl
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, ModuleIdPath Partition, ModuleImportState &ImportState)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Definition: SemaModule.cpp:178
llvm::MutableArrayRef
Definition: LLVM.h:35
clang::Sema::ModuleImportState::ImportFinished
@ ImportFinished
after any non-import decl.
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:2624
clang::ASTContext::getExternalSource
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1194
clang::Preprocessor::SetPoisonReason
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
Definition: Preprocessor.cpp:747
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:1014
clang::Module
Describes a module or submodule.
Definition: Module.h:98
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:1770
DeclTemplate.h
clang::Sema::SkipBodyInfo::ShouldSkip
bool ShouldSkip
Definition: Sema.h:2557
clang::Sema::CodeCompletePreprocessorDirective
void CodeCompletePreprocessorDirective(bool InConditional)
Definition: SemaCodeComplete.cpp:9693
clang::ImportDecl
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4587
clang::Sema::NameClassification
Definition: Sema.h:2637
clang::Sema::PCC_Class
@ PCC_Class
Code completion occurs within a class, struct, or union.
Definition: Sema.h:13098
clang::DeclSpec::getTypeSpecType
TST getTypeSpecType() const
Definition: DeclSpec.h:495
Id
int Id
Definition: ASTDiff.cpp:189
clang::Sema::CodeCompleteObjCMethodDecl
void CodeCompleteObjCMethodDecl(Scope *S, Optional< bool > IsInstanceMethod, ParsedType ReturnType)
Definition: SemaCodeComplete.cpp:9432
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:2847
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
Definition: ParsedTemplate.h:182
clang::Parser::SkipUntilFlags
SkipUntilFlags
Control flags for SkipUntil functions.
Definition: Parser.h:1209
clang::DeclSpec::TST_interface
static const TST TST_interface
Definition: DeclSpec.h:287
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
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:1443
clang::Parser::StopAtCodeCompletion
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1213
clang::Preprocessor::addCommentHandler
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
Definition: Preprocessor.cpp:1394
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:93
clang::MultiTemplateParamsArg
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:276
clang::Sema::ActOnSkippedFunctionBody
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15154
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:53
clang::Token::getAnnotationValue
void * getAnnotationValue() const
Definition: Token.h:228
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:13128
clang::BalancedDelimiterTracker::expectAndConsume
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2681
clang::Sema::IER_DoesNotExist
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:5964
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1299
clang::DeclSpec::ClearStorageClassSpecs
void ClearStorageClassSpecs()
Definition: DeclSpec.h:473
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:1212
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:2713
clang::Sema::Initialize
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:266
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:1965
clang::DeclSpec::TST_class
static const TST TST_class
Definition: DeclSpec.h:288
clang::Preprocessor::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Definition: Preprocessor.h:1899
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:442
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:898
clang::RISCV::Policy
Policy
Definition: RISCVVIntrinsicUtils.h:96
clang::DeclSpec::hasTagDefinition
bool hasTagDefinition() const
Definition: DeclSpec.cpp:446
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:98
clang::Sema::ModuleImportState::GlobalFragment
@ GlobalFragment
after 'module;' but before 'module X;'
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:520
clang::Preprocessor::isBacktrackEnabled
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
Definition: Preprocessor.h:1584
clang::DeclContext::isTranslationUnit
bool isTranslationUnit() const
Definition: DeclBase.h:1998
clang::Sema::SetFunctionBodyKind
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind)
Definition: SemaDeclCXX.cpp:17680
clang::Sema::NC_DependentNonType
@ NC_DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:2619
clang::Parser::TryAnnotateCXXScopeToken
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2166
clang::ParsedAttr
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:233
clang::SourceManager::getFileID
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Definition: SourceManager.h:1116
clang::Token::setAnnotationValue
void setAnnotationValue(void *val)
Definition: Token.h:232
clang::ParsingDeclarator::complete
void complete(Decl *D)
Definition: RAIIObjectsForParser.h:223
clang::Sema::NameClassification::getNonTypeDecl
NamedDecl * getNonTypeDecl() const
Definition: Sema.h:2723
clang::Sema::CodeCompleteOrdinaryName
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
Definition: SemaCodeComplete.cpp:4331
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:620
clang::TemplateIdAnnotation::Kind
TemplateNameKind Kind
The kind of template that Template refers to.
Definition: ParsedTemplate.h:174
ASTContext.h
clang::Sema::ActOnTypenameType
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
Definition: SemaTemplate.cpp:10731
clang::Declarator::setFunctionDefinitionKind
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2642
clang::Sema::SkipBodyInfo
Definition: Sema.h:2553
clang::DeclSpec::getStorageClassSpec
SCS getStorageClassSpec() const
Definition: DeclSpec.h:459
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:102
clang::Parser::MightBeCXXScopeToken
bool MightBeCXXScopeToken()
Definition: Parser.h:868
clang::Sema::ParsedFreeStandingDeclSpec
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4831
clang::DeclSpec::TST_union
static const TST TST_union
Definition: DeclSpec.h:285
clang::Sema::CheckMicrosoftIfExistsSymbol
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
Definition: SemaExprCXX.cpp:8878
clang::DeclSpec::SCS_register
@ SCS_register
Definition: DeclSpec.h:240
clang::Parser::getCurScope
Scope * getCurScope() const
Definition: Parser.h:449
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:1363
clang::Sema::CodeCompleteModuleImport
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path)
Definition: SemaCodeComplete.cpp:4283
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:99
clang::DeclSpec::getThreadStorageClassSpecLoc
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:469
getKind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1024
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:2361
clang::Sema::CodeCompleteNaturalLanguage
void CodeCompleteNaturalLanguage()
Definition: SemaCodeComplete.cpp:10075
clang::Parser::ParseStringLiteralExpression
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1277
clang::Parser::StopAtSemi
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1210
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:2011
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:58
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:7011
clang::Sema::ActOnFinishKNRParamDeclarations
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:14667
clang::OpaquePtr
Wrapper for void* pointer.
Definition: Ownership.h:50
clang::Sema::NameClassification::getTemplateNameKind
TemplateNameKind getTemplateNameKind() const
Definition: Sema.h:2735
clang::DeclSpec::TST_int
static const TST TST_int
Definition: DeclSpec.h:268
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
Definition: ParsedTemplate.h:178
clang::DeclSpec::getStorageClassSpecLoc
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:468
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:1069
IsHeaderFile
static bool IsHeaderFile(const std::string &Filename)
Definition: RewriteModernObjC.cpp:629
clang::ParsedAttributesView::Range
SourceRange Range
Definition: ParsedAttr.h:925
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:15112
clang::AccessSpecifier
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:111
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:1914
clang::Preprocessor::getTokenCount
unsigned getTokenCount() const
Get the number of tokens processed so far.
Definition: Preprocessor.h:1172
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:5968
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::Sema::ModuleImportState
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:3123
clang::TemplateIdAnnotation::TemplateNameLoc
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
Definition: ParsedTemplate.h:159
clang::Declarator::getFunctionTypeInfo
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2392
clang::Parser::ConsumeToken
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:492
clang::Preprocessor::hadModuleLoaderFatalFailure
bool hadModuleLoaderFatalFailure() const
Definition: Preprocessor.h:1089
false
#define false
Definition: stdbool.h:22
clang::DeclSpec::isDeclRep
static bool isDeclRep(TST T)
Definition: DeclSpec.h:427
clang::TemplateIdAnnotation::mightBeType
bool mightBeType() const
Determine whether this might be a type template.
Definition: ParsedTemplate.h:223
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:2626
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:201
clang::Preprocessor::isCodeCompletionEnabled
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
Definition: Preprocessor.h:1806
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
llvm::ArrayRef
Definition: LLVM.h:34
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::ParsingDeclarator::getDeclSpec
const ParsingDeclSpec & getDeclSpec() const
Definition: RAIIObjectsForParser.h:210
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:460
clang::Sema::ActOnComment
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2364
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:358
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::Sema::NC_Type
@ NC_Type
The name was classified as a type.
Definition: Sema.h:2607
clang::FunctionDefinitionKind::Definition
@ Definition
clang::Parser::ParseTopLevelDecl
bool ParseTopLevelDecl()
Definition: Parser.h:481
ASTConsumer.h
clang::Parser::TryConsumeToken
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:500
clang::ParsedAttributes
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:1023
clang::Sema::NameClassification::getType
ParsedType getType() const
Definition: Sema.h:2718
clang::PoisonSEHIdentifiersRAIIObject
Definition: RAIIObjectsForParser.h:362
clang::Sema::ActOnFileScopeAsmDecl
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:19541
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:85
clang::Sema::NC_UndeclaredTemplate
@ NC_UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition: Sema.h:2632
clang::Sema::ActOnStartOfTranslationUnit
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:1022
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:312
clang::Sema::NC_Concept
@ NC_Concept
The name was classified as a concept name.
Definition: Sema.h:2634
clang::OpaquePtr< TemplateName >::make
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:60
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::Sema::BuildDeclaratorGroup
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14301
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::Sema::FnBodyKind::Delete
@ Delete
= delete ;
clang::Preprocessor::removeCommentHandler
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
Definition: Preprocessor.cpp:1401
clang::ActionResult
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc.
Definition: Ownership.h:152
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:7015
clang::ExtensionRAIIObject
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
Definition: RAIIObjectsForParser.h:255
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:1052
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:134
clang::Sema::ModuleImportState::ImportAllowed
@ ImportAllowed
after 'module X;' but before any non-import decl.
clang::Sema::ActOnModuleEnd
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaModule.cpp:685
clang::DeclSpec::TST_unspecified
static const TST TST_unspecified
Definition: DeclSpec.h:261
clang::TemplateIdAnnotation::TemplateKWLoc
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
Definition: ParsedTemplate.h:155
clang::DeclSpec::takeAttributesFrom
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:821
clang::Module::Kind
ModuleKind Kind
The kind of this module.
Definition: Module.h:131
clang::Sema::NC_Keyword
@ NC_Keyword
The name has been typo-corrected to a keyword.
Definition: Sema.h:2605
clang::Module::isHeaderUnit
bool isHeaderUnit() const
Is this module a header unit.
Definition: Module.h:547
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::Preprocessor::clearCodeCompletionHandler
void clearCodeCompletionHandler()
Clear out the code completion handler.
Definition: Preprocessor.h:1433
clang::BalancedDelimiterTracker::skipToEnd
void skipToEnd()
Definition: Parser.cpp:2717
clang
Definition: CalledOnceCheck.h:17
clang::Preprocessor::getMaxTokensOverrideLoc
SourceLocation getMaxTokensOverrideLoc() const
Definition: Preprocessor.h:1182
clang::Sema::NC_UndeclaredNonType
@ NC_UndeclaredNonType
The name was classified as an ADL-only function name.
Definition: Sema.h:2615
clang::TemplateIdAnnotation::Name
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
Definition: ParsedTemplate.h:162
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:71
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:192
clang::Sema::IER_Exists
@ IER_Exists
The symbol exists.
Definition: Sema.h:5961
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1834
clang::Sema::FnBodyKind::Default
@ Default
= default ;
clang::Sema::CodeCompletePreprocessorMacroName
void CodeCompletePreprocessorMacroName(bool IsDefinition)
Definition: SemaCodeComplete.cpp:9868
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
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::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
clang::Sema::ActOnDefaultCtorInitializers
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
Definition: SemaDeclCXX.cpp:5795
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:2023
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:94
ParseDiagnostic.h
clang::BalancedDelimiterTracker::consumeClose
bool consumeClose()
Definition: RAIIObjectsForParser.h:449
clang::TemplateIdAnnotation::isInvalid
bool isInvalid() const
Definition: ParsedTemplate.h:233
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, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:327
clang::Parser::TryAnnotateTypeOrScopeToken
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1933
clang::Sema::ModuleImportState::PrivateFragment
@ PrivateFragment
after 'module :private;'.
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:100
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:286
clang::Sema::CodeCompletePreprocessorMacroArgument
void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument)
Definition: SemaCodeComplete.cpp:9919
clang::SourceManager::getFileEntryRefForID
Optional< FileEntryRef > getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
Definition: SourceManager.h:1050
clang::Sema::SetLateTemplateParser
void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P)
Definition: Sema.h:923
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:54
clang::ParsingDeclarator
A class for parsing a declarator.
Definition: RAIIObjectsForParser.h:200
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
llvm::SmallVectorImpl
Definition: Randstruct.h:18
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:6224
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:654
true
#define true
Definition: stdbool.h:21
clang::HLSL
@ HLSL
Definition: LangStandard.h:63
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:129
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:191
clang::IdentifierInfo::revertTokenIDToIdentifier
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
Definition: IdentifierTable.h:273
clang::Declarator::getAttributes
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2588
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:70
clang::DeclSpec::SetRangeEnd
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:659
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:15136
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:74
clang::Sema::NC_VarTemplate
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:2628
clang::IdentifierLoc
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:211
clang::Parser::NextToken
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:811
clang::Sema::ActOnStartOfFunctionDef
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:14715
clang::Sema::ModuleDeclKind
ModuleDeclKind
Definition: Sema.h:3113
clang::Sema::ActOnPopScope
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:2211
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:2603
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:172
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1904
clang::DeclaratorChunk::ParamInfo::Ident
IdentifierInfo * Ident
Definition: DeclSpec.h:1275
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3983
clang::TemplateIdAnnotation::Template
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Definition: ParsedTemplate.h:169
clang::Parser::TemplateParameterLists
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:463
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:1682
clang::Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
Definition: Parser.cpp:2051
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:193
clang::DeclSpec::SetTypeSpecType
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:832
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1383
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:134
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:14417
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:230
clang::Sema::ActOnModuleBegin
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaModule.cpp:661
clang::DeclSpec::SCS_extern
@ SCS_extern
Definition: DeclSpec.h:237
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
ParsedTemplate.h
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:196
clang::TypeSpecifierType
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:52
clang::Sema::getASTConsumer
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1638
clang::DeclSpec::PQ_StorageClassSpecifier
@ PQ_StorageClassSpecifier
Definition: DeclSpec.h:324
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:16465
clang::DeclSpec::getThreadStorageClassSpec
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:460