clang  16.0.0git
Preprocessor.cpp
Go to the documentation of this file.
1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
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 Preprocessor interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // Options to support:
14 // -H - Print the name of each header file used.
15 // -d[DNI] - Dump various things.
16 // -fworking-directory - #line's with preprocessor's working dir.
17 // -fpreprocessed
18 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19 // -W*
20 // -w
21 //
22 // Messages to emit:
23 // "Multiple include guards may be useful for:\n"
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/Module.h"
37 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Lex/HeaderSearch.h"
42 #include "clang/Lex/Lexer.h"
44 #include "clang/Lex/MacroArgs.h"
45 #include "clang/Lex/MacroInfo.h"
46 #include "clang/Lex/ModuleLoader.h"
47 #include "clang/Lex/Pragma.h"
52 #include "clang/Lex/Token.h"
53 #include "clang/Lex/TokenLexer.h"
54 #include "llvm/ADT/APInt.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/Support/Capacity.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/MemoryBuffer.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <memory>
68 #include <string>
69 #include <utility>
70 #include <vector>
71 
72 using namespace clang;
73 
74 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
75 
77 
78 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
79  DiagnosticsEngine &diags, LangOptions &opts,
80  SourceManager &SM, HeaderSearch &Headers,
81  ModuleLoader &TheModuleLoader,
82  IdentifierInfoLookup *IILookup, bool OwnsHeaders,
83  TranslationUnitKind TUKind)
84  : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
85  FileMgr(Headers.getFileMgr()), SourceMgr(SM),
86  ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
87  TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
88  // As the language options may have not been loaded yet (when
89  // deserializing an ASTUnit), adding keywords to the identifier table is
90  // deferred to Preprocessor::Initialize().
91  Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
92  TUKind(TUKind), SkipMainFilePreamble(0, true),
93  CurSubmoduleState(&NullSubmoduleState) {
94  OwnsHeaderSearch = OwnsHeaders;
95 
96  // Default to discarding comments.
97  KeepComments = false;
98  KeepMacroComments = false;
99  SuppressIncludeNotFoundError = false;
100 
101  // Macro expansion is enabled.
102  DisableMacroExpansion = false;
103  MacroExpansionInDirectivesOverride = false;
104  InMacroArgs = false;
105  ArgMacro = nullptr;
106  InMacroArgPreExpansion = false;
107  NumCachedTokenLexers = 0;
108  PragmasEnabled = true;
109  ParsingIfOrElifDirective = false;
110  PreprocessedOutput = false;
111 
112  // We haven't read anything from the external source.
113  ReadMacrosFromExternalSource = false;
114 
115  BuiltinInfo = std::make_unique<Builtin::Context>();
116 
117  // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
118  // a macro. They get unpoisoned where it is allowed.
119  (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
120  SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
121  (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
122  SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
123 
124  // Initialize the pragma handlers.
125  RegisterBuiltinPragmas();
126 
127  // Initialize builtin macros like __LINE__ and friends.
128  RegisterBuiltinMacros();
129 
130  if(LangOpts.Borland) {
131  Ident__exception_info = getIdentifierInfo("_exception_info");
132  Ident___exception_info = getIdentifierInfo("__exception_info");
133  Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
134  Ident__exception_code = getIdentifierInfo("_exception_code");
135  Ident___exception_code = getIdentifierInfo("__exception_code");
136  Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
137  Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
138  Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
139  Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
140  } else {
141  Ident__exception_info = Ident__exception_code = nullptr;
142  Ident__abnormal_termination = Ident___exception_info = nullptr;
143  Ident___exception_code = Ident___abnormal_termination = nullptr;
144  Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
145  Ident_AbnormalTermination = nullptr;
146  }
147 
148  // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
150  SkippingUntilPragmaHdrStop = true;
151 
152  // If using a PCH with a through header, start skipping tokens.
153  if (!this->PPOpts->PCHThroughHeader.empty() &&
154  !this->PPOpts->ImplicitPCHInclude.empty())
155  SkippingUntilPCHThroughHeader = true;
156 
157  if (this->PPOpts->GeneratePreamble)
158  PreambleConditionalStack.startRecording();
159 
160  MaxTokens = LangOpts.MaxTokens;
161 }
162 
164  assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
165 
166  IncludeMacroStack.clear();
167 
168  // Destroy any macro definitions.
169  while (MacroInfoChain *I = MIChainHead) {
170  MIChainHead = I->Next;
171  I->~MacroInfoChain();
172  }
173 
174  // Free any cached macro expanders.
175  // This populates MacroArgCache, so all TokenLexers need to be destroyed
176  // before the code below that frees up the MacroArgCache list.
177  std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
178  CurTokenLexer.reset();
179 
180  // Free any cached MacroArgs.
181  for (MacroArgs *ArgList = MacroArgCache; ArgList;)
182  ArgList = ArgList->deallocate();
183 
184  // Delete the header search info, if we own it.
185  if (OwnsHeaderSearch)
186  delete &HeaderInfo;
187 }
188 
190  const TargetInfo *AuxTarget) {
191  assert((!this->Target || this->Target == &Target) &&
192  "Invalid override of target information");
193  this->Target = &Target;
194 
195  assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
196  "Invalid override of aux target information.");
197  this->AuxTarget = AuxTarget;
198 
199  // Initialize information about built-ins.
200  BuiltinInfo->InitializeTarget(Target, AuxTarget);
201  HeaderInfo.setTarget(Target);
202 
203  // Populate the identifier table with info about keywords for the current language.
204  Identifiers.AddKeywords(LangOpts);
205 
206  // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
207  setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
208 
209  if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
210  // Use setting from TargetInfo.
211  setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
212  else
213  // Set initial value of __FLT_EVAL_METHOD__ from the command line.
214  setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
215  // When `-ffast-math` option is enabled, it triggers several driver math
216  // options to be enabled. Among those, only one the following two modes
217  // affect the eval-method: reciprocal or reassociate.
218  if (getLangOpts().AllowFPReassoc || getLangOpts().AllowRecip)
220 }
221 
223  NumEnteredSourceFiles = 0;
224 
225  // Reset pragmas
226  PragmaHandlersBackup = std::move(PragmaHandlers);
227  PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
228  RegisterBuiltinPragmas();
229 
230  // Reset PredefinesFileID
231  PredefinesFileID = FileID();
232 }
233 
235  NumEnteredSourceFiles = 1;
236 
237  PragmaHandlers = std::move(PragmaHandlersBackup);
238 }
239 
240 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
241  llvm::errs() << tok::getTokenName(Tok.getKind());
242 
243  if (!Tok.isAnnotation())
244  llvm::errs() << " '" << getSpelling(Tok) << "'";
245 
246  if (!DumpFlags) return;
247 
248  llvm::errs() << "\t";
249  if (Tok.isAtStartOfLine())
250  llvm::errs() << " [StartOfLine]";
251  if (Tok.hasLeadingSpace())
252  llvm::errs() << " [LeadingSpace]";
253  if (Tok.isExpandDisabled())
254  llvm::errs() << " [ExpandDisabled]";
255  if (Tok.needsCleaning()) {
256  const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
257  llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
258  << "']";
259  }
260 
261  llvm::errs() << "\tLoc=<";
262  DumpLocation(Tok.getLocation());
263  llvm::errs() << ">";
264 }
265 
267  Loc.print(llvm::errs(), SourceMgr);
268 }
269 
270 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
271  llvm::errs() << "MACRO: ";
272  for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
274  llvm::errs() << " ";
275  }
276  llvm::errs() << "\n";
277 }
278 
280  llvm::errs() << "\n*** Preprocessor Stats:\n";
281  llvm::errs() << NumDirectives << " directives found:\n";
282  llvm::errs() << " " << NumDefined << " #define.\n";
283  llvm::errs() << " " << NumUndefined << " #undef.\n";
284  llvm::errs() << " #include/#include_next/#import:\n";
285  llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
286  llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
287  llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
288  llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
289  llvm::errs() << " " << NumEndif << " #endif.\n";
290  llvm::errs() << " " << NumPragma << " #pragma.\n";
291  llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
292 
293  llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
294  << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
295  << NumFastMacroExpanded << " on the fast path.\n";
296  llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
297  << " token paste (##) operations performed, "
298  << NumFastTokenPaste << " on the fast path.\n";
299 
300  llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
301 
302  llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
303  llvm::errs() << "\n Macro Expanded Tokens: "
304  << llvm::capacity_in_bytes(MacroExpandedTokens);
305  llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
306  // FIXME: List information for all submodules.
307  llvm::errs() << "\n Macros: "
308  << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
309  llvm::errs() << "\n #pragma push_macro Info: "
310  << llvm::capacity_in_bytes(PragmaPushMacroInfo);
311  llvm::errs() << "\n Poison Reasons: "
312  << llvm::capacity_in_bytes(PoisonReasons);
313  llvm::errs() << "\n Comment Handlers: "
314  << llvm::capacity_in_bytes(CommentHandlers) << "\n";
315 }
316 
318 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
319  if (IncludeExternalMacros && ExternalSource &&
320  !ReadMacrosFromExternalSource) {
321  ReadMacrosFromExternalSource = true;
322  ExternalSource->ReadDefinedMacros();
323  }
324 
325  // Make sure we cover all macros in visible modules.
326  for (const ModuleMacro &Macro : ModuleMacros)
327  CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
328 
329  return CurSubmoduleState->Macros.begin();
330 }
331 
333  return BP.getTotalMemory()
334  + llvm::capacity_in_bytes(MacroExpandedTokens)
335  + Predefines.capacity() /* Predefines buffer. */
336  // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
337  // and ModuleMacros.
338  + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
339  + llvm::capacity_in_bytes(PragmaPushMacroInfo)
340  + llvm::capacity_in_bytes(PoisonReasons)
341  + llvm::capacity_in_bytes(CommentHandlers);
342 }
343 
345 Preprocessor::macro_end(bool IncludeExternalMacros) const {
346  if (IncludeExternalMacros && ExternalSource &&
347  !ReadMacrosFromExternalSource) {
348  ReadMacrosFromExternalSource = true;
349  ExternalSource->ReadDefinedMacros();
350  }
351 
352  return CurSubmoduleState->Macros.end();
353 }
354 
355 /// Compares macro tokens with a specified token value sequence.
356 static bool MacroDefinitionEquals(const MacroInfo *MI,
357  ArrayRef<TokenValue> Tokens) {
358  return Tokens.size() == MI->getNumTokens() &&
359  std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
360 }
361 
363  SourceLocation Loc,
364  ArrayRef<TokenValue> Tokens) const {
365  SourceLocation BestLocation;
366  StringRef BestSpelling;
368  I != E; ++I) {
370  Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
371  if (!Def || !Def.getMacroInfo())
372  continue;
373  if (!Def.getMacroInfo()->isObjectLike())
374  continue;
375  if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
376  continue;
377  SourceLocation Location = Def.getLocation();
378  // Choose the macro defined latest.
379  if (BestLocation.isInvalid() ||
380  (Location.isValid() &&
381  SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
382  BestLocation = Location;
383  BestSpelling = I->first->getName();
384  }
385  }
386  return BestSpelling;
387 }
388 
390  if (CurLexer)
391  CurLexerKind = CurLexer->isDependencyDirectivesLexer()
392  ? CLK_DependencyDirectivesLexer
393  : CLK_Lexer;
394  else if (CurTokenLexer)
395  CurLexerKind = CLK_TokenLexer;
396  else
397  CurLexerKind = CLK_CachingLexer;
398 }
399 
401  unsigned CompleteLine,
402  unsigned CompleteColumn) {
403  assert(File);
404  assert(CompleteLine && CompleteColumn && "Starts from 1:1");
405  assert(!CodeCompletionFile && "Already set");
406 
407  // Load the actual file's contents.
410  if (!Buffer)
411  return true;
412 
413  // Find the byte position of the truncation point.
414  const char *Position = Buffer->getBufferStart();
415  for (unsigned Line = 1; Line < CompleteLine; ++Line) {
416  for (; *Position; ++Position) {
417  if (*Position != '\r' && *Position != '\n')
418  continue;
419 
420  // Eat \r\n or \n\r as a single line.
421  if ((Position[1] == '\r' || Position[1] == '\n') &&
422  Position[0] != Position[1])
423  ++Position;
424  ++Position;
425  break;
426  }
427  }
428 
429  Position += CompleteColumn - 1;
430 
431  // If pointing inside the preamble, adjust the position at the beginning of
432  // the file after the preamble.
433  if (SkipMainFilePreamble.first &&
434  SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
435  if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
436  Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
437  }
438 
439  if (Position > Buffer->getBufferEnd())
440  Position = Buffer->getBufferEnd();
441 
442  CodeCompletionFile = File;
443  CodeCompletionOffset = Position - Buffer->getBufferStart();
444 
445  auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
446  Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
447  char *NewBuf = NewBuffer->getBufferStart();
448  char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
449  *NewPos = '\0';
450  std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
451  SourceMgr.overrideFileContents(File, std::move(NewBuffer));
452 
453  return false;
454 }
455 
456 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
457  bool IsAngled) {
459  if (CodeComplete)
460  CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
461 }
462 
465  if (CodeComplete)
466  CodeComplete->CodeCompleteNaturalLanguage();
467 }
468 
469 /// getSpelling - This method is used to get the spelling of a token into a
470 /// SmallVector. Note that the returned StringRef may not point to the
471 /// supplied buffer if a copy can be avoided.
472 StringRef Preprocessor::getSpelling(const Token &Tok,
473  SmallVectorImpl<char> &Buffer,
474  bool *Invalid) const {
475  // NOTE: this has to be checked *before* testing for an IdentifierInfo.
476  if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
477  // Try the fast path.
478  if (const IdentifierInfo *II = Tok.getIdentifierInfo())
479  return II->getName();
480  }
481 
482  // Resize the buffer if we need to copy into it.
483  if (Tok.needsCleaning())
484  Buffer.resize(Tok.getLength());
485 
486  const char *Ptr = Buffer.data();
487  unsigned Len = getSpelling(Tok, Ptr, Invalid);
488  return StringRef(Ptr, Len);
489 }
490 
491 /// CreateString - Plop the specified string into a scratch buffer and return a
492 /// location for it. If specified, the source location provides a source
493 /// location for the token.
494 void Preprocessor::CreateString(StringRef Str, Token &Tok,
495  SourceLocation ExpansionLocStart,
496  SourceLocation ExpansionLocEnd) {
497  Tok.setLength(Str.size());
498 
499  const char *DestPtr;
500  SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
501 
502  if (ExpansionLocStart.isValid())
503  Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
504  ExpansionLocEnd, Str.size());
505  Tok.setLocation(Loc);
506 
507  // If this is a raw identifier or a literal token, set the pointer data.
508  if (Tok.is(tok::raw_identifier))
509  Tok.setRawIdentifierData(DestPtr);
510  else if (Tok.isLiteral())
511  Tok.setLiteralData(DestPtr);
512 }
513 
515  auto &SM = getSourceManager();
516  SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
517  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
518  bool Invalid = false;
519  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
520  if (Invalid)
521  return SourceLocation();
522 
523  // FIXME: We could consider re-using spelling for tokens we see repeatedly.
524  const char *DestPtr;
525  SourceLocation Spelling =
526  ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
527  return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
528 }
529 
531  if (!getLangOpts().isCompilingModule())
532  return nullptr;
533 
534  return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
535 }
536 
538  if (!getLangOpts().isCompilingModuleImplementation())
539  return nullptr;
540 
541  return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
542 }
543 
544 //===----------------------------------------------------------------------===//
545 // Preprocessor Initialization Methods
546 //===----------------------------------------------------------------------===//
547 
548 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
549 /// which implicitly adds the builtin defines etc.
551  // We do not allow the preprocessor to reenter the main file. Doing so will
552  // cause FileID's to accumulate information from both runs (e.g. #line
553  // information) and predefined macros aren't guaranteed to be set properly.
554  assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
555  FileID MainFileID = SourceMgr.getMainFileID();
556 
557  // If MainFileID is loaded it means we loaded an AST file, no need to enter
558  // a main file.
559  if (!SourceMgr.isLoadedFileID(MainFileID)) {
560  // Enter the main file source buffer.
561  EnterSourceFile(MainFileID, nullptr, SourceLocation());
562 
563  // If we've been asked to skip bytes in the main file (e.g., as part of a
564  // precompiled preamble), do so now.
565  if (SkipMainFilePreamble.first > 0)
566  CurLexer->SetByteOffset(SkipMainFilePreamble.first,
567  SkipMainFilePreamble.second);
568 
569  // Tell the header info that the main file was entered. If the file is later
570  // #imported, it won't be re-entered.
571  if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
572  markIncluded(FE);
573  }
574 
575  // Preprocess Predefines to populate the initial preprocessor state.
576  std::unique_ptr<llvm::MemoryBuffer> SB =
577  llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
578  assert(SB && "Cannot create predefined source buffer");
579  FileID FID = SourceMgr.createFileID(std::move(SB));
580  assert(FID.isValid() && "Could not create FileID for predefines?");
581  setPredefinesFileID(FID);
582 
583  // Start parsing the predefines.
584  EnterSourceFile(FID, nullptr, SourceLocation());
585 
586  if (!PPOpts->PCHThroughHeader.empty()) {
587  // Lookup and save the FileID for the through header. If it isn't found
588  // in the search path, it's a fatal error.
590  SourceLocation(), PPOpts->PCHThroughHeader,
591  /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
592  /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
593  /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
594  /*IsFrameworkFound=*/nullptr);
595  if (!File) {
596  Diag(SourceLocation(), diag::err_pp_through_header_not_found)
597  << PPOpts->PCHThroughHeader;
598  return;
599  }
600  setPCHThroughHeaderFileID(
602  }
603 
604  // Skip tokens from the Predefines and if needed the main file.
605  if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
606  (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
608 }
609 
610 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
611  assert(PCHThroughHeaderFileID.isInvalid() &&
612  "PCHThroughHeaderFileID already set!");
613  PCHThroughHeaderFileID = FID;
614 }
615 
617  assert(PCHThroughHeaderFileID.isValid() &&
618  "Invalid PCH through header FileID");
619  return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
620 }
621 
623  return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
624  PCHThroughHeaderFileID.isValid();
625 }
626 
628  return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
629  PCHThroughHeaderFileID.isValid();
630 }
631 
633  return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
634 }
635 
637  return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
638 }
639 
640 /// Skip tokens until after the #include of the through header or
641 /// until after a #pragma hdrstop is seen. Tokens in the predefines file
642 /// and the main file may be skipped. If the end of the predefines file
643 /// is reached, skipping continues into the main file. If the end of the
644 /// main file is reached, it's a fatal error.
646  bool ReachedMainFileEOF = false;
647  bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
648  bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
649  Token Tok;
650  while (true) {
651  bool InPredefines =
652  (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
653  switch (CurLexerKind) {
654  case CLK_Lexer:
655  CurLexer->Lex(Tok);
656  break;
657  case CLK_TokenLexer:
658  CurTokenLexer->Lex(Tok);
659  break;
660  case CLK_CachingLexer:
661  CachingLex(Tok);
662  break;
663  case CLK_DependencyDirectivesLexer:
664  CurLexer->LexDependencyDirectiveToken(Tok);
665  break;
666  case CLK_LexAfterModuleImport:
668  break;
669  }
670  if (Tok.is(tok::eof) && !InPredefines) {
671  ReachedMainFileEOF = true;
672  break;
673  }
674  if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
675  break;
676  if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
677  break;
678  }
679  if (ReachedMainFileEOF) {
680  if (UsingPCHThroughHeader)
681  Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
682  << PPOpts->PCHThroughHeader << 1;
683  else if (!PPOpts->PCHWithHdrStopCreate)
684  Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
685  }
686 }
687 
688 void Preprocessor::replayPreambleConditionalStack() {
689  // Restore the conditional stack from the preamble, if there is one.
690  if (PreambleConditionalStack.isReplaying()) {
691  assert(CurPPLexer &&
692  "CurPPLexer is null when calling replayPreambleConditionalStack.");
693  CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
694  PreambleConditionalStack.doneReplaying();
695  if (PreambleConditionalStack.reachedEOFWhileSkipping())
696  SkipExcludedConditionalBlock(
697  PreambleConditionalStack.SkipInfo->HashTokenLoc,
698  PreambleConditionalStack.SkipInfo->IfTokenLoc,
699  PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
700  PreambleConditionalStack.SkipInfo->FoundElse,
701  PreambleConditionalStack.SkipInfo->ElseLoc);
702  }
703 }
704 
706  // Notify the client that we reached the end of the source file.
707  if (Callbacks)
708  Callbacks->EndOfMainFile();
709 }
710 
711 //===----------------------------------------------------------------------===//
712 // Lexer Event Handling.
713 //===----------------------------------------------------------------------===//
714 
715 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
716 /// identifier information for the token and install it into the token,
717 /// updating the token kind accordingly.
719  assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
720 
721  // Look up this token, see if it is a macro, or if it is a language keyword.
722  IdentifierInfo *II;
723  if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
724  // No cleaning needed, just use the characters from the lexed buffer.
725  II = getIdentifierInfo(Identifier.getRawIdentifier());
726  } else {
727  // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
728  SmallString<64> IdentifierBuffer;
729  StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
730 
731  if (Identifier.hasUCN()) {
732  SmallString<64> UCNIdentifierBuffer;
733  expandUCNs(UCNIdentifierBuffer, CleanedStr);
734  II = getIdentifierInfo(UCNIdentifierBuffer);
735  } else {
736  II = getIdentifierInfo(CleanedStr);
737  }
738  }
739 
740  // Update the token info (identifier info and appropriate token kind).
741  // FIXME: the raw_identifier may contain leading whitespace which is removed
742  // from the cleaned identifier token. The SourceLocation should be updated to
743  // refer to the non-whitespace character. For instance, the text "\\\nB" (a
744  // line continuation before 'B') is parsed as a single tok::raw_identifier and
745  // is cleaned to tok::identifier "B". After cleaning the token's length is
746  // still 3 and the SourceLocation refers to the location of the backslash.
747  Identifier.setIdentifierInfo(II);
748  Identifier.setKind(II->getTokenID());
749 
750  return II;
751 }
752 
753 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
754  PoisonReasons[II] = DiagID;
755 }
756 
758  assert(Ident__exception_code && Ident__exception_info);
759  assert(Ident___exception_code && Ident___exception_info);
760  Ident__exception_code->setIsPoisoned(Poison);
761  Ident___exception_code->setIsPoisoned(Poison);
762  Ident_GetExceptionCode->setIsPoisoned(Poison);
763  Ident__exception_info->setIsPoisoned(Poison);
764  Ident___exception_info->setIsPoisoned(Poison);
765  Ident_GetExceptionInfo->setIsPoisoned(Poison);
766  Ident__abnormal_termination->setIsPoisoned(Poison);
767  Ident___abnormal_termination->setIsPoisoned(Poison);
768  Ident_AbnormalTermination->setIsPoisoned(Poison);
769 }
770 
772  assert(Identifier.getIdentifierInfo() &&
773  "Can't handle identifiers without identifier info!");
774  llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
775  PoisonReasons.find(Identifier.getIdentifierInfo());
776  if(it == PoisonReasons.end())
777  Diag(Identifier, diag::err_pp_used_poisoned_id);
778  else
779  Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
780 }
781 
782 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
783  assert(II.isOutOfDate() && "not out of date");
785 }
786 
787 /// HandleIdentifier - This callback is invoked when the lexer reads an
788 /// identifier. This callback looks up the identifier in the map and/or
789 /// potentially macro expands it or turns it into a named token (like 'for').
790 ///
791 /// Note that callers of this method are guarded by checking the
792 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
793 /// IdentifierInfo methods that compute these properties will need to change to
794 /// match.
796  assert(Identifier.getIdentifierInfo() &&
797  "Can't handle identifiers without identifier info!");
798 
799  IdentifierInfo &II = *Identifier.getIdentifierInfo();
800 
801  // If the information about this identifier is out of date, update it from
802  // the external source.
803  // We have to treat __VA_ARGS__ in a special way, since it gets
804  // serialized with isPoisoned = true, but our preprocessor may have
805  // unpoisoned it if we're defining a C99 macro.
806  if (II.isOutOfDate()) {
807  bool CurrentIsPoisoned = false;
808  const bool IsSpecialVariadicMacro =
809  &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
810  if (IsSpecialVariadicMacro)
811  CurrentIsPoisoned = II.isPoisoned();
812 
813  updateOutOfDateIdentifier(II);
814  Identifier.setKind(II.getTokenID());
815 
816  if (IsSpecialVariadicMacro)
817  II.setIsPoisoned(CurrentIsPoisoned);
818  }
819 
820  // If this identifier was poisoned, and if it was not produced from a macro
821  // expansion, emit an error.
822  if (II.isPoisoned() && CurPPLexer) {
824  }
825 
826  // If this is a macro to be expanded, do it.
827  if (MacroDefinition MD = getMacroDefinition(&II)) {
828  auto *MI = MD.getMacroInfo();
829  assert(MI && "macro definition with no macro info?");
830  if (!DisableMacroExpansion) {
831  if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
832  // C99 6.10.3p10: If the preprocessing token immediately after the
833  // macro name isn't a '(', this macro should not be expanded.
834  if (!MI->isFunctionLike() || isNextPPTokenLParen())
835  return HandleMacroExpandedIdentifier(Identifier, MD);
836  } else {
837  // C99 6.10.3.4p2 says that a disabled macro may never again be
838  // expanded, even if it's in a context where it could be expanded in the
839  // future.
841  if (MI->isObjectLike() || isNextPPTokenLParen())
842  Diag(Identifier, diag::pp_disabled_macro_expansion);
843  }
844  }
845  }
846 
847  // If this identifier is a keyword in a newer Standard or proposed Standard,
848  // produce a warning. Don't warn if we're not considering macro expansion,
849  // since this identifier might be the name of a macro.
850  // FIXME: This warning is disabled in cases where it shouldn't be, like
851  // "#define constexpr constexpr", "int constexpr;"
852  if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
853  Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
854  << II.getName();
855  // Don't diagnose this keyword again in this translation unit.
856  II.setIsFutureCompatKeyword(false);
857  }
858 
859  // If this is an extension token, diagnose its use.
860  // We avoid diagnosing tokens that originate from macro definitions.
861  // FIXME: This warning is disabled in cases where it shouldn't be,
862  // like "#define TY typeof", "TY(1) x".
863  if (II.isExtensionToken() && !DisableMacroExpansion)
864  Diag(Identifier, diag::ext_token_used);
865 
866  // If this is the 'import' contextual keyword following an '@', note
867  // that the next token indicates a module name.
868  //
869  // Note that we do not treat 'import' as a contextual
870  // keyword when we're in a caching lexer, because caching lexers only get
871  // used in contexts where import declarations are disallowed.
872  //
873  // Likewise if this is the C++ Modules TS import keyword.
874  if (((LastTokenWasAt && II.isModulesImport()) ||
875  Identifier.is(tok::kw_import)) &&
876  !InMacroArgs && !DisableMacroExpansion &&
877  (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
878  CurLexerKind != CLK_CachingLexer) {
879  ModuleImportLoc = Identifier.getLocation();
880  ModuleImportPath.clear();
881  ModuleImportExpectsIdentifier = true;
882  CurLexerKind = CLK_LexAfterModuleImport;
883  }
884  return true;
885 }
886 
887 void Preprocessor::Lex(Token &Result) {
888  ++LexLevel;
889 
890  // We loop here until a lex function returns a token; this avoids recursion.
891  bool ReturnedToken;
892  do {
893  switch (CurLexerKind) {
894  case CLK_Lexer:
895  ReturnedToken = CurLexer->Lex(Result);
896  break;
897  case CLK_TokenLexer:
898  ReturnedToken = CurTokenLexer->Lex(Result);
899  break;
900  case CLK_CachingLexer:
901  CachingLex(Result);
902  ReturnedToken = true;
903  break;
904  case CLK_DependencyDirectivesLexer:
905  ReturnedToken = CurLexer->LexDependencyDirectiveToken(Result);
906  break;
907  case CLK_LexAfterModuleImport:
908  ReturnedToken = LexAfterModuleImport(Result);
909  break;
910  }
911  } while (!ReturnedToken);
912 
913  if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
914  return;
915 
916  if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
917  // Remember the identifier before code completion token.
918  setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
920  // Set IdenfitierInfo to null to avoid confusing code that handles both
921  // identifiers and completion tokens.
922  Result.setIdentifierInfo(nullptr);
923  }
924 
925  // Update ImportSeqState to track our position within a C++20 import-seq
926  // if this token is being produced as a result of phase 4 of translation.
927  // Update TrackGMFState to decide if we are currently in a Global Module
928  // Fragment. GMF state updates should precede ImportSeq ones, since GMF state
929  // depends on the prevailing ImportSeq state in two cases.
930  if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
931  !Result.getFlag(Token::IsReinjected)) {
932  switch (Result.getKind()) {
933  case tok::l_paren: case tok::l_square: case tok::l_brace:
934  ImportSeqState.handleOpenBracket();
935  break;
936  case tok::r_paren: case tok::r_square:
937  ImportSeqState.handleCloseBracket();
938  break;
939  case tok::r_brace:
940  ImportSeqState.handleCloseBrace();
941  break;
942  // This token is injected to represent the translation of '#include "a.h"'
943  // into "import a.h;". Mimic the notional ';'.
944  case tok::annot_module_include:
945  case tok::semi:
946  TrackGMFState.handleSemi();
947  ImportSeqState.handleSemi();
948  break;
949  case tok::header_name:
950  case tok::annot_header_unit:
951  ImportSeqState.handleHeaderName();
952  break;
953  case tok::kw_export:
954  TrackGMFState.handleExport();
955  ImportSeqState.handleExport();
956  break;
957  case tok::identifier:
958  if (Result.getIdentifierInfo()->isModulesImport()) {
959  TrackGMFState.handleImport(ImportSeqState.afterTopLevelSeq());
960  ImportSeqState.handleImport();
961  if (ImportSeqState.afterImportSeq()) {
962  ModuleImportLoc = Result.getLocation();
963  ModuleImportPath.clear();
964  ModuleImportExpectsIdentifier = true;
965  CurLexerKind = CLK_LexAfterModuleImport;
966  }
967  break;
968  } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
969  TrackGMFState.handleModule(ImportSeqState.afterTopLevelSeq());
970  break;
971  }
972  [[fallthrough]];
973  default:
974  TrackGMFState.handleMisc();
975  ImportSeqState.handleMisc();
976  break;
977  }
978  }
979 
980  LastTokenWasAt = Result.is(tok::at);
981  --LexLevel;
982 
983  if ((LexLevel == 0 || PreprocessToken) &&
984  !Result.getFlag(Token::IsReinjected)) {
985  if (LexLevel == 0)
986  ++TokenCount;
987  if (OnToken)
988  OnToken(Result);
989  }
990 }
991 
992 /// Lex a header-name token (including one formed from header-name-tokens if
993 /// \p AllowConcatenation is \c true).
994 ///
995 /// \param FilenameTok Filled in with the next token. On success, this will
996 /// be either a header_name token. On failure, it will be whatever other
997 /// token was found instead.
998 /// \param AllowMacroExpansion If \c true, allow the header name to be formed
999 /// by macro expansion (concatenating tokens as necessary if the first
1000 /// token is a '<').
1001 /// \return \c true if we reached EOD or EOF while looking for a > token in
1002 /// a concatenated header name and diagnosed it. \c false otherwise.
1003 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1004  // Lex using header-name tokenization rules if tokens are being lexed from
1005  // a file. Just grab a token normally if we're in a macro expansion.
1006  if (CurPPLexer)
1007  CurPPLexer->LexIncludeFilename(FilenameTok);
1008  else
1009  Lex(FilenameTok);
1010 
1011  // This could be a <foo/bar.h> file coming from a macro expansion. In this
1012  // case, glue the tokens together into an angle_string_literal token.
1013  SmallString<128> FilenameBuffer;
1014  if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1015  bool StartOfLine = FilenameTok.isAtStartOfLine();
1016  bool LeadingSpace = FilenameTok.hasLeadingSpace();
1017  bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1018 
1019  SourceLocation Start = FilenameTok.getLocation();
1021  FilenameBuffer.push_back('<');
1022 
1023  // Consume tokens until we find a '>'.
1024  // FIXME: A header-name could be formed starting or ending with an
1025  // alternative token. It's not clear whether that's ill-formed in all
1026  // cases.
1027  while (FilenameTok.isNot(tok::greater)) {
1028  Lex(FilenameTok);
1029  if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1030  Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1031  Diag(Start, diag::note_matching) << tok::less;
1032  return true;
1033  }
1034 
1035  End = FilenameTok.getLocation();
1036 
1037  // FIXME: Provide code completion for #includes.
1038  if (FilenameTok.is(tok::code_completion)) {
1040  Lex(FilenameTok);
1041  continue;
1042  }
1043 
1044  // Append the spelling of this token to the buffer. If there was a space
1045  // before it, add it now.
1046  if (FilenameTok.hasLeadingSpace())
1047  FilenameBuffer.push_back(' ');
1048 
1049  // Get the spelling of the token, directly into FilenameBuffer if
1050  // possible.
1051  size_t PreAppendSize = FilenameBuffer.size();
1052  FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1053 
1054  const char *BufPtr = &FilenameBuffer[PreAppendSize];
1055  unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1056 
1057  // If the token was spelled somewhere else, copy it into FilenameBuffer.
1058  if (BufPtr != &FilenameBuffer[PreAppendSize])
1059  memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1060 
1061  // Resize FilenameBuffer to the correct size.
1062  if (FilenameTok.getLength() != ActualLen)
1063  FilenameBuffer.resize(PreAppendSize + ActualLen);
1064  }
1065 
1066  FilenameTok.startToken();
1067  FilenameTok.setKind(tok::header_name);
1068  FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1069  FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1070  FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1071  CreateString(FilenameBuffer, FilenameTok, Start, End);
1072  } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1073  // Convert a string-literal token of the form " h-char-sequence "
1074  // (produced by macro expansion) into a header-name token.
1075  //
1076  // The rules for header-names don't quite match the rules for
1077  // string-literals, but all the places where they differ result in
1078  // undefined behavior, so we can and do treat them the same.
1079  //
1080  // A string-literal with a prefix or suffix is not translated into a
1081  // header-name. This could theoretically be observable via the C++20
1082  // context-sensitive header-name formation rules.
1083  StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1084  if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1085  FilenameTok.setKind(tok::header_name);
1086  }
1087 
1088  return false;
1089 }
1090 
1091 /// Collect the tokens of a C++20 pp-import-suffix.
1093  // FIXME: For error recovery, consider recognizing attribute syntax here
1094  // and terminating / diagnosing a missing semicolon if we find anything
1095  // else? (Can we leave that to the parser?)
1096  unsigned BracketDepth = 0;
1097  while (true) {
1098  Toks.emplace_back();
1099  Lex(Toks.back());
1100 
1101  switch (Toks.back().getKind()) {
1102  case tok::l_paren: case tok::l_square: case tok::l_brace:
1103  ++BracketDepth;
1104  break;
1105 
1106  case tok::r_paren: case tok::r_square: case tok::r_brace:
1107  if (BracketDepth == 0)
1108  return;
1109  --BracketDepth;
1110  break;
1111 
1112  case tok::semi:
1113  if (BracketDepth == 0)
1114  return;
1115  break;
1116 
1117  case tok::eof:
1118  return;
1119 
1120  default:
1121  break;
1122  }
1123  }
1124 }
1125 
1126 
1127 /// Lex a token following the 'import' contextual keyword.
1128 ///
1129 /// pp-import: [C++20]
1130 /// import header-name pp-import-suffix[opt] ;
1131 /// import header-name-tokens pp-import-suffix[opt] ;
1132 /// [ObjC] @ import module-name ;
1133 /// [Clang] import module-name ;
1134 ///
1135 /// header-name-tokens:
1136 /// string-literal
1137 /// < [any sequence of preprocessing-tokens other than >] >
1138 ///
1139 /// module-name:
1140 /// module-name-qualifier[opt] identifier
1141 ///
1142 /// module-name-qualifier
1143 /// module-name-qualifier[opt] identifier .
1144 ///
1145 /// We respond to a pp-import by importing macros from the named module.
1147  // Figure out what kind of lexer we actually have.
1149 
1150  // Lex the next token. The header-name lexing rules are used at the start of
1151  // a pp-import.
1152  //
1153  // For now, we only support header-name imports in C++20 mode.
1154  // FIXME: Should we allow this in all language modes that support an import
1155  // declaration as an extension?
1156  if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
1157  if (LexHeaderName(Result))
1158  return true;
1159  } else {
1160  Lex(Result);
1161  }
1162 
1163  // Allocate a holding buffer for a sequence of tokens and introduce it into
1164  // the token stream.
1165  auto EnterTokens = [this](ArrayRef<Token> Toks) {
1166  auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1167  std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1168  EnterTokenStream(std::move(ToksCopy), Toks.size(),
1169  /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
1170  };
1171 
1172  // Check for a header-name.
1173  SmallVector<Token, 32> Suffix;
1174  if (Result.is(tok::header_name)) {
1175  // Enter the header-name token into the token stream; a Lex action cannot
1176  // both return a token and cache tokens (doing so would corrupt the token
1177  // cache if the call to Lex comes from CachingLex / PeekAhead).
1178  Suffix.push_back(Result);
1179 
1180  // Consume the pp-import-suffix and expand any macros in it now. We'll add
1181  // it back into the token stream later.
1182  CollectPpImportSuffix(Suffix);
1183  if (Suffix.back().isNot(tok::semi)) {
1184  // This is not a pp-import after all.
1185  EnterTokens(Suffix);
1186  return false;
1187  }
1188 
1189  // C++2a [cpp.module]p1:
1190  // The ';' preprocessing-token terminating a pp-import shall not have
1191  // been produced by macro replacement.
1192  SourceLocation SemiLoc = Suffix.back().getLocation();
1193  if (SemiLoc.isMacroID())
1194  Diag(SemiLoc, diag::err_header_import_semi_in_macro);
1195 
1196  // Reconstitute the import token.
1197  Token ImportTok;
1198  ImportTok.startToken();
1199  ImportTok.setKind(tok::kw_import);
1200  ImportTok.setLocation(ModuleImportLoc);
1201  ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
1202  ImportTok.setLength(6);
1203 
1204  auto Action = HandleHeaderIncludeOrImport(
1205  /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
1206  switch (Action.Kind) {
1207  case ImportAction::None:
1208  break;
1209 
1210  case ImportAction::ModuleBegin:
1211  // Let the parser know we're textually entering the module.
1212  Suffix.emplace_back();
1213  Suffix.back().startToken();
1214  Suffix.back().setKind(tok::annot_module_begin);
1215  Suffix.back().setLocation(SemiLoc);
1216  Suffix.back().setAnnotationEndLoc(SemiLoc);
1217  Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1218  [[fallthrough]];
1219 
1220  case ImportAction::ModuleImport:
1221  case ImportAction::HeaderUnitImport:
1222  case ImportAction::SkippedModuleImport:
1223  // We chose to import (or textually enter) the file. Convert the
1224  // header-name token into a header unit annotation token.
1225  Suffix[0].setKind(tok::annot_header_unit);
1226  Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
1227  Suffix[0].setAnnotationValue(Action.ModuleForHeader);
1228  // FIXME: Call the moduleImport callback?
1229  break;
1230  case ImportAction::Failure:
1231  assert(TheModuleLoader.HadFatalFailure &&
1232  "This should be an early exit only to a fatal error");
1233  Result.setKind(tok::eof);
1234  CurLexer->cutOffLexing();
1235  EnterTokens(Suffix);
1236  return true;
1237  }
1238 
1239  EnterTokens(Suffix);
1240  return false;
1241  }
1242 
1243  // The token sequence
1244  //
1245  // import identifier (. identifier)*
1246  //
1247  // indicates a module import directive. We already saw the 'import'
1248  // contextual keyword, so now we're looking for the identifiers.
1249  if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
1250  // We expected to see an identifier here, and we did; continue handling
1251  // identifiers.
1252  ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
1253  Result.getLocation()));
1254  ModuleImportExpectsIdentifier = false;
1255  CurLexerKind = CLK_LexAfterModuleImport;
1256  return true;
1257  }
1258 
1259  // If we're expecting a '.' or a ';', and we got a '.', then wait until we
1260  // see the next identifier. (We can also see a '[[' that begins an
1261  // attribute-specifier-seq here under the C++ Modules TS.)
1262  if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
1263  ModuleImportExpectsIdentifier = true;
1264  CurLexerKind = CLK_LexAfterModuleImport;
1265  return true;
1266  }
1267 
1268  // If we didn't recognize a module name at all, this is not a (valid) import.
1269  if (ModuleImportPath.empty() || Result.is(tok::eof))
1270  return true;
1271 
1272  // Consume the pp-import-suffix and expand any macros in it now, if we're not
1273  // at the semicolon already.
1274  SourceLocation SemiLoc = Result.getLocation();
1275  if (Result.isNot(tok::semi)) {
1276  Suffix.push_back(Result);
1277  CollectPpImportSuffix(Suffix);
1278  if (Suffix.back().isNot(tok::semi)) {
1279  // This is not an import after all.
1280  EnterTokens(Suffix);
1281  return false;
1282  }
1283  SemiLoc = Suffix.back().getLocation();
1284  }
1285 
1286  // Under the Modules TS, the dot is just part of the module name, and not
1287  // a real hierarchy separator. Flatten such module names now.
1288  //
1289  // FIXME: Is this the right level to be performing this transformation?
1290  std::string FlatModuleName;
1291  if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
1292  for (auto &Piece : ModuleImportPath) {
1293  if (!FlatModuleName.empty())
1294  FlatModuleName += ".";
1295  FlatModuleName += Piece.first->getName();
1296  }
1297  SourceLocation FirstPathLoc = ModuleImportPath[0].second;
1298  ModuleImportPath.clear();
1299  ModuleImportPath.push_back(
1300  std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
1301  }
1302 
1303  Module *Imported = nullptr;
1304  if (getLangOpts().Modules) {
1305  Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1306  ModuleImportPath,
1308  /*IsInclusionDirective=*/false);
1309  if (Imported)
1310  makeModuleVisible(Imported, SemiLoc);
1311  }
1312  if (Callbacks)
1313  Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
1314 
1315  if (!Suffix.empty()) {
1316  EnterTokens(Suffix);
1317  return false;
1318  }
1319  return true;
1320 }
1321 
1323  CurSubmoduleState->VisibleModules.setVisible(
1324  M, Loc, [](Module *) {},
1325  [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1326  // FIXME: Include the path in the diagnostic.
1327  // FIXME: Include the import location for the conflicting module.
1328  Diag(ModuleImportLoc, diag::warn_module_conflict)
1329  << Path[0]->getFullModuleName()
1330  << Conflict->getFullModuleName()
1331  << Message;
1332  });
1333 
1334  // Add this module to the imports list of the currently-built submodule.
1335  if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1336  BuildingSubmoduleStack.back().M->Imports.insert(M);
1337 }
1338 
1340  const char *DiagnosticTag,
1341  bool AllowMacroExpansion) {
1342  // We need at least one string literal.
1343  if (Result.isNot(tok::string_literal)) {
1344  Diag(Result, diag::err_expected_string_literal)
1345  << /*Source='in...'*/0 << DiagnosticTag;
1346  return false;
1347  }
1348 
1349  // Lex string literal tokens, optionally with macro expansion.
1350  SmallVector<Token, 4> StrToks;
1351  do {
1352  StrToks.push_back(Result);
1353 
1354  if (Result.hasUDSuffix())
1355  Diag(Result, diag::err_invalid_string_udl);
1356 
1357  if (AllowMacroExpansion)
1358  Lex(Result);
1359  else
1360  LexUnexpandedToken(Result);
1361  } while (Result.is(tok::string_literal));
1362 
1363  // Concatenate and parse the strings.
1364  StringLiteralParser Literal(StrToks, *this);
1365  assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1366 
1367  if (Literal.hadError)
1368  return false;
1369 
1370  if (Literal.Pascal) {
1371  Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1372  << /*Source='in...'*/0 << DiagnosticTag;
1373  return false;
1374  }
1375 
1376  String = std::string(Literal.GetString());
1377  return true;
1378 }
1379 
1381  assert(Tok.is(tok::numeric_constant));
1382  SmallString<8> IntegerBuffer;
1383  bool NumberInvalid = false;
1384  StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1385  if (NumberInvalid)
1386  return false;
1389  getDiagnostics());
1390  if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1391  return false;
1392  llvm::APInt APVal(64, 0);
1393  if (Literal.GetIntegerValue(APVal))
1394  return false;
1395  Lex(Tok);
1396  Value = APVal.getLimitedValue();
1397  return true;
1398 }
1399 
1401  assert(Handler && "NULL comment handler");
1402  assert(!llvm::is_contained(CommentHandlers, Handler) &&
1403  "Comment handler already registered");
1404  CommentHandlers.push_back(Handler);
1405 }
1406 
1408  std::vector<CommentHandler *>::iterator Pos =
1409  llvm::find(CommentHandlers, Handler);
1410  assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1411  CommentHandlers.erase(Pos);
1412 }
1413 
1415  bool AnyPendingTokens = false;
1416  for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1417  HEnd = CommentHandlers.end();
1418  H != HEnd; ++H) {
1419  if ((*H)->HandleComment(*this, Comment))
1420  AnyPendingTokens = true;
1421  }
1422  if (!AnyPendingTokens || getCommentRetentionState())
1423  return false;
1424  Lex(result);
1425  return true;
1426 }
1427 
1428 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1429  const MacroAnnotations &A =
1430  getMacroAnnotations(Identifier.getIdentifierInfo());
1431  assert(A.DeprecationInfo &&
1432  "Macro deprecation warning without recorded annotation!");
1433  const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1434  if (Info.Message.empty())
1435  Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1436  << Identifier.getIdentifierInfo() << 0;
1437  else
1438  Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1439  << Identifier.getIdentifierInfo() << 1 << Info.Message;
1440  Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1441 }
1442 
1443 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1444  const MacroAnnotations &A =
1445  getMacroAnnotations(Identifier.getIdentifierInfo());
1446  assert(A.RestrictExpansionInfo &&
1447  "Macro restricted expansion warning without recorded annotation!");
1448  const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1449  if (Info.Message.empty())
1450  Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1451  << Identifier.getIdentifierInfo() << 0;
1452  else
1453  Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1454  << Identifier.getIdentifierInfo() << 1 << Info.Message;
1455  Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1456 }
1457 
1458 void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1459  bool IsUndef) const {
1460  const MacroAnnotations &A =
1461  getMacroAnnotations(Identifier.getIdentifierInfo());
1462  assert(A.FinalAnnotationLoc &&
1463  "Final macro warning without recorded annotation!");
1464 
1465  Diag(Identifier, diag::warn_pragma_final_macro)
1466  << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1467  Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1468 }
1469 
1470 ModuleLoader::~ModuleLoader() = default;
1471 
1473 
1475 
1477 
1479  if (Record)
1480  return;
1481 
1482  Record = new PreprocessingRecord(getSourceManager());
1483  addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1484 }
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:170
clang::MacroDirective::DefInfo::getLocation
SourceLocation getLocation() const
Definition: MacroInfo.h:486
clang::MacroInfo::getNumTokens
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:236
PreprocessorLexer.h
Builtins.h
clang::MacroInfo::getReplacementToken
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:238
clang::Preprocessor::CreateString
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
Definition: Preprocessor.cpp:494
clang::Token::IsReinjected
@ IsReinjected
Definition: Token.h:87
clang::Preprocessor::PrintStats
void PrintStats()
Definition: Preprocessor.cpp:279
clang::Preprocessor::FinalizeForModelFile
void FinalizeForModelFile()
Cleanup after model file parsing.
Definition: Preprocessor.cpp:234
clang::Token::hasUCN
bool hasUCN() const
Returns true if this token contains a universal character name.
Definition: Token.h:295
clang::Token::hasLeadingSpace
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:271
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::Preprocessor::FinishLexStringLiteral
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
Definition: Preprocessor.cpp:1339
clang::Preprocessor::setCodeCompletionReached
void setCodeCompletionReached()
Note that we hit the code-completion point.
Definition: Preprocessor.h:1834
clang::Preprocessor::getMacroDefinition
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
Definition: Preprocessor.h:1225
clang::Decl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:428
clang::DeclaratorContext::File
@ File
clang::Preprocessor::SetCodeCompletionPoint
bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
Definition: Preprocessor.cpp:400
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::Preprocessor::getLastMacroWithSpelling
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
Definition: Preprocessor.cpp:362
clang::Preprocessor::setCodeCompletionTokenRange
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
Definition: Preprocessor.h:1459
clang::Preprocessor::Lex
void Lex(Token &Result)
Lex the next token for this preprocessor.
Definition: Preprocessor.cpp:887
clang::Preprocessor::HandleIdentifier
bool HandleIdentifier(Token &Identifier)
Callback invoked when the lexer reads an identifier and has filled in the tokens IdentifierInfo membe...
Definition: Preprocessor.cpp:795
clang::MacroInfo::isObjectLike
bool isObjectLike() const
Definition: MacroInfo.h:203
clang::Preprocessor::macro_iterator
MacroMap::const_iterator macro_iterator
Definition: Preprocessor.h:1326
clang::MacroDefinition
A description of the current definition of a macro.
Definition: MacroInfo.h:588
clang::Preprocessor::LexHeaderName
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
Definition: Preprocessor.cpp:1003
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Preprocessor::TUKind
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Preprocessor.h:291
clang::MacroInfo::tokens_begin
const_tokens_iterator tokens_begin() const
Definition: MacroInfo.h:245
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::Preprocessor::getCommentRetentionState
bool getCommentRetentionState() const
Definition: Preprocessor.h:1118
TargetInfo.h
clang::MultiVersionKind::Target
@ Target
clang::Token::isExpandDisabled
bool isExpandDisabled() const
Return true if this identifier token should never be expanded in the future, due to C99 6....
Definition: Token.h:275
clang::PreprocessorLexer::setConditionalLevels
void setConditionalLevels(ArrayRef< PPConditionalInfo > CL)
Definition: PreprocessorLexer.h:175
clang::Token::getIdentifierInfo
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:178
clang::MacroArgs
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition: MacroArgs.h:29
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:205
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
clang::PreprocessingRecord
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
Definition: PreprocessingRecord.h:306
Module.h
clang::Token::isAtStartOfLine
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:267
clang::IdentifierInfo::isOutOfDate
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
Definition: IdentifierTable.h:415
clang::Preprocessor::CodeCompleteIncludedFile
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Hook used by the lexer to invoke the "included file" code completion point.
Definition: Preprocessor.cpp:456
llvm::Optional< llvm::MemoryBufferRef >
clang::Preprocessor::macro_end
macro_iterator macro_end(bool IncludeExternalMacros=true) const
Definition: Preprocessor.cpp:345
clang::ModuleLoader::HadFatalFailure
bool HadFatalFailure
Definition: ModuleLoader.h:162
clang::MacroInfo
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
SourceManager.h
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:187
clang::MacroDirective::DefInfo::getMacroInfo
MacroInfo * getMacroInfo()
Definition: MacroInfo.h:492
Identifier
StringRef Identifier
Definition: Format.cpp:2596
clang::IdentifierInfo::getTokenID
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
Definition: IdentifierTable.h:262
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
LiteralSupport.h
clang::CommentHandler
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Definition: Preprocessor.h:2704
End
SourceLocation End
Definition: USRLocFinder.cpp:167
TokenLexer.h
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:1080
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:627
clang::Preprocessor::getLangOpts
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:1073
Preprocessor.h
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:223
clang::ModuleLoader::loadModule
virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective)=0
Attempt to load the given module.
clang::Preprocessor::creatingPCHWithPragmaHdrStop
bool creatingPCHWithPragmaHdrStop()
True if creating a PCH with a #pragma hdrstop.
Definition: Preprocessor.cpp:632
clang::TU_Prefix
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:908
uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:24
clang::Preprocessor::usingPCHWithThroughHeader
bool usingPCHWithThroughHeader()
True if using a PCH with a through header.
Definition: Preprocessor.cpp:627
clang::PreprocessorLexer::LexIncludeFilename
void LexIncludeFilename(Token &FilenameTok)
Lex a token, producing a header-name token if possible.
Definition: PreprocessorLexer.cpp:32
clang::dataflow::Literal
uint32_t Literal
Literals are represented as positive integers.
Definition: WatchedLiteralsSolver.cpp:55
clang::Preprocessor::getCurrentModuleImplementation
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
Definition: Preprocessor.cpp:537
clang::CodeCompletionHandler::CodeCompleteIncludedFile
virtual void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Callback invoked when performing code completion inside the filename part of an include directive.
Definition: CodeCompletionHandler.h:67
clang::SourceLocation::print
void print(raw_ostream &OS, const SourceManager &SM) const
Definition: SourceLocation.cpp:62
clang::Preprocessor::SetPoisonReason
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
Definition: Preprocessor.cpp:753
clang::Token::setRawIdentifierData
void setRawIdentifierData(const char *Ptr)
Definition: Token.h:208
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::Module::Hidden
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:335
clang::Preprocessor::EnterSourceFile
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
Definition: PPLexerChange.cpp:68
clang::Preprocessor::EndSourceFile
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
Definition: Preprocessor.cpp:705
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:435
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
Pragma.h
clang::Preprocessor::InitializeForModelFile
void InitializeForModelFile()
Initialize the preprocessor to parse a model file.
Definition: Preprocessor.cpp:222
clang::Preprocessor::addCommentHandler
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
Definition: Preprocessor.cpp:1400
clang::Token::setFlagValue
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition: Token.h:258
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:92
clang::IdentifierInfo::setIsFutureCompatKeyword
void setIsFutureCompatKeyword(bool Val)
Definition: IdentifierTable.h:336
clang::ExternalPreprocessorSource::~ExternalPreprocessorSource
virtual ~ExternalPreprocessorSource()
clang::SourceManager::getMainFileID
FileID getMainFileID() const
Returns the FileID of the main source file.
Definition: SourceManager.h:841
clang::FileID::isValid
bool isValid() const
Definition: SourceLocation.h:44
clang::IdentifierInfo::setIsPoisoned
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
Definition: IdentifierTable.h:346
LangOptions.h
clang::Preprocessor::isPCHThroughHeader
bool isPCHThroughHeader(const FileEntry *FE)
Returns true if the FileEntry is the PCH through header.
Definition: Preprocessor.cpp:616
clang::Preprocessor::setTUFPEvalMethod
void setTUFPEvalMethod(LangOptions::FPEvalMethodKind Val)
Definition: Preprocessor.h:2225
LexDiagnostic.h
clang::Preprocessor::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Definition: Preprocessor.h:1906
ModuleLoader.h
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:97
clang::HeaderSearch::lookupModule
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
Definition: HeaderSearch.cpp:278
clang::Preprocessor::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:1074
clang::Preprocessor::createPreprocessingRecord
void createPreprocessingRecord()
Create a new preprocessing record, which will keep track of all macro expansions, macro definitions,...
Definition: Preprocessor.cpp:1478
clang::Token::DisableExpand
@ DisableExpand
Definition: Token.h:77
IdentifierTable.h
clang::tok::getTokenName
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
Definition: TokenKinds.cpp:24
llvm::SmallString
Definition: LLVM.h:37
clang::Token::needsCleaning
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
Definition: Token.h:284
clang::Token::LeadingEmptyMacro
@ LeadingEmptyMacro
Definition: Token.h:79
clang::Preprocessor::LexAfterModuleImport
bool LexAfterModuleImport(Token &Result)
Lex a token following the 'import' contextual keyword.
Definition: Preprocessor.cpp:1146
clang::CommentHandler::~CommentHandler
virtual ~CommentHandler()
clang::ExternalPreprocessorSource::ReadDefinedMacros
virtual void ReadDefinedMacros()=0
Read the set of macros defined by this external macro source.
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:80
clang::Preprocessor::EnterMainSourceFile
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
Definition: Preprocessor.cpp:550
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:349
clang::Preprocessor::SplitToken
SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length)
Split the first Length characters out of the token starting at TokLoc and return a location pointing ...
Definition: Preprocessor.cpp:514
clang::Token::isLiteral
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
Definition: Token.h:114
clang::Token::getLength
unsigned getLength() const
Definition: Token.h:128
clang::SourceManager::isBeforeInTranslationUnit
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
Definition: SourceManager.cpp:2017
clang::Token::LeadingSpace
@ LeadingSpace
Definition: Token.h:75
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:1077
clang::LangOptions::FEM_UnsetOnCommandLine
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:294
clang::Preprocessor::HandleComment
bool HandleComment(Token &result, SourceRange Comment)
Definition: Preprocessor.cpp:1414
clang::LangOptions::FEM_Indeterminable
@ FEM_Indeterminable
The evaluation method cannot be determined or is inconsistent for this target.
Definition: LangOptions.h:283
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:1921
MacroArgs.h
clang::Preprocessor::PoisonSEHIdentifiers
void PoisonSEHIdentifiers(bool Poison=true)
Definition: Preprocessor.cpp:757
clang::expandUCNs
void expandUCNs(SmallVectorImpl< char > &Buf, StringRef Input)
Copy characters from Input to Buf, expanding any UCNs.
Definition: LiteralSupport.cpp:331
clang::Preprocessor::CollectPpImportSuffix
void CollectPpImportSuffix(SmallVectorImpl< Token > &Toks)
Collect the tokens of a C++20 pp-import-suffix.
Definition: Preprocessor.cpp:1092
FileSystemStatCache.h
SourceLocation.h
clang::Preprocessor::SkipTokensWhileUsingPCH
void SkipTokensWhileUsingPCH()
Skip tokens until after the include of the through header or until after a #pragma hdrstop.
Definition: Preprocessor.cpp:645
clang::Preprocessor::getTotalMemory
size_t getTotalMemory() const
Definition: Preprocessor.cpp:332
clang::Preprocessor::CodeCompleteNaturalLanguage
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
Definition: Preprocessor.cpp:463
clang::Token::setLiteralData
void setLiteralData(const char *Ptr)
Definition: Token.h:220
clang::SourceManager::getMemoryBufferForFileOrNone
llvm::Optional< llvm::MemoryBufferRef > getMemoryBufferForFileOrNone(const FileEntry *File)
Retrieve the memory buffer associated with the given file.
Definition: SourceManager.cpp:682
clang::ScratchBuffer
ScratchBuffer - This class exposes a simple interface for the dynamic construction of tokens.
Definition: ScratchBuffer.h:24
clang::Preprocessor::DumpLocation
void DumpLocation(SourceLocation Loc) const
Definition: Preprocessor.cpp:266
MacroDefinitionEquals
static bool MacroDefinitionEquals(const MacroInfo *MI, ArrayRef< TokenValue > Tokens)
Compares macro tokens with a specified token value sequence.
Definition: Preprocessor.cpp:356
clang::Preprocessor::usingPCHWithPragmaHdrStop
bool usingPCHWithPragmaHdrStop()
True if using a PCH with a #pragma hdrstop.
Definition: Preprocessor.cpp:636
clang::IdentifierInfo::isPoisoned
bool isPoisoned() const
Return true if this token has been poisoned.
Definition: IdentifierTable.h:355
PreprocessingRecord.h
llvm::ArrayRef
Definition: LLVM.h:34
Lexer.h
Value
Value
Definition: UninitializedValues.cpp:102
clang::Preprocessor::setCodeCompletionIdentifierInfo
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
Definition: Preprocessor.h:1453
clang::SourceManager::getCharacterData
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
Definition: SourceManager.cpp:1155
HeaderSearch.h
LLVM.h
clang::Preprocessor::DumpToken
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
Definition: Preprocessor.cpp:240
clang::Token::StartOfLine
@ StartOfLine
Definition: Token.h:73
clang::Preprocessor::setCurrentFPEvalMethod
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
Definition: Preprocessor.h:2214
clang::NumericLiteralParser
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Definition: LiteralSupport.h:42
clang::Preprocessor::getCurrentModule
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
Definition: Preprocessor.cpp:530
clang::ModuleLoader
Abstract interface for a module loader.
Definition: ModuleLoader.h:82
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:85
clang::SourceManager::overrideFileContents
void overrideFileContents(const FileEntry *SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
Definition: SourceManager.h:952
clang::IdentifierTable::AddKeywords
void AddKeywords(const LangOptions &LangOpts)
Populate the identifier table with info about the language keywords for the language specified by Lan...
Definition: IdentifierTable.cpp:284
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:125
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:78
CodeCompletionHandler.h
clang::Token::isAnnotation
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:119
clang::Preprocessor::removeCommentHandler
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
Definition: Preprocessor.cpp:1407
clang::SourceManager::isLoadedFileID
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
Definition: SourceManager.h:1751
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:133
std
Definition: Format.h:4321
clang::TranslationUnitKind
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:902
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:196
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang
Definition: CalledOnceCheck.h:17
clang::Preprocessor::addPPCallbacks
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
Definition: Preprocessor.h:1171
clang::SourceManager::createFileID
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
Definition: SourceManager.cpp:532
clang::ExternalPreprocessorSource::updateOutOfDateIdentifier
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)=0
Update an out-of-date identifier.
clang::Preprocessor::markIncluded
bool markIncluded(const FileEntry *File)
Mark the file as included.
Definition: Preprocessor.h:1358
clang::CodeCompletionHandler::CodeCompleteNaturalLanguage
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
Definition: CodeCompletionHandler.h:72
clang::Preprocessor::creatingPCHWithThroughHeader
bool creatingPCHWithThroughHeader()
True if creating a PCH with a through header.
Definition: Preprocessor.cpp:622
clang::Preprocessor::LookUpIdentifierInfo
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
Definition: Preprocessor.cpp:718
clang::PragmaHandlerRegistry
llvm::Registry< PragmaHandler > PragmaHandlerRegistry
Registry of pragma handlers added by plugins.
Definition: Preprocessor.h:2724
MacroInfo.h
clang::Preprocessor::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:1070
clang::Preprocessor::Preprocessor
Preprocessor(std::shared_ptr< PreprocessorOptions > PPOpts, DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup=nullptr, bool OwnsHeaderSearch=false, TranslationUnitKind TUKind=TU_Complete)
Definition: Preprocessor.cpp:78
clang::EmptylineHandler::~EmptylineHandler
virtual ~EmptylineHandler()
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::Token::setLength
void setLength(unsigned Len)
Definition: Token.h:134
clang::FileID::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:45
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1035
clang::Preprocessor::LookupFile
Optional< FileEntryRef > LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
Definition: PPDirectives.cpp:948
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:93
clang::IdentifierInfoLookup
Provides lookups to, and iteration over, IdentiferInfo objects.
Definition: IdentifierTable.h:535
clang::Preprocessor::makeModuleVisible
void makeModuleVisible(Module *M, SourceLocation Loc)
Definition: Preprocessor.cpp:1322
clang::Preprocessor::recomputeCurLexerKind
void recomputeCurLexerKind()
Recompute the current lexer kind based on the CurLexer/ CurTokenLexer pointers.
Definition: Preprocessor.cpp:389
clang::Preprocessor::DumpMacro
void DumpMacro(const MacroInfo &MI) const
Definition: Preprocessor.cpp:270
clang::IdentifierInfo::isModulesImport
bool isModulesImport() const
Determine whether this is the contextual keyword import.
Definition: IdentifierTable.h:428
clang::IdentifierInfo::isExtensionToken
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
Definition: IdentifierTable.h:321
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:99
clang::IdentifierInfo::isFutureCompatKeyword
bool isFutureCompatKeyword() const
is/setIsFutureCompatKeyword - Initialize information about whether or not this language token is a ke...
Definition: IdentifierTable.h:335
ScratchBuffer.h
clang::CodeCompletionHandler::~CodeCompletionHandler
virtual ~CodeCompletionHandler()
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
llvm::SmallVectorImpl< char >
FileManager.h
clang::PragmaNamespace
PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, allowing hierarchical pragm...
Definition: Pragma.h:96
clang::Preprocessor::LexUnexpandedToken
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
Definition: Preprocessor.h:1639
true
#define true
Definition: stdbool.h:21
PreprocessorOptions.h
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::Preprocessor::HandlePoisonedIdentifier
void HandlePoisonedIdentifier(Token &Identifier)
Display reason for poisoned identifier.
Definition: Preprocessor.cpp:771
clang::Preprocessor::getHeaderSearchInfo
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:1078
Token.h
clang::MacroDirective::DefInfo
Definition: MacroInfo.h:362
clang::StringLiteralParser
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Definition: LiteralSupport.h:218
clang::Preprocessor::getExternalSource
ExternalPreprocessorSource * getExternalSource() const
Definition: Preprocessor.h:1090
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:432
clang::Preprocessor::getMacroAnnotations
const MacroAnnotations & getMacroAnnotations(const IdentifierInfo *II) const
Definition: Preprocessor.h:2679
clang::Preprocessor::~Preprocessor
~Preprocessor()
Definition: Preprocessor.cpp:163
clang::Preprocessor::getPredefinesFileID
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
Definition: Preprocessor.h:1163
clang::HeaderSearch::setTarget
void setTarget(const TargetInfo &Target)
Set the target information for the header search, if not already known.
Definition: HeaderSearch.cpp:724
clang::SourceManager::createExpansionLoc
SourceLocation createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned Length, bool ExpansionIsTokenRange=true, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Creates an expansion SLocEntry for a macro use.
Definition: SourceManager.cpp:639
clang::ModuleMacro
Represents a macro directive exported by a module.
Definition: MacroInfo.h:512
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1390
clang::Preprocessor::macro_begin
macro_iterator macro_begin(bool IncludeExternalMacros=true) const
Definition: Preprocessor.cpp:318
clang::Preprocessor::parseSimpleIntegerLiteral
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
Definition: Preprocessor.cpp:1380
ExternalPreprocessorSource.h
clang::Preprocessor::Initialize
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
Definition: Preprocessor.cpp:189
clang::ModuleLoader::~ModuleLoader
virtual ~ModuleLoader()
clang::Token::hasLeadingEmptyMacro
bool hasLeadingEmptyMacro() const
Return true if this token has an empty macro before it.
Definition: Token.h:288