Preprocessor.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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/Pragma.h"
  47. #include "clang/Lex/PreprocessingRecord.h"
  48. #include "clang/Lex/PreprocessorLexer.h"
  49. #include "clang/Lex/PreprocessorOptions.h"
  50. #include "clang/Lex/ScratchBuffer.h"
  51. #include "clang/Lex/Token.h"
  52. #include "clang/Lex/TokenLexer.h"
  53. #include "llvm/ADT/APInt.h"
  54. #include "llvm/ADT/ArrayRef.h"
  55. #include "llvm/ADT/DenseMap.h"
  56. #include "llvm/ADT/SmallString.h"
  57. #include "llvm/ADT/SmallVector.h"
  58. #include "llvm/ADT/STLExtras.h"
  59. #include "llvm/ADT/StringRef.h"
  60. #include "llvm/ADT/StringSwitch.h"
  61. #include "llvm/Support/Capacity.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/MemoryBuffer.h"
  64. #include "llvm/Support/raw_ostream.h"
  65. #include <algorithm>
  66. #include <cassert>
  67. #include <memory>
  68. #include <string>
  69. #include <utility>
  70. #include <vector>
  71. using namespace clang;
  72. LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
  73. ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
  74. Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
  75. DiagnosticsEngine &diags, LangOptions &opts,
  76. SourceManager &SM, MemoryBufferCache &PCMCache,
  77. HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
  78. IdentifierInfoLookup *IILookup, bool OwnsHeaders,
  79. TranslationUnitKind TUKind)
  80. : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
  81. FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
  82. ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
  83. TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
  84. // As the language options may have not been loaded yet (when
  85. // deserializing an ASTUnit), adding keywords to the identifier table is
  86. // deferred to Preprocessor::Initialize().
  87. Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
  88. TUKind(TUKind), SkipMainFilePreamble(0, true),
  89. CurSubmoduleState(&NullSubmoduleState) {
  90. OwnsHeaderSearch = OwnsHeaders;
  91. // Default to discarding comments.
  92. KeepComments = false;
  93. KeepMacroComments = false;
  94. SuppressIncludeNotFoundError = false;
  95. // Macro expansion is enabled.
  96. DisableMacroExpansion = false;
  97. MacroExpansionInDirectivesOverride = false;
  98. InMacroArgs = false;
  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. if (!File) {
  491. Diag(SourceLocation(), diag::err_pp_through_header_not_found)
  492. << PPOpts->PCHThroughHeader;
  493. return;
  494. }
  495. setPCHThroughHeaderFileID(
  496. SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User));
  497. }
  498. // Skip tokens from the Predefines and if needed the main file.
  499. if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
  500. (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
  501. SkipTokensWhileUsingPCH();
  502. }
  503. void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
  504. assert(PCHThroughHeaderFileID.isInvalid() &&
  505. "PCHThroughHeaderFileID already set!");
  506. PCHThroughHeaderFileID = FID;
  507. }
  508. bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
  509. assert(PCHThroughHeaderFileID.isValid() &&
  510. "Invalid PCH through header FileID");
  511. return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
  512. }
  513. bool Preprocessor::creatingPCHWithThroughHeader() {
  514. return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  515. PCHThroughHeaderFileID.isValid();
  516. }
  517. bool Preprocessor::usingPCHWithThroughHeader() {
  518. return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  519. PCHThroughHeaderFileID.isValid();
  520. }
  521. bool Preprocessor::creatingPCHWithPragmaHdrStop() {
  522. return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
  523. }
  524. bool Preprocessor::usingPCHWithPragmaHdrStop() {
  525. return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
  526. }
  527. /// Skip tokens until after the #include of the through header or
  528. /// until after a #pragma hdrstop is seen. Tokens in the predefines file
  529. /// and the main file may be skipped. If the end of the predefines file
  530. /// is reached, skipping continues into the main file. If the end of the
  531. /// main file is reached, it's a fatal error.
  532. void Preprocessor::SkipTokensWhileUsingPCH() {
  533. bool ReachedMainFileEOF = false;
  534. bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
  535. bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
  536. Token Tok;
  537. while (true) {
  538. bool InPredefines = (CurLexer->getFileID() == getPredefinesFileID());
  539. CurLexer->Lex(Tok);
  540. if (Tok.is(tok::eof) && !InPredefines) {
  541. ReachedMainFileEOF = true;
  542. break;
  543. }
  544. if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
  545. break;
  546. if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
  547. break;
  548. }
  549. if (ReachedMainFileEOF) {
  550. if (UsingPCHThroughHeader)
  551. Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
  552. << PPOpts->PCHThroughHeader << 1;
  553. else if (!PPOpts->PCHWithHdrStopCreate)
  554. Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
  555. }
  556. }
  557. void Preprocessor::replayPreambleConditionalStack() {
  558. // Restore the conditional stack from the preamble, if there is one.
  559. if (PreambleConditionalStack.isReplaying()) {
  560. assert(CurPPLexer &&
  561. "CurPPLexer is null when calling replayPreambleConditionalStack.");
  562. CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
  563. PreambleConditionalStack.doneReplaying();
  564. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  565. SkipExcludedConditionalBlock(
  566. PreambleConditionalStack.SkipInfo->HashTokenLoc,
  567. PreambleConditionalStack.SkipInfo->IfTokenLoc,
  568. PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
  569. PreambleConditionalStack.SkipInfo->FoundElse,
  570. PreambleConditionalStack.SkipInfo->ElseLoc);
  571. }
  572. }
  573. void Preprocessor::EndSourceFile() {
  574. // Notify the client that we reached the end of the source file.
  575. if (Callbacks)
  576. Callbacks->EndOfMainFile();
  577. }
  578. //===----------------------------------------------------------------------===//
  579. // Lexer Event Handling.
  580. //===----------------------------------------------------------------------===//
  581. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  582. /// identifier information for the token and install it into the token,
  583. /// updating the token kind accordingly.
  584. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  585. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  586. // Look up this token, see if it is a macro, or if it is a language keyword.
  587. IdentifierInfo *II;
  588. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  589. // No cleaning needed, just use the characters from the lexed buffer.
  590. II = getIdentifierInfo(Identifier.getRawIdentifier());
  591. } else {
  592. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  593. SmallString<64> IdentifierBuffer;
  594. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  595. if (Identifier.hasUCN()) {
  596. SmallString<64> UCNIdentifierBuffer;
  597. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  598. II = getIdentifierInfo(UCNIdentifierBuffer);
  599. } else {
  600. II = getIdentifierInfo(CleanedStr);
  601. }
  602. }
  603. // Update the token info (identifier info and appropriate token kind).
  604. Identifier.setIdentifierInfo(II);
  605. if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
  606. getSourceManager().isInSystemHeader(Identifier.getLocation()))
  607. Identifier.setKind(tok::identifier);
  608. else
  609. Identifier.setKind(II->getTokenID());
  610. return II;
  611. }
  612. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  613. PoisonReasons[II] = DiagID;
  614. }
  615. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  616. assert(Ident__exception_code && Ident__exception_info);
  617. assert(Ident___exception_code && Ident___exception_info);
  618. Ident__exception_code->setIsPoisoned(Poison);
  619. Ident___exception_code->setIsPoisoned(Poison);
  620. Ident_GetExceptionCode->setIsPoisoned(Poison);
  621. Ident__exception_info->setIsPoisoned(Poison);
  622. Ident___exception_info->setIsPoisoned(Poison);
  623. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  624. Ident__abnormal_termination->setIsPoisoned(Poison);
  625. Ident___abnormal_termination->setIsPoisoned(Poison);
  626. Ident_AbnormalTermination->setIsPoisoned(Poison);
  627. }
  628. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  629. assert(Identifier.getIdentifierInfo() &&
  630. "Can't handle identifiers without identifier info!");
  631. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  632. PoisonReasons.find(Identifier.getIdentifierInfo());
  633. if(it == PoisonReasons.end())
  634. Diag(Identifier, diag::err_pp_used_poisoned_id);
  635. else
  636. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  637. }
  638. /// Returns a diagnostic message kind for reporting a future keyword as
  639. /// appropriate for the identifier and specified language.
  640. static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
  641. const LangOptions &LangOpts) {
  642. assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
  643. if (LangOpts.CPlusPlus)
  644. return llvm::StringSwitch<diag::kind>(II.getName())
  645. #define CXX11_KEYWORD(NAME, FLAGS) \
  646. .Case(#NAME, diag::warn_cxx11_keyword)
  647. #define CXX2A_KEYWORD(NAME, FLAGS) \
  648. .Case(#NAME, diag::warn_cxx2a_keyword)
  649. #include "clang/Basic/TokenKinds.def"
  650. ;
  651. llvm_unreachable(
  652. "Keyword not known to come from a newer Standard or proposed Standard");
  653. }
  654. void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
  655. assert(II.isOutOfDate() && "not out of date");
  656. getExternalSource()->updateOutOfDateIdentifier(II);
  657. }
  658. /// HandleIdentifier - This callback is invoked when the lexer reads an
  659. /// identifier. This callback looks up the identifier in the map and/or
  660. /// potentially macro expands it or turns it into a named token (like 'for').
  661. ///
  662. /// Note that callers of this method are guarded by checking the
  663. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  664. /// IdentifierInfo methods that compute these properties will need to change to
  665. /// match.
  666. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  667. assert(Identifier.getIdentifierInfo() &&
  668. "Can't handle identifiers without identifier info!");
  669. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  670. // If the information about this identifier is out of date, update it from
  671. // the external source.
  672. // We have to treat __VA_ARGS__ in a special way, since it gets
  673. // serialized with isPoisoned = true, but our preprocessor may have
  674. // unpoisoned it if we're defining a C99 macro.
  675. if (II.isOutOfDate()) {
  676. bool CurrentIsPoisoned = false;
  677. const bool IsSpecialVariadicMacro =
  678. &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
  679. if (IsSpecialVariadicMacro)
  680. CurrentIsPoisoned = II.isPoisoned();
  681. updateOutOfDateIdentifier(II);
  682. Identifier.setKind(II.getTokenID());
  683. if (IsSpecialVariadicMacro)
  684. II.setIsPoisoned(CurrentIsPoisoned);
  685. }
  686. // If this identifier was poisoned, and if it was not produced from a macro
  687. // expansion, emit an error.
  688. if (II.isPoisoned() && CurPPLexer) {
  689. HandlePoisonedIdentifier(Identifier);
  690. }
  691. // If this is a macro to be expanded, do it.
  692. if (MacroDefinition MD = getMacroDefinition(&II)) {
  693. auto *MI = MD.getMacroInfo();
  694. assert(MI && "macro definition with no macro info?");
  695. if (!DisableMacroExpansion) {
  696. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  697. // C99 6.10.3p10: If the preprocessing token immediately after the
  698. // macro name isn't a '(', this macro should not be expanded.
  699. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  700. return HandleMacroExpandedIdentifier(Identifier, MD);
  701. } else {
  702. // C99 6.10.3.4p2 says that a disabled macro may never again be
  703. // expanded, even if it's in a context where it could be expanded in the
  704. // future.
  705. Identifier.setFlag(Token::DisableExpand);
  706. if (MI->isObjectLike() || isNextPPTokenLParen())
  707. Diag(Identifier, diag::pp_disabled_macro_expansion);
  708. }
  709. }
  710. }
  711. // If this identifier is a keyword in a newer Standard or proposed Standard,
  712. // produce a warning. Don't warn if we're not considering macro expansion,
  713. // since this identifier might be the name of a macro.
  714. // FIXME: This warning is disabled in cases where it shouldn't be, like
  715. // "#define constexpr constexpr", "int constexpr;"
  716. if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
  717. Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
  718. << II.getName();
  719. // Don't diagnose this keyword again in this translation unit.
  720. II.setIsFutureCompatKeyword(false);
  721. }
  722. // If this is an extension token, diagnose its use.
  723. // We avoid diagnosing tokens that originate from macro definitions.
  724. // FIXME: This warning is disabled in cases where it shouldn't be,
  725. // like "#define TY typeof", "TY(1) x".
  726. if (II.isExtensionToken() && !DisableMacroExpansion)
  727. Diag(Identifier, diag::ext_token_used);
  728. // If this is the 'import' contextual keyword following an '@', note
  729. // that the next token indicates a module name.
  730. //
  731. // Note that we do not treat 'import' as a contextual
  732. // keyword when we're in a caching lexer, because caching lexers only get
  733. // used in contexts where import declarations are disallowed.
  734. //
  735. // Likewise if this is the C++ Modules TS import keyword.
  736. if (((LastTokenWasAt && II.isModulesImport()) ||
  737. Identifier.is(tok::kw_import)) &&
  738. !InMacroArgs && !DisableMacroExpansion &&
  739. (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
  740. CurLexerKind != CLK_CachingLexer) {
  741. ModuleImportLoc = Identifier.getLocation();
  742. ModuleImportPath.clear();
  743. ModuleImportExpectsIdentifier = true;
  744. CurLexerKind = CLK_LexAfterModuleImport;
  745. }
  746. return true;
  747. }
  748. void Preprocessor::Lex(Token &Result) {
  749. // We loop here until a lex function returns a token; this avoids recursion.
  750. bool ReturnedToken;
  751. do {
  752. switch (CurLexerKind) {
  753. case CLK_Lexer:
  754. ReturnedToken = CurLexer->Lex(Result);
  755. break;
  756. case CLK_TokenLexer:
  757. ReturnedToken = CurTokenLexer->Lex(Result);
  758. break;
  759. case CLK_CachingLexer:
  760. CachingLex(Result);
  761. ReturnedToken = true;
  762. break;
  763. case CLK_LexAfterModuleImport:
  764. LexAfterModuleImport(Result);
  765. ReturnedToken = true;
  766. break;
  767. }
  768. } while (!ReturnedToken);
  769. if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
  770. // Remember the identifier before code completion token.
  771. setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
  772. setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
  773. // Set IdenfitierInfo to null to avoid confusing code that handles both
  774. // identifiers and completion tokens.
  775. Result.setIdentifierInfo(nullptr);
  776. }
  777. LastTokenWasAt = Result.is(tok::at);
  778. }
  779. /// Lex a token following the 'import' contextual keyword.
  780. ///
  781. void Preprocessor::LexAfterModuleImport(Token &Result) {
  782. // Figure out what kind of lexer we actually have.
  783. recomputeCurLexerKind();
  784. // Lex the next token.
  785. Lex(Result);
  786. // The token sequence
  787. //
  788. // import identifier (. identifier)*
  789. //
  790. // indicates a module import directive. We already saw the 'import'
  791. // contextual keyword, so now we're looking for the identifiers.
  792. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  793. // We expected to see an identifier here, and we did; continue handling
  794. // identifiers.
  795. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  796. Result.getLocation()));
  797. ModuleImportExpectsIdentifier = false;
  798. CurLexerKind = CLK_LexAfterModuleImport;
  799. return;
  800. }
  801. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  802. // see the next identifier. (We can also see a '[[' that begins an
  803. // attribute-specifier-seq here under the C++ Modules TS.)
  804. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  805. ModuleImportExpectsIdentifier = true;
  806. CurLexerKind = CLK_LexAfterModuleImport;
  807. return;
  808. }
  809. // If we have a non-empty module path, load the named module.
  810. if (!ModuleImportPath.empty()) {
  811. // Under the Modules TS, the dot is just part of the module name, and not
  812. // a real hierarchy separator. Flatten such module names now.
  813. //
  814. // FIXME: Is this the right level to be performing this transformation?
  815. std::string FlatModuleName;
  816. if (getLangOpts().ModulesTS) {
  817. for (auto &Piece : ModuleImportPath) {
  818. if (!FlatModuleName.empty())
  819. FlatModuleName += ".";
  820. FlatModuleName += Piece.first->getName();
  821. }
  822. SourceLocation FirstPathLoc = ModuleImportPath[0].second;
  823. ModuleImportPath.clear();
  824. ModuleImportPath.push_back(
  825. std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
  826. }
  827. Module *Imported = nullptr;
  828. if (getLangOpts().Modules) {
  829. Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  830. ModuleImportPath,
  831. Module::Hidden,
  832. /*IsIncludeDirective=*/false);
  833. if (Imported)
  834. makeModuleVisible(Imported, ModuleImportLoc);
  835. }
  836. if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
  837. Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
  838. }
  839. }
  840. void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
  841. CurSubmoduleState->VisibleModules.setVisible(
  842. M, Loc, [](Module *) {},
  843. [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
  844. // FIXME: Include the path in the diagnostic.
  845. // FIXME: Include the import location for the conflicting module.
  846. Diag(ModuleImportLoc, diag::warn_module_conflict)
  847. << Path[0]->getFullModuleName()
  848. << Conflict->getFullModuleName()
  849. << Message;
  850. });
  851. // Add this module to the imports list of the currently-built submodule.
  852. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
  853. BuildingSubmoduleStack.back().M->Imports.insert(M);
  854. }
  855. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  856. const char *DiagnosticTag,
  857. bool AllowMacroExpansion) {
  858. // We need at least one string literal.
  859. if (Result.isNot(tok::string_literal)) {
  860. Diag(Result, diag::err_expected_string_literal)
  861. << /*Source='in...'*/0 << DiagnosticTag;
  862. return false;
  863. }
  864. // Lex string literal tokens, optionally with macro expansion.
  865. SmallVector<Token, 4> StrToks;
  866. do {
  867. StrToks.push_back(Result);
  868. if (Result.hasUDSuffix())
  869. Diag(Result, diag::err_invalid_string_udl);
  870. if (AllowMacroExpansion)
  871. Lex(Result);
  872. else
  873. LexUnexpandedToken(Result);
  874. } while (Result.is(tok::string_literal));
  875. // Concatenate and parse the strings.
  876. StringLiteralParser Literal(StrToks, *this);
  877. assert(Literal.isAscii() && "Didn't allow wide strings in");
  878. if (Literal.hadError)
  879. return false;
  880. if (Literal.Pascal) {
  881. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  882. << /*Source='in...'*/0 << DiagnosticTag;
  883. return false;
  884. }
  885. String = Literal.GetString();
  886. return true;
  887. }
  888. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  889. assert(Tok.is(tok::numeric_constant));
  890. SmallString<8> IntegerBuffer;
  891. bool NumberInvalid = false;
  892. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  893. if (NumberInvalid)
  894. return false;
  895. NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
  896. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  897. return false;
  898. llvm::APInt APVal(64, 0);
  899. if (Literal.GetIntegerValue(APVal))
  900. return false;
  901. Lex(Tok);
  902. Value = APVal.getLimitedValue();
  903. return true;
  904. }
  905. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  906. assert(Handler && "NULL comment handler");
  907. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  908. CommentHandlers.end() && "Comment handler already registered");
  909. CommentHandlers.push_back(Handler);
  910. }
  911. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  912. std::vector<CommentHandler *>::iterator Pos =
  913. std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  914. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  915. CommentHandlers.erase(Pos);
  916. }
  917. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  918. bool AnyPendingTokens = false;
  919. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  920. HEnd = CommentHandlers.end();
  921. H != HEnd; ++H) {
  922. if ((*H)->HandleComment(*this, Comment))
  923. AnyPendingTokens = true;
  924. }
  925. if (!AnyPendingTokens || getCommentRetentionState())
  926. return false;
  927. Lex(result);
  928. return true;
  929. }
  930. ModuleLoader::~ModuleLoader() = default;
  931. CommentHandler::~CommentHandler() = default;
  932. CodeCompletionHandler::~CodeCompletionHandler() = default;
  933. void Preprocessor::createPreprocessingRecord() {
  934. if (Record)
  935. return;
  936. Record = new PreprocessingRecord(getSourceManager());
  937. addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
  938. }