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