Preprocessor.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. //===- Preprocess.cpp - C Language Family Preprocessor Implementation -----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Preprocessor interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Options to support:
  15. // -H - Print the name of each header file used.
  16. // -d[DNI] - Dump various things.
  17. // -fworking-directory - #line's with preprocessor's working dir.
  18. // -fpreprocessed
  19. // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
  20. // -W*
  21. // -w
  22. //
  23. // Messages to emit:
  24. // "Multiple include guards may be useful for:\n"
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Basic/FileManager.h"
  29. #include "clang/Basic/FileSystemStatCache.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/LangOptions.h"
  33. #include "clang/Basic/Module.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Lex/CodeCompletionHandler.h"
  38. #include "clang/Lex/ExternalPreprocessorSource.h"
  39. #include "clang/Lex/HeaderSearch.h"
  40. #include "clang/Lex/LexDiagnostic.h"
  41. #include "clang/Lex/Lexer.h"
  42. #include "clang/Lex/LiteralSupport.h"
  43. #include "clang/Lex/MacroArgs.h"
  44. #include "clang/Lex/MacroInfo.h"
  45. #include "clang/Lex/ModuleLoader.h"
  46. #include "clang/Lex/PTHLexer.h"
  47. #include "clang/Lex/PTHManager.h"
  48. #include "clang/Lex/Pragma.h"
  49. #include "clang/Lex/PreprocessingRecord.h"
  50. #include "clang/Lex/PreprocessorLexer.h"
  51. #include "clang/Lex/PreprocessorOptions.h"
  52. #include "clang/Lex/ScratchBuffer.h"
  53. #include "clang/Lex/Token.h"
  54. #include "clang/Lex/TokenLexer.h"
  55. #include "llvm/ADT/APInt.h"
  56. #include "llvm/ADT/ArrayRef.h"
  57. #include "llvm/ADT/DenseMap.h"
  58. #include "llvm/ADT/SmallString.h"
  59. #include "llvm/ADT/SmallVector.h"
  60. #include "llvm/ADT/STLExtras.h"
  61. #include "llvm/ADT/StringRef.h"
  62. #include "llvm/ADT/StringSwitch.h"
  63. #include "llvm/Support/Capacity.h"
  64. #include "llvm/Support/ErrorHandling.h"
  65. #include "llvm/Support/MemoryBuffer.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <memory>
  70. #include <string>
  71. #include <utility>
  72. #include <vector>
  73. using namespace clang;
  74. LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
  75. ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
  76. Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
  77. DiagnosticsEngine &diags, LangOptions &opts,
  78. SourceManager &SM, MemoryBufferCache &PCMCache,
  79. HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
  80. IdentifierInfoLookup *IILookup, bool OwnsHeaders,
  81. TranslationUnitKind TUKind)
  82. : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
  83. FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
  84. ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
  85. TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
  86. // As the language options may have not been loaded yet (when
  87. // deserializing an ASTUnit), adding keywords to the identifier table is
  88. // deferred to Preprocessor::Initialize().
  89. Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
  90. TUKind(TUKind), SkipMainFilePreamble(0, true),
  91. CurSubmoduleState(&NullSubmoduleState) {
  92. OwnsHeaderSearch = OwnsHeaders;
  93. // Default to discarding comments.
  94. KeepComments = false;
  95. KeepMacroComments = false;
  96. SuppressIncludeNotFoundError = false;
  97. // Macro expansion is enabled.
  98. DisableMacroExpansion = false;
  99. MacroExpansionInDirectivesOverride = false;
  100. InMacroArgs = false;
  101. InMacroArgPreExpansion = false;
  102. NumCachedTokenLexers = 0;
  103. PragmasEnabled = true;
  104. ParsingIfOrElifDirective = false;
  105. PreprocessedOutput = false;
  106. // We haven't read anything from the external source.
  107. ReadMacrosFromExternalSource = false;
  108. // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
  109. // a macro. They get unpoisoned where it is allowed.
  110. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  111. SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
  112. if (getLangOpts().CPlusPlus2a) {
  113. (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
  114. SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
  115. } else {
  116. Ident__VA_OPT__ = nullptr;
  117. }
  118. // Initialize the pragma handlers.
  119. RegisterBuiltinPragmas();
  120. // Initialize builtin macros like __LINE__ and friends.
  121. RegisterBuiltinMacros();
  122. if(LangOpts.Borland) {
  123. Ident__exception_info = getIdentifierInfo("_exception_info");
  124. Ident___exception_info = getIdentifierInfo("__exception_info");
  125. Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
  126. Ident__exception_code = getIdentifierInfo("_exception_code");
  127. Ident___exception_code = getIdentifierInfo("__exception_code");
  128. Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
  129. Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
  130. Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
  131. Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
  132. } else {
  133. Ident__exception_info = Ident__exception_code = nullptr;
  134. Ident__abnormal_termination = Ident___exception_info = nullptr;
  135. Ident___exception_code = Ident___abnormal_termination = nullptr;
  136. Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
  137. Ident_AbnormalTermination = nullptr;
  138. }
  139. // If using a PCH with a through header, start skipping tokens.
  140. if (!this->PPOpts->PCHThroughHeader.empty() &&
  141. !this->PPOpts->ImplicitPCHInclude.empty())
  142. SkippingUntilPCHThroughHeader = true;
  143. if (this->PPOpts->GeneratePreamble)
  144. PreambleConditionalStack.startRecording();
  145. }
  146. Preprocessor::~Preprocessor() {
  147. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  148. IncludeMacroStack.clear();
  149. // Destroy any macro definitions.
  150. while (MacroInfoChain *I = MIChainHead) {
  151. MIChainHead = I->Next;
  152. I->~MacroInfoChain();
  153. }
  154. // Free any cached macro expanders.
  155. // This populates MacroArgCache, so all TokenLexers need to be destroyed
  156. // before the code below that frees up the MacroArgCache list.
  157. std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
  158. CurTokenLexer.reset();
  159. // Free any cached MacroArgs.
  160. for (MacroArgs *ArgList = MacroArgCache; ArgList;)
  161. ArgList = ArgList->deallocate();
  162. // Delete the header search info, if we own it.
  163. if (OwnsHeaderSearch)
  164. delete &HeaderInfo;
  165. }
  166. void Preprocessor::Initialize(const TargetInfo &Target,
  167. const TargetInfo *AuxTarget) {
  168. assert((!this->Target || this->Target == &Target) &&
  169. "Invalid override of target information");
  170. this->Target = &Target;
  171. assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
  172. "Invalid override of aux target information.");
  173. this->AuxTarget = AuxTarget;
  174. // Initialize information about built-ins.
  175. BuiltinInfo.InitializeTarget(Target, AuxTarget);
  176. HeaderInfo.setTarget(Target);
  177. // Populate the identifier table with info about keywords for the current language.
  178. Identifiers.AddKeywords(LangOpts);
  179. }
  180. void Preprocessor::InitializeForModelFile() {
  181. NumEnteredSourceFiles = 0;
  182. // Reset pragmas
  183. PragmaHandlersBackup = std::move(PragmaHandlers);
  184. PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
  185. RegisterBuiltinPragmas();
  186. // Reset PredefinesFileID
  187. PredefinesFileID = FileID();
  188. }
  189. void Preprocessor::FinalizeForModelFile() {
  190. NumEnteredSourceFiles = 1;
  191. PragmaHandlers = std::move(PragmaHandlersBackup);
  192. }
  193. void Preprocessor::setPTHManager(PTHManager* pm) {
  194. PTH.reset(pm);
  195. FileMgr.addStatCache(PTH->createStatCache());
  196. }
  197. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  198. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  199. << getSpelling(Tok) << "'";
  200. if (!DumpFlags) return;
  201. llvm::errs() << "\t";
  202. if (Tok.isAtStartOfLine())
  203. llvm::errs() << " [StartOfLine]";
  204. if (Tok.hasLeadingSpace())
  205. llvm::errs() << " [LeadingSpace]";
  206. if (Tok.isExpandDisabled())
  207. llvm::errs() << " [ExpandDisabled]";
  208. if (Tok.needsCleaning()) {
  209. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  210. llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
  211. << "']";
  212. }
  213. llvm::errs() << "\tLoc=<";
  214. DumpLocation(Tok.getLocation());
  215. llvm::errs() << ">";
  216. }
  217. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  218. Loc.dump(SourceMgr);
  219. }
  220. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  221. llvm::errs() << "MACRO: ";
  222. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  223. DumpToken(MI.getReplacementToken(i));
  224. llvm::errs() << " ";
  225. }
  226. llvm::errs() << "\n";
  227. }
  228. void Preprocessor::PrintStats() {
  229. llvm::errs() << "\n*** Preprocessor Stats:\n";
  230. llvm::errs() << NumDirectives << " directives found:\n";
  231. llvm::errs() << " " << NumDefined << " #define.\n";
  232. llvm::errs() << " " << NumUndefined << " #undef.\n";
  233. llvm::errs() << " #include/#include_next/#import:\n";
  234. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  235. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  236. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  237. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  238. llvm::errs() << " " << NumEndif << " #endif.\n";
  239. llvm::errs() << " " << NumPragma << " #pragma.\n";
  240. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  241. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  242. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  243. << NumFastMacroExpanded << " on the fast path.\n";
  244. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  245. << " token paste (##) operations performed, "
  246. << NumFastTokenPaste << " on the fast path.\n";
  247. llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
  248. llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
  249. llvm::errs() << "\n Macro Expanded Tokens: "
  250. << llvm::capacity_in_bytes(MacroExpandedTokens);
  251. llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
  252. // FIXME: List information for all submodules.
  253. llvm::errs() << "\n Macros: "
  254. << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
  255. llvm::errs() << "\n #pragma push_macro Info: "
  256. << llvm::capacity_in_bytes(PragmaPushMacroInfo);
  257. llvm::errs() << "\n Poison Reasons: "
  258. << llvm::capacity_in_bytes(PoisonReasons);
  259. llvm::errs() << "\n Comment Handlers: "
  260. << llvm::capacity_in_bytes(CommentHandlers) << "\n";
  261. }
  262. Preprocessor::macro_iterator
  263. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  264. if (IncludeExternalMacros && ExternalSource &&
  265. !ReadMacrosFromExternalSource) {
  266. ReadMacrosFromExternalSource = true;
  267. ExternalSource->ReadDefinedMacros();
  268. }
  269. // Make sure we cover all macros in visible modules.
  270. for (const ModuleMacro &Macro : ModuleMacros)
  271. CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
  272. return CurSubmoduleState->Macros.begin();
  273. }
  274. size_t Preprocessor::getTotalMemory() const {
  275. return BP.getTotalMemory()
  276. + llvm::capacity_in_bytes(MacroExpandedTokens)
  277. + Predefines.capacity() /* Predefines buffer. */
  278. // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
  279. // and ModuleMacros.
  280. + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
  281. + llvm::capacity_in_bytes(PragmaPushMacroInfo)
  282. + llvm::capacity_in_bytes(PoisonReasons)
  283. + llvm::capacity_in_bytes(CommentHandlers);
  284. }
  285. Preprocessor::macro_iterator
  286. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  287. if (IncludeExternalMacros && ExternalSource &&
  288. !ReadMacrosFromExternalSource) {
  289. ReadMacrosFromExternalSource = true;
  290. ExternalSource->ReadDefinedMacros();
  291. }
  292. return CurSubmoduleState->Macros.end();
  293. }
  294. /// Compares macro tokens with a specified token value sequence.
  295. static bool MacroDefinitionEquals(const MacroInfo *MI,
  296. ArrayRef<TokenValue> Tokens) {
  297. return Tokens.size() == MI->getNumTokens() &&
  298. std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
  299. }
  300. StringRef Preprocessor::getLastMacroWithSpelling(
  301. SourceLocation Loc,
  302. ArrayRef<TokenValue> Tokens) const {
  303. SourceLocation BestLocation;
  304. StringRef BestSpelling;
  305. for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
  306. I != E; ++I) {
  307. const MacroDirective::DefInfo
  308. Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
  309. if (!Def || !Def.getMacroInfo())
  310. continue;
  311. if (!Def.getMacroInfo()->isObjectLike())
  312. continue;
  313. if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
  314. continue;
  315. SourceLocation Location = Def.getLocation();
  316. // Choose the macro defined latest.
  317. if (BestLocation.isInvalid() ||
  318. (Location.isValid() &&
  319. SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
  320. BestLocation = Location;
  321. BestSpelling = I->first->getName();
  322. }
  323. }
  324. return BestSpelling;
  325. }
  326. void Preprocessor::recomputeCurLexerKind() {
  327. if (CurLexer)
  328. CurLexerKind = CLK_Lexer;
  329. else if (CurPTHLexer)
  330. CurLexerKind = CLK_PTHLexer;
  331. else if (CurTokenLexer)
  332. CurLexerKind = CLK_TokenLexer;
  333. else
  334. CurLexerKind = CLK_CachingLexer;
  335. }
  336. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  337. unsigned CompleteLine,
  338. unsigned CompleteColumn) {
  339. assert(File);
  340. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  341. assert(!CodeCompletionFile && "Already set");
  342. using llvm::MemoryBuffer;
  343. // Load the actual file's contents.
  344. bool Invalid = false;
  345. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  346. if (Invalid)
  347. return true;
  348. // Find the byte position of the truncation point.
  349. const char *Position = Buffer->getBufferStart();
  350. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  351. for (; *Position; ++Position) {
  352. if (*Position != '\r' && *Position != '\n')
  353. continue;
  354. // Eat \r\n or \n\r as a single line.
  355. if ((Position[1] == '\r' || Position[1] == '\n') &&
  356. Position[0] != Position[1])
  357. ++Position;
  358. ++Position;
  359. break;
  360. }
  361. }
  362. Position += CompleteColumn - 1;
  363. // If pointing inside the preamble, adjust the position at the beginning of
  364. // the file after the preamble.
  365. if (SkipMainFilePreamble.first &&
  366. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
  367. if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
  368. Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
  369. }
  370. if (Position > Buffer->getBufferEnd())
  371. Position = Buffer->getBufferEnd();
  372. CodeCompletionFile = File;
  373. CodeCompletionOffset = Position - Buffer->getBufferStart();
  374. auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
  375. Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
  376. char *NewBuf = NewBuffer->getBufferStart();
  377. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  378. *NewPos = '\0';
  379. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  380. SourceMgr.overrideFileContents(File, std::move(NewBuffer));
  381. return false;
  382. }
  383. void Preprocessor::CodeCompleteNaturalLanguage() {
  384. if (CodeComplete)
  385. CodeComplete->CodeCompleteNaturalLanguage();
  386. setCodeCompletionReached();
  387. }
  388. /// getSpelling - This method is used to get the spelling of a token into a
  389. /// SmallVector. Note that the returned StringRef may not point to the
  390. /// supplied buffer if a copy can be avoided.
  391. StringRef Preprocessor::getSpelling(const Token &Tok,
  392. SmallVectorImpl<char> &Buffer,
  393. bool *Invalid) const {
  394. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  395. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
  396. // Try the fast path.
  397. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  398. return II->getName();
  399. }
  400. // Resize the buffer if we need to copy into it.
  401. if (Tok.needsCleaning())
  402. Buffer.resize(Tok.getLength());
  403. const char *Ptr = Buffer.data();
  404. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  405. return StringRef(Ptr, Len);
  406. }
  407. /// CreateString - Plop the specified string into a scratch buffer and return a
  408. /// location for it. If specified, the source location provides a source
  409. /// location for the token.
  410. void Preprocessor::CreateString(StringRef Str, Token &Tok,
  411. SourceLocation ExpansionLocStart,
  412. SourceLocation ExpansionLocEnd) {
  413. Tok.setLength(Str.size());
  414. const char *DestPtr;
  415. SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
  416. if (ExpansionLocStart.isValid())
  417. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  418. ExpansionLocEnd, Str.size());
  419. Tok.setLocation(Loc);
  420. // If this is a raw identifier or a literal token, set the pointer data.
  421. if (Tok.is(tok::raw_identifier))
  422. Tok.setRawIdentifierData(DestPtr);
  423. else if (Tok.isLiteral())
  424. Tok.setLiteralData(DestPtr);
  425. }
  426. SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
  427. auto &SM = getSourceManager();
  428. SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
  429. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
  430. bool Invalid = false;
  431. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  432. if (Invalid)
  433. return SourceLocation();
  434. // FIXME: We could consider re-using spelling for tokens we see repeatedly.
  435. const char *DestPtr;
  436. SourceLocation Spelling =
  437. ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
  438. return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
  439. }
  440. Module *Preprocessor::getCurrentModule() {
  441. if (!getLangOpts().isCompilingModule())
  442. return nullptr;
  443. return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
  444. }
  445. //===----------------------------------------------------------------------===//
  446. // Preprocessor Initialization Methods
  447. //===----------------------------------------------------------------------===//
  448. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  449. /// which implicitly adds the builtin defines etc.
  450. void Preprocessor::EnterMainSourceFile() {
  451. // We do not allow the preprocessor to reenter the main file. Doing so will
  452. // cause FileID's to accumulate information from both runs (e.g. #line
  453. // information) and predefined macros aren't guaranteed to be set properly.
  454. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  455. FileID MainFileID = SourceMgr.getMainFileID();
  456. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  457. // a main file.
  458. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  459. // Enter the main file source buffer.
  460. EnterSourceFile(MainFileID, nullptr, SourceLocation());
  461. // If we've been asked to skip bytes in the main file (e.g., as part of a
  462. // precompiled preamble), do so now.
  463. if (SkipMainFilePreamble.first > 0)
  464. CurLexer->SetByteOffset(SkipMainFilePreamble.first,
  465. SkipMainFilePreamble.second);
  466. // Tell the header info that the main file was entered. If the file is later
  467. // #imported, it won't be re-entered.
  468. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  469. HeaderInfo.IncrementIncludeCount(FE);
  470. }
  471. // Preprocess Predefines to populate the initial preprocessor state.
  472. std::unique_ptr<llvm::MemoryBuffer> SB =
  473. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  474. assert(SB && "Cannot create predefined source buffer");
  475. FileID FID = SourceMgr.createFileID(std::move(SB));
  476. assert(FID.isValid() && "Could not create FileID for predefines?");
  477. setPredefinesFileID(FID);
  478. // Start parsing the predefines.
  479. EnterSourceFile(FID, nullptr, SourceLocation());
  480. if (!PPOpts->PCHThroughHeader.empty()) {
  481. // Lookup and save the FileID for the through header. If it isn't found
  482. // in the search path, it's a fatal error.
  483. const DirectoryLookup *CurDir;
  484. const FileEntry *File = LookupFile(
  485. SourceLocation(), PPOpts->PCHThroughHeader,
  486. /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir,
  487. /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
  488. /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr);
  489. if (!File) {
  490. Diag(SourceLocation(), diag::err_pp_through_header_not_found)
  491. << PPOpts->PCHThroughHeader;
  492. return;
  493. }
  494. setPCHThroughHeaderFileID(
  495. SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User));
  496. }
  497. // Skip tokens from the Predefines and if needed the main file.
  498. if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader)
  499. SkipTokensUntilPCHThroughHeader();
  500. }
  501. void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
  502. assert(PCHThroughHeaderFileID.isInvalid() &&
  503. "PCHThroughHeaderFileID already set!");
  504. PCHThroughHeaderFileID = FID;
  505. }
  506. bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
  507. assert(PCHThroughHeaderFileID.isValid() &&
  508. "Invalid PCH through header FileID");
  509. return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
  510. }
  511. bool Preprocessor::creatingPCHWithThroughHeader() {
  512. return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  513. PCHThroughHeaderFileID.isValid();
  514. }
  515. bool Preprocessor::usingPCHWithThroughHeader() {
  516. return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  517. PCHThroughHeaderFileID.isValid();
  518. }
  519. /// Skip tokens until after the #include of the through header.
  520. /// Tokens in the predefines file and the main file may be skipped. If the end
  521. /// of the predefines file is reached, skipping continues into the main file.
  522. /// If the end of the main file is reached, it's a fatal error.
  523. void Preprocessor::SkipTokensUntilPCHThroughHeader() {
  524. bool ReachedMainFileEOF = false;
  525. Token Tok;
  526. while (true) {
  527. bool InPredefines = (CurLexer->getFileID() == getPredefinesFileID());
  528. CurLexer->Lex(Tok);
  529. if (Tok.is(tok::eof) && !InPredefines) {
  530. ReachedMainFileEOF = true;
  531. break;
  532. }
  533. if (!SkippingUntilPCHThroughHeader)
  534. break;
  535. }
  536. if (ReachedMainFileEOF)
  537. Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
  538. << PPOpts->PCHThroughHeader << 1;
  539. }
  540. void Preprocessor::replayPreambleConditionalStack() {
  541. // Restore the conditional stack from the preamble, if there is one.
  542. if (PreambleConditionalStack.isReplaying()) {
  543. assert(CurPPLexer &&
  544. "CurPPLexer is null when calling replayPreambleConditionalStack.");
  545. CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
  546. PreambleConditionalStack.doneReplaying();
  547. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  548. SkipExcludedConditionalBlock(
  549. PreambleConditionalStack.SkipInfo->HashTokenLoc,
  550. PreambleConditionalStack.SkipInfo->IfTokenLoc,
  551. PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
  552. PreambleConditionalStack.SkipInfo->FoundElse,
  553. PreambleConditionalStack.SkipInfo->ElseLoc);
  554. }
  555. }
  556. void Preprocessor::EndSourceFile() {
  557. // Notify the client that we reached the end of the source file.
  558. if (Callbacks)
  559. Callbacks->EndOfMainFile();
  560. }
  561. //===----------------------------------------------------------------------===//
  562. // Lexer Event Handling.
  563. //===----------------------------------------------------------------------===//
  564. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  565. /// identifier information for the token and install it into the token,
  566. /// updating the token kind accordingly.
  567. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  568. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  569. // Look up this token, see if it is a macro, or if it is a language keyword.
  570. IdentifierInfo *II;
  571. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  572. // No cleaning needed, just use the characters from the lexed buffer.
  573. II = getIdentifierInfo(Identifier.getRawIdentifier());
  574. } else {
  575. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  576. SmallString<64> IdentifierBuffer;
  577. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  578. if (Identifier.hasUCN()) {
  579. SmallString<64> UCNIdentifierBuffer;
  580. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  581. II = getIdentifierInfo(UCNIdentifierBuffer);
  582. } else {
  583. II = getIdentifierInfo(CleanedStr);
  584. }
  585. }
  586. // Update the token info (identifier info and appropriate token kind).
  587. Identifier.setIdentifierInfo(II);
  588. if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
  589. getSourceManager().isInSystemHeader(Identifier.getLocation()))
  590. Identifier.setKind(tok::identifier);
  591. else
  592. Identifier.setKind(II->getTokenID());
  593. return II;
  594. }
  595. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  596. PoisonReasons[II] = DiagID;
  597. }
  598. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  599. assert(Ident__exception_code && Ident__exception_info);
  600. assert(Ident___exception_code && Ident___exception_info);
  601. Ident__exception_code->setIsPoisoned(Poison);
  602. Ident___exception_code->setIsPoisoned(Poison);
  603. Ident_GetExceptionCode->setIsPoisoned(Poison);
  604. Ident__exception_info->setIsPoisoned(Poison);
  605. Ident___exception_info->setIsPoisoned(Poison);
  606. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  607. Ident__abnormal_termination->setIsPoisoned(Poison);
  608. Ident___abnormal_termination->setIsPoisoned(Poison);
  609. Ident_AbnormalTermination->setIsPoisoned(Poison);
  610. }
  611. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  612. assert(Identifier.getIdentifierInfo() &&
  613. "Can't handle identifiers without identifier info!");
  614. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  615. PoisonReasons.find(Identifier.getIdentifierInfo());
  616. if(it == PoisonReasons.end())
  617. Diag(Identifier, diag::err_pp_used_poisoned_id);
  618. else
  619. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  620. }
  621. /// Returns a diagnostic message kind for reporting a future keyword as
  622. /// appropriate for the identifier and specified language.
  623. static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
  624. const LangOptions &LangOpts) {
  625. assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
  626. if (LangOpts.CPlusPlus)
  627. return llvm::StringSwitch<diag::kind>(II.getName())
  628. #define CXX11_KEYWORD(NAME, FLAGS) \
  629. .Case(#NAME, diag::warn_cxx11_keyword)
  630. #define CXX2A_KEYWORD(NAME, FLAGS) \
  631. .Case(#NAME, diag::warn_cxx2a_keyword)
  632. #include "clang/Basic/TokenKinds.def"
  633. ;
  634. llvm_unreachable(
  635. "Keyword not known to come from a newer Standard or proposed Standard");
  636. }
  637. void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
  638. assert(II.isOutOfDate() && "not out of date");
  639. getExternalSource()->updateOutOfDateIdentifier(II);
  640. }
  641. /// HandleIdentifier - This callback is invoked when the lexer reads an
  642. /// identifier. This callback looks up the identifier in the map and/or
  643. /// potentially macro expands it or turns it into a named token (like 'for').
  644. ///
  645. /// Note that callers of this method are guarded by checking the
  646. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  647. /// IdentifierInfo methods that compute these properties will need to change to
  648. /// match.
  649. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  650. assert(Identifier.getIdentifierInfo() &&
  651. "Can't handle identifiers without identifier info!");
  652. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  653. // If the information about this identifier is out of date, update it from
  654. // the external source.
  655. // We have to treat __VA_ARGS__ in a special way, since it gets
  656. // serialized with isPoisoned = true, but our preprocessor may have
  657. // unpoisoned it if we're defining a C99 macro.
  658. if (II.isOutOfDate()) {
  659. bool CurrentIsPoisoned = false;
  660. const bool IsSpecialVariadicMacro =
  661. &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
  662. if (IsSpecialVariadicMacro)
  663. CurrentIsPoisoned = II.isPoisoned();
  664. updateOutOfDateIdentifier(II);
  665. Identifier.setKind(II.getTokenID());
  666. if (IsSpecialVariadicMacro)
  667. II.setIsPoisoned(CurrentIsPoisoned);
  668. }
  669. // If this identifier was poisoned, and if it was not produced from a macro
  670. // expansion, emit an error.
  671. if (II.isPoisoned() && CurPPLexer) {
  672. HandlePoisonedIdentifier(Identifier);
  673. }
  674. // If this is a macro to be expanded, do it.
  675. if (MacroDefinition MD = getMacroDefinition(&II)) {
  676. auto *MI = MD.getMacroInfo();
  677. assert(MI && "macro definition with no macro info?");
  678. if (!DisableMacroExpansion) {
  679. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  680. // C99 6.10.3p10: If the preprocessing token immediately after the
  681. // macro name isn't a '(', this macro should not be expanded.
  682. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  683. return HandleMacroExpandedIdentifier(Identifier, MD);
  684. } else {
  685. // C99 6.10.3.4p2 says that a disabled macro may never again be
  686. // expanded, even if it's in a context where it could be expanded in the
  687. // future.
  688. Identifier.setFlag(Token::DisableExpand);
  689. if (MI->isObjectLike() || isNextPPTokenLParen())
  690. Diag(Identifier, diag::pp_disabled_macro_expansion);
  691. }
  692. }
  693. }
  694. // If this identifier is a keyword in a newer Standard or proposed Standard,
  695. // produce a warning. Don't warn if we're not considering macro expansion,
  696. // since this identifier might be the name of a macro.
  697. // FIXME: This warning is disabled in cases where it shouldn't be, like
  698. // "#define constexpr constexpr", "int constexpr;"
  699. if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
  700. Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
  701. << II.getName();
  702. // Don't diagnose this keyword again in this translation unit.
  703. II.setIsFutureCompatKeyword(false);
  704. }
  705. // If this is an extension token, diagnose its use.
  706. // We avoid diagnosing tokens that originate from macro definitions.
  707. // FIXME: This warning is disabled in cases where it shouldn't be,
  708. // like "#define TY typeof", "TY(1) x".
  709. if (II.isExtensionToken() && !DisableMacroExpansion)
  710. Diag(Identifier, diag::ext_token_used);
  711. // If this is the 'import' contextual keyword following an '@', note
  712. // that the next token indicates a module name.
  713. //
  714. // Note that we do not treat 'import' as a contextual
  715. // keyword when we're in a caching lexer, because caching lexers only get
  716. // used in contexts where import declarations are disallowed.
  717. //
  718. // Likewise if this is the C++ Modules TS import keyword.
  719. if (((LastTokenWasAt && II.isModulesImport()) ||
  720. Identifier.is(tok::kw_import)) &&
  721. !InMacroArgs && !DisableMacroExpansion &&
  722. (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
  723. CurLexerKind != CLK_CachingLexer) {
  724. ModuleImportLoc = Identifier.getLocation();
  725. ModuleImportPath.clear();
  726. ModuleImportExpectsIdentifier = true;
  727. CurLexerKind = CLK_LexAfterModuleImport;
  728. }
  729. return true;
  730. }
  731. void Preprocessor::Lex(Token &Result) {
  732. // We loop here until a lex function returns a token; this avoids recursion.
  733. bool ReturnedToken;
  734. do {
  735. switch (CurLexerKind) {
  736. case CLK_Lexer:
  737. ReturnedToken = CurLexer->Lex(Result);
  738. break;
  739. case CLK_PTHLexer:
  740. ReturnedToken = CurPTHLexer->Lex(Result);
  741. break;
  742. case CLK_TokenLexer:
  743. ReturnedToken = CurTokenLexer->Lex(Result);
  744. break;
  745. case CLK_CachingLexer:
  746. CachingLex(Result);
  747. ReturnedToken = true;
  748. break;
  749. case CLK_LexAfterModuleImport:
  750. LexAfterModuleImport(Result);
  751. ReturnedToken = true;
  752. break;
  753. }
  754. } while (!ReturnedToken);
  755. if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
  756. // Remember the identifier before code completion token.
  757. setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
  758. setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
  759. // Set IdenfitierInfo to null to avoid confusing code that handles both
  760. // identifiers and completion tokens.
  761. Result.setIdentifierInfo(nullptr);
  762. }
  763. LastTokenWasAt = Result.is(tok::at);
  764. }
  765. /// Lex a token following the 'import' contextual keyword.
  766. ///
  767. void Preprocessor::LexAfterModuleImport(Token &Result) {
  768. // Figure out what kind of lexer we actually have.
  769. recomputeCurLexerKind();
  770. // Lex the next token.
  771. Lex(Result);
  772. // The token sequence
  773. //
  774. // import identifier (. identifier)*
  775. //
  776. // indicates a module import directive. We already saw the 'import'
  777. // contextual keyword, so now we're looking for the identifiers.
  778. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  779. // We expected to see an identifier here, and we did; continue handling
  780. // identifiers.
  781. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  782. Result.getLocation()));
  783. ModuleImportExpectsIdentifier = false;
  784. CurLexerKind = CLK_LexAfterModuleImport;
  785. return;
  786. }
  787. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  788. // see the next identifier. (We can also see a '[[' that begins an
  789. // attribute-specifier-seq here under the C++ Modules TS.)
  790. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  791. ModuleImportExpectsIdentifier = true;
  792. CurLexerKind = CLK_LexAfterModuleImport;
  793. return;
  794. }
  795. // If we have a non-empty module path, load the named module.
  796. if (!ModuleImportPath.empty()) {
  797. // Under the Modules TS, the dot is just part of the module name, and not
  798. // a real hierarachy separator. Flatten such module names now.
  799. //
  800. // FIXME: Is this the right level to be performing this transformation?
  801. std::string FlatModuleName;
  802. if (getLangOpts().ModulesTS) {
  803. for (auto &Piece : ModuleImportPath) {
  804. if (!FlatModuleName.empty())
  805. FlatModuleName += ".";
  806. FlatModuleName += Piece.first->getName();
  807. }
  808. SourceLocation FirstPathLoc = ModuleImportPath[0].second;
  809. ModuleImportPath.clear();
  810. ModuleImportPath.push_back(
  811. std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
  812. }
  813. Module *Imported = nullptr;
  814. if (getLangOpts().Modules) {
  815. Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  816. ModuleImportPath,
  817. Module::Hidden,
  818. /*IsIncludeDirective=*/false);
  819. if (Imported)
  820. makeModuleVisible(Imported, ModuleImportLoc);
  821. }
  822. if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
  823. Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
  824. }
  825. }
  826. void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
  827. CurSubmoduleState->VisibleModules.setVisible(
  828. M, Loc, [](Module *) {},
  829. [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
  830. // FIXME: Include the path in the diagnostic.
  831. // FIXME: Include the import location for the conflicting module.
  832. Diag(ModuleImportLoc, diag::warn_module_conflict)
  833. << Path[0]->getFullModuleName()
  834. << Conflict->getFullModuleName()
  835. << Message;
  836. });
  837. // Add this module to the imports list of the currently-built submodule.
  838. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
  839. BuildingSubmoduleStack.back().M->Imports.insert(M);
  840. }
  841. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  842. const char *DiagnosticTag,
  843. bool AllowMacroExpansion) {
  844. // We need at least one string literal.
  845. if (Result.isNot(tok::string_literal)) {
  846. Diag(Result, diag::err_expected_string_literal)
  847. << /*Source='in...'*/0 << DiagnosticTag;
  848. return false;
  849. }
  850. // Lex string literal tokens, optionally with macro expansion.
  851. SmallVector<Token, 4> StrToks;
  852. do {
  853. StrToks.push_back(Result);
  854. if (Result.hasUDSuffix())
  855. Diag(Result, diag::err_invalid_string_udl);
  856. if (AllowMacroExpansion)
  857. Lex(Result);
  858. else
  859. LexUnexpandedToken(Result);
  860. } while (Result.is(tok::string_literal));
  861. // Concatenate and parse the strings.
  862. StringLiteralParser Literal(StrToks, *this);
  863. assert(Literal.isAscii() && "Didn't allow wide strings in");
  864. if (Literal.hadError)
  865. return false;
  866. if (Literal.Pascal) {
  867. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  868. << /*Source='in...'*/0 << DiagnosticTag;
  869. return false;
  870. }
  871. String = Literal.GetString();
  872. return true;
  873. }
  874. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  875. assert(Tok.is(tok::numeric_constant));
  876. SmallString<8> IntegerBuffer;
  877. bool NumberInvalid = false;
  878. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  879. if (NumberInvalid)
  880. return false;
  881. NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
  882. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  883. return false;
  884. llvm::APInt APVal(64, 0);
  885. if (Literal.GetIntegerValue(APVal))
  886. return false;
  887. Lex(Tok);
  888. Value = APVal.getLimitedValue();
  889. return true;
  890. }
  891. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  892. assert(Handler && "NULL comment handler");
  893. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  894. CommentHandlers.end() && "Comment handler already registered");
  895. CommentHandlers.push_back(Handler);
  896. }
  897. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  898. std::vector<CommentHandler *>::iterator Pos =
  899. std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  900. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  901. CommentHandlers.erase(Pos);
  902. }
  903. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  904. bool AnyPendingTokens = false;
  905. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  906. HEnd = CommentHandlers.end();
  907. H != HEnd; ++H) {
  908. if ((*H)->HandleComment(*this, Comment))
  909. AnyPendingTokens = true;
  910. }
  911. if (!AnyPendingTokens || getCommentRetentionState())
  912. return false;
  913. Lex(result);
  914. return true;
  915. }
  916. ModuleLoader::~ModuleLoader() = default;
  917. CommentHandler::~CommentHandler() = default;
  918. CodeCompletionHandler::~CodeCompletionHandler() = default;
  919. void Preprocessor::createPreprocessingRecord() {
  920. if (Record)
  921. return;
  922. Record = new PreprocessingRecord(getSourceManager());
  923. addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
  924. }