Preprocessor.cpp 40 KB

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