Preprocessor.cpp 35 KB

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