Preprocessor.cpp 40 KB

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