Preprocessor.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Lex/CodeCompletionHandler.h"
  33. #include "clang/Lex/ExternalPreprocessorSource.h"
  34. #include "clang/Lex/HeaderSearch.h"
  35. #include "clang/Lex/LexDiagnostic.h"
  36. #include "clang/Lex/LiteralSupport.h"
  37. #include "clang/Lex/MacroArgs.h"
  38. #include "clang/Lex/MacroInfo.h"
  39. #include "clang/Lex/ModuleLoader.h"
  40. #include "clang/Lex/Pragma.h"
  41. #include "clang/Lex/PreprocessingRecord.h"
  42. #include "clang/Lex/PreprocessorOptions.h"
  43. #include "clang/Lex/ScratchBuffer.h"
  44. #include "llvm/ADT/APFloat.h"
  45. #include "llvm/ADT/STLExtras.h"
  46. #include "llvm/ADT/SmallString.h"
  47. #include "llvm/ADT/StringExtras.h"
  48. #include "llvm/Support/Capacity.h"
  49. #include "llvm/Support/ConvertUTF.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. using namespace clang;
  53. //===----------------------------------------------------------------------===//
  54. ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
  55. Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
  56. DiagnosticsEngine &diags, LangOptions &opts,
  57. SourceManager &SM, HeaderSearch &Headers,
  58. ModuleLoader &TheModuleLoader,
  59. IdentifierInfoLookup *IILookup, bool OwnsHeaders,
  60. TranslationUnitKind TUKind)
  61. : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
  62. FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
  63. TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
  64. Identifiers(opts, IILookup), IncrementalProcessing(false), TUKind(TUKind),
  65. CodeComplete(nullptr), CodeCompletionFile(nullptr),
  66. CodeCompletionOffset(0), LastTokenWasAt(false),
  67. ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
  68. SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
  69. CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
  70. Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
  71. MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
  72. OwnsHeaderSearch = OwnsHeaders;
  73. ScratchBuf = new ScratchBuffer(SourceMgr);
  74. CounterValue = 0; // __COUNTER__ starts at 0.
  75. // Clear stats.
  76. NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
  77. NumIf = NumElse = NumEndif = 0;
  78. NumEnteredSourceFiles = 0;
  79. NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
  80. NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
  81. MaxIncludeStackDepth = 0;
  82. NumSkipped = 0;
  83. // Default to discarding comments.
  84. KeepComments = false;
  85. KeepMacroComments = false;
  86. SuppressIncludeNotFoundError = false;
  87. // Macro expansion is enabled.
  88. DisableMacroExpansion = false;
  89. MacroExpansionInDirectivesOverride = false;
  90. InMacroArgs = false;
  91. InMacroArgPreExpansion = false;
  92. NumCachedTokenLexers = 0;
  93. PragmasEnabled = true;
  94. ParsingIfOrElifDirective = false;
  95. PreprocessedOutput = false;
  96. CachedLexPos = 0;
  97. // We haven't read anything from the external source.
  98. ReadMacrosFromExternalSource = false;
  99. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
  100. // This gets unpoisoned where it is allowed.
  101. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  102. SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
  103. // Initialize the pragma handlers.
  104. PragmaHandlers = new PragmaNamespace(StringRef());
  105. RegisterBuiltinPragmas();
  106. // Initialize builtin macros like __LINE__ and friends.
  107. RegisterBuiltinMacros();
  108. if(LangOpts.Borland) {
  109. Ident__exception_info = getIdentifierInfo("_exception_info");
  110. Ident___exception_info = getIdentifierInfo("__exception_info");
  111. Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
  112. Ident__exception_code = getIdentifierInfo("_exception_code");
  113. Ident___exception_code = getIdentifierInfo("__exception_code");
  114. Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
  115. Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
  116. Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
  117. Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
  118. } else {
  119. Ident__exception_info = Ident__exception_code = nullptr;
  120. Ident__abnormal_termination = Ident___exception_info = nullptr;
  121. Ident___exception_code = Ident___abnormal_termination = nullptr;
  122. Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
  123. Ident_AbnormalTermination = nullptr;
  124. }
  125. }
  126. Preprocessor::~Preprocessor() {
  127. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  128. IncludeMacroStack.clear();
  129. // Destroy any macro definitions.
  130. while (MacroInfoChain *I = MIChainHead) {
  131. MIChainHead = I->Next;
  132. I->~MacroInfoChain();
  133. }
  134. // Free any cached macro expanders.
  135. // This populates MacroArgCache, so all TokenLexers need to be destroyed
  136. // before the code below that frees up the MacroArgCache list.
  137. for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
  138. delete TokenLexerCache[i];
  139. CurTokenLexer.reset();
  140. while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
  141. DeserialMIChainHead = I->Next;
  142. I->~DeserializedMacroInfoChain();
  143. }
  144. // Free any cached MacroArgs.
  145. for (MacroArgs *ArgList = MacroArgCache; ArgList;)
  146. ArgList = ArgList->deallocate();
  147. // Release pragma information.
  148. delete PragmaHandlers;
  149. // Delete the scratch buffer info.
  150. delete ScratchBuf;
  151. // Delete the header search info, if we own it.
  152. if (OwnsHeaderSearch)
  153. delete &HeaderInfo;
  154. delete Callbacks;
  155. }
  156. void Preprocessor::Initialize(const TargetInfo &Target) {
  157. assert((!this->Target || this->Target == &Target) &&
  158. "Invalid override of target information");
  159. this->Target = &Target;
  160. // Initialize information about built-ins.
  161. BuiltinInfo.InitializeTarget(Target);
  162. HeaderInfo.setTarget(Target);
  163. }
  164. void Preprocessor::InitializeForModelFile() {
  165. NumEnteredSourceFiles = 0;
  166. // Reset pragmas
  167. PragmaHandlersBackup = PragmaHandlers;
  168. PragmaHandlers = new PragmaNamespace(StringRef());
  169. RegisterBuiltinPragmas();
  170. // Reset PredefinesFileID
  171. PredefinesFileID = FileID();
  172. }
  173. void Preprocessor::FinalizeForModelFile() {
  174. NumEnteredSourceFiles = 1;
  175. delete PragmaHandlers;
  176. PragmaHandlers = PragmaHandlersBackup;
  177. }
  178. void Preprocessor::setPTHManager(PTHManager* pm) {
  179. PTH.reset(pm);
  180. FileMgr.addStatCache(PTH->createStatCache());
  181. }
  182. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  183. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  184. << getSpelling(Tok) << "'";
  185. if (!DumpFlags) return;
  186. llvm::errs() << "\t";
  187. if (Tok.isAtStartOfLine())
  188. llvm::errs() << " [StartOfLine]";
  189. if (Tok.hasLeadingSpace())
  190. llvm::errs() << " [LeadingSpace]";
  191. if (Tok.isExpandDisabled())
  192. llvm::errs() << " [ExpandDisabled]";
  193. if (Tok.needsCleaning()) {
  194. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  195. llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
  196. << "']";
  197. }
  198. llvm::errs() << "\tLoc=<";
  199. DumpLocation(Tok.getLocation());
  200. llvm::errs() << ">";
  201. }
  202. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  203. Loc.dump(SourceMgr);
  204. }
  205. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  206. llvm::errs() << "MACRO: ";
  207. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  208. DumpToken(MI.getReplacementToken(i));
  209. llvm::errs() << " ";
  210. }
  211. llvm::errs() << "\n";
  212. }
  213. void Preprocessor::PrintStats() {
  214. llvm::errs() << "\n*** Preprocessor Stats:\n";
  215. llvm::errs() << NumDirectives << " directives found:\n";
  216. llvm::errs() << " " << NumDefined << " #define.\n";
  217. llvm::errs() << " " << NumUndefined << " #undef.\n";
  218. llvm::errs() << " #include/#include_next/#import:\n";
  219. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  220. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  221. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  222. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  223. llvm::errs() << " " << NumEndif << " #endif.\n";
  224. llvm::errs() << " " << NumPragma << " #pragma.\n";
  225. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  226. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  227. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  228. << NumFastMacroExpanded << " on the fast path.\n";
  229. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  230. << " token paste (##) operations performed, "
  231. << NumFastTokenPaste << " on the fast path.\n";
  232. llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
  233. llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
  234. llvm::errs() << "\n Macro Expanded Tokens: "
  235. << llvm::capacity_in_bytes(MacroExpandedTokens);
  236. llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
  237. llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
  238. llvm::errs() << "\n #pragma push_macro Info: "
  239. << llvm::capacity_in_bytes(PragmaPushMacroInfo);
  240. llvm::errs() << "\n Poison Reasons: "
  241. << llvm::capacity_in_bytes(PoisonReasons);
  242. llvm::errs() << "\n Comment Handlers: "
  243. << llvm::capacity_in_bytes(CommentHandlers) << "\n";
  244. }
  245. Preprocessor::macro_iterator
  246. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  247. if (IncludeExternalMacros && ExternalSource &&
  248. !ReadMacrosFromExternalSource) {
  249. ReadMacrosFromExternalSource = true;
  250. ExternalSource->ReadDefinedMacros();
  251. }
  252. return Macros.begin();
  253. }
  254. size_t Preprocessor::getTotalMemory() const {
  255. return BP.getTotalMemory()
  256. + llvm::capacity_in_bytes(MacroExpandedTokens)
  257. + Predefines.capacity() /* Predefines buffer. */
  258. + llvm::capacity_in_bytes(Macros)
  259. + llvm::capacity_in_bytes(PragmaPushMacroInfo)
  260. + llvm::capacity_in_bytes(PoisonReasons)
  261. + llvm::capacity_in_bytes(CommentHandlers);
  262. }
  263. Preprocessor::macro_iterator
  264. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  265. if (IncludeExternalMacros && ExternalSource &&
  266. !ReadMacrosFromExternalSource) {
  267. ReadMacrosFromExternalSource = true;
  268. ExternalSource->ReadDefinedMacros();
  269. }
  270. return Macros.end();
  271. }
  272. /// \brief Compares macro tokens with a specified token value sequence.
  273. static bool MacroDefinitionEquals(const MacroInfo *MI,
  274. ArrayRef<TokenValue> Tokens) {
  275. return Tokens.size() == MI->getNumTokens() &&
  276. std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
  277. }
  278. StringRef Preprocessor::getLastMacroWithSpelling(
  279. SourceLocation Loc,
  280. ArrayRef<TokenValue> Tokens) const {
  281. SourceLocation BestLocation;
  282. StringRef BestSpelling;
  283. for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
  284. I != E; ++I) {
  285. if (!I->second->getMacroInfo()->isObjectLike())
  286. continue;
  287. const MacroDirective::DefInfo
  288. Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
  289. if (!Def)
  290. continue;
  291. if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
  292. continue;
  293. SourceLocation Location = Def.getLocation();
  294. // Choose the macro defined latest.
  295. if (BestLocation.isInvalid() ||
  296. (Location.isValid() &&
  297. SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
  298. BestLocation = Location;
  299. BestSpelling = I->first->getName();
  300. }
  301. }
  302. return BestSpelling;
  303. }
  304. void Preprocessor::recomputeCurLexerKind() {
  305. if (CurLexer)
  306. CurLexerKind = CLK_Lexer;
  307. else if (CurPTHLexer)
  308. CurLexerKind = CLK_PTHLexer;
  309. else if (CurTokenLexer)
  310. CurLexerKind = CLK_TokenLexer;
  311. else
  312. CurLexerKind = CLK_CachingLexer;
  313. }
  314. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  315. unsigned CompleteLine,
  316. unsigned CompleteColumn) {
  317. assert(File);
  318. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  319. assert(!CodeCompletionFile && "Already set");
  320. using llvm::MemoryBuffer;
  321. // Load the actual file's contents.
  322. bool Invalid = false;
  323. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  324. if (Invalid)
  325. return true;
  326. // Find the byte position of the truncation point.
  327. const char *Position = Buffer->getBufferStart();
  328. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  329. for (; *Position; ++Position) {
  330. if (*Position != '\r' && *Position != '\n')
  331. continue;
  332. // Eat \r\n or \n\r as a single line.
  333. if ((Position[1] == '\r' || Position[1] == '\n') &&
  334. Position[0] != Position[1])
  335. ++Position;
  336. ++Position;
  337. break;
  338. }
  339. }
  340. Position += CompleteColumn - 1;
  341. // Insert '\0' at the code-completion point.
  342. if (Position < Buffer->getBufferEnd()) {
  343. CodeCompletionFile = File;
  344. CodeCompletionOffset = Position - Buffer->getBufferStart();
  345. std::unique_ptr<MemoryBuffer> NewBuffer =
  346. MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
  347. Buffer->getBufferIdentifier());
  348. char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
  349. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  350. *NewPos = '\0';
  351. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  352. SourceMgr.overrideFileContents(File, std::move(NewBuffer));
  353. }
  354. return false;
  355. }
  356. void Preprocessor::CodeCompleteNaturalLanguage() {
  357. if (CodeComplete)
  358. CodeComplete->CodeCompleteNaturalLanguage();
  359. setCodeCompletionReached();
  360. }
  361. /// getSpelling - This method is used to get the spelling of a token into a
  362. /// SmallVector. Note that the returned StringRef may not point to the
  363. /// supplied buffer if a copy can be avoided.
  364. StringRef Preprocessor::getSpelling(const Token &Tok,
  365. SmallVectorImpl<char> &Buffer,
  366. bool *Invalid) const {
  367. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  368. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
  369. // Try the fast path.
  370. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  371. return II->getName();
  372. }
  373. // Resize the buffer if we need to copy into it.
  374. if (Tok.needsCleaning())
  375. Buffer.resize(Tok.getLength());
  376. const char *Ptr = Buffer.data();
  377. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  378. return StringRef(Ptr, Len);
  379. }
  380. /// CreateString - Plop the specified string into a scratch buffer and return a
  381. /// location for it. If specified, the source location provides a source
  382. /// location for the token.
  383. void Preprocessor::CreateString(StringRef Str, Token &Tok,
  384. SourceLocation ExpansionLocStart,
  385. SourceLocation ExpansionLocEnd) {
  386. Tok.setLength(Str.size());
  387. const char *DestPtr;
  388. SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
  389. if (ExpansionLocStart.isValid())
  390. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  391. ExpansionLocEnd, Str.size());
  392. Tok.setLocation(Loc);
  393. // If this is a raw identifier or a literal token, set the pointer data.
  394. if (Tok.is(tok::raw_identifier))
  395. Tok.setRawIdentifierData(DestPtr);
  396. else if (Tok.isLiteral())
  397. Tok.setLiteralData(DestPtr);
  398. }
  399. Module *Preprocessor::getCurrentModule() {
  400. if (getLangOpts().CurrentModule.empty())
  401. return nullptr;
  402. return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
  403. }
  404. //===----------------------------------------------------------------------===//
  405. // Preprocessor Initialization Methods
  406. //===----------------------------------------------------------------------===//
  407. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  408. /// which implicitly adds the builtin defines etc.
  409. void Preprocessor::EnterMainSourceFile() {
  410. // We do not allow the preprocessor to reenter the main file. Doing so will
  411. // cause FileID's to accumulate information from both runs (e.g. #line
  412. // information) and predefined macros aren't guaranteed to be set properly.
  413. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  414. FileID MainFileID = SourceMgr.getMainFileID();
  415. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  416. // a main file.
  417. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  418. // Enter the main file source buffer.
  419. EnterSourceFile(MainFileID, nullptr, SourceLocation());
  420. // If we've been asked to skip bytes in the main file (e.g., as part of a
  421. // precompiled preamble), do so now.
  422. if (SkipMainFilePreamble.first > 0)
  423. CurLexer->SkipBytes(SkipMainFilePreamble.first,
  424. SkipMainFilePreamble.second);
  425. // Tell the header info that the main file was entered. If the file is later
  426. // #imported, it won't be re-entered.
  427. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  428. HeaderInfo.IncrementIncludeCount(FE);
  429. }
  430. // Preprocess Predefines to populate the initial preprocessor state.
  431. std::unique_ptr<llvm::MemoryBuffer> SB =
  432. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  433. assert(SB && "Cannot create predefined source buffer");
  434. FileID FID = SourceMgr.createFileID(std::move(SB));
  435. assert(!FID.isInvalid() && "Could not create FileID for predefines?");
  436. setPredefinesFileID(FID);
  437. // Start parsing the predefines.
  438. EnterSourceFile(FID, nullptr, SourceLocation());
  439. }
  440. void Preprocessor::EndSourceFile() {
  441. // Notify the client that we reached the end of the source file.
  442. if (Callbacks)
  443. Callbacks->EndOfMainFile();
  444. }
  445. //===----------------------------------------------------------------------===//
  446. // Lexer Event Handling.
  447. //===----------------------------------------------------------------------===//
  448. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  449. /// identifier information for the token and install it into the token,
  450. /// updating the token kind accordingly.
  451. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  452. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  453. // Look up this token, see if it is a macro, or if it is a language keyword.
  454. IdentifierInfo *II;
  455. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  456. // No cleaning needed, just use the characters from the lexed buffer.
  457. II = getIdentifierInfo(Identifier.getRawIdentifier());
  458. } else {
  459. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  460. SmallString<64> IdentifierBuffer;
  461. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  462. if (Identifier.hasUCN()) {
  463. SmallString<64> UCNIdentifierBuffer;
  464. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  465. II = getIdentifierInfo(UCNIdentifierBuffer);
  466. } else {
  467. II = getIdentifierInfo(CleanedStr);
  468. }
  469. }
  470. // Update the token info (identifier info and appropriate token kind).
  471. Identifier.setIdentifierInfo(II);
  472. Identifier.setKind(II->getTokenID());
  473. return II;
  474. }
  475. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  476. PoisonReasons[II] = DiagID;
  477. }
  478. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  479. assert(Ident__exception_code && Ident__exception_info);
  480. assert(Ident___exception_code && Ident___exception_info);
  481. Ident__exception_code->setIsPoisoned(Poison);
  482. Ident___exception_code->setIsPoisoned(Poison);
  483. Ident_GetExceptionCode->setIsPoisoned(Poison);
  484. Ident__exception_info->setIsPoisoned(Poison);
  485. Ident___exception_info->setIsPoisoned(Poison);
  486. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  487. Ident__abnormal_termination->setIsPoisoned(Poison);
  488. Ident___abnormal_termination->setIsPoisoned(Poison);
  489. Ident_AbnormalTermination->setIsPoisoned(Poison);
  490. }
  491. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  492. assert(Identifier.getIdentifierInfo() &&
  493. "Can't handle identifiers without identifier info!");
  494. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  495. PoisonReasons.find(Identifier.getIdentifierInfo());
  496. if(it == PoisonReasons.end())
  497. Diag(Identifier, diag::err_pp_used_poisoned_id);
  498. else
  499. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  500. }
  501. /// HandleIdentifier - This callback is invoked when the lexer reads an
  502. /// identifier. This callback looks up the identifier in the map and/or
  503. /// potentially macro expands it or turns it into a named token (like 'for').
  504. ///
  505. /// Note that callers of this method are guarded by checking the
  506. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  507. /// IdentifierInfo methods that compute these properties will need to change to
  508. /// match.
  509. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  510. assert(Identifier.getIdentifierInfo() &&
  511. "Can't handle identifiers without identifier info!");
  512. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  513. // If the information about this identifier is out of date, update it from
  514. // the external source.
  515. // We have to treat __VA_ARGS__ in a special way, since it gets
  516. // serialized with isPoisoned = true, but our preprocessor may have
  517. // unpoisoned it if we're defining a C99 macro.
  518. if (II.isOutOfDate()) {
  519. bool CurrentIsPoisoned = false;
  520. if (&II == Ident__VA_ARGS__)
  521. CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
  522. ExternalSource->updateOutOfDateIdentifier(II);
  523. Identifier.setKind(II.getTokenID());
  524. if (&II == Ident__VA_ARGS__)
  525. II.setIsPoisoned(CurrentIsPoisoned);
  526. }
  527. // If this identifier was poisoned, and if it was not produced from a macro
  528. // expansion, emit an error.
  529. if (II.isPoisoned() && CurPPLexer) {
  530. HandlePoisonedIdentifier(Identifier);
  531. }
  532. // If this is a macro to be expanded, do it.
  533. if (MacroDirective *MD = getMacroDirective(&II)) {
  534. MacroInfo *MI = MD->getMacroInfo();
  535. if (!DisableMacroExpansion) {
  536. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  537. // C99 6.10.3p10: If the preprocessing token immediately after the
  538. // macro name isn't a '(', this macro should not be expanded.
  539. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  540. return HandleMacroExpandedIdentifier(Identifier, MD);
  541. } else {
  542. // C99 6.10.3.4p2 says that a disabled macro may never again be
  543. // expanded, even if it's in a context where it could be expanded in the
  544. // future.
  545. Identifier.setFlag(Token::DisableExpand);
  546. if (MI->isObjectLike() || isNextPPTokenLParen())
  547. Diag(Identifier, diag::pp_disabled_macro_expansion);
  548. }
  549. }
  550. }
  551. // If this identifier is a keyword in C++11, produce a warning. Don't warn if
  552. // we're not considering macro expansion, since this identifier might be the
  553. // name of a macro.
  554. // FIXME: This warning is disabled in cases where it shouldn't be, like
  555. // "#define constexpr constexpr", "int constexpr;"
  556. if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
  557. Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
  558. // Don't diagnose this keyword again in this translation unit.
  559. II.setIsCXX11CompatKeyword(false);
  560. }
  561. // C++ 2.11p2: If this is an alternative representation of a C++ operator,
  562. // then we act as if it is the actual operator and not the textual
  563. // representation of it.
  564. if (II.isCPlusPlusOperatorKeyword())
  565. Identifier.setIdentifierInfo(nullptr);
  566. // If this is an extension token, diagnose its use.
  567. // We avoid diagnosing tokens that originate from macro definitions.
  568. // FIXME: This warning is disabled in cases where it shouldn't be,
  569. // like "#define TY typeof", "TY(1) x".
  570. if (II.isExtensionToken() && !DisableMacroExpansion)
  571. Diag(Identifier, diag::ext_token_used);
  572. // If this is the 'import' contextual keyword following an '@', note
  573. // that the next token indicates a module name.
  574. //
  575. // Note that we do not treat 'import' as a contextual
  576. // keyword when we're in a caching lexer, because caching lexers only get
  577. // used in contexts where import declarations are disallowed.
  578. if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
  579. !DisableMacroExpansion && getLangOpts().Modules &&
  580. CurLexerKind != CLK_CachingLexer) {
  581. ModuleImportLoc = Identifier.getLocation();
  582. ModuleImportPath.clear();
  583. ModuleImportExpectsIdentifier = true;
  584. CurLexerKind = CLK_LexAfterModuleImport;
  585. }
  586. return true;
  587. }
  588. void Preprocessor::Lex(Token &Result) {
  589. // We loop here until a lex function retuns a token; this avoids recursion.
  590. bool ReturnedToken;
  591. do {
  592. switch (CurLexerKind) {
  593. case CLK_Lexer:
  594. ReturnedToken = CurLexer->Lex(Result);
  595. break;
  596. case CLK_PTHLexer:
  597. ReturnedToken = CurPTHLexer->Lex(Result);
  598. break;
  599. case CLK_TokenLexer:
  600. ReturnedToken = CurTokenLexer->Lex(Result);
  601. break;
  602. case CLK_CachingLexer:
  603. CachingLex(Result);
  604. ReturnedToken = true;
  605. break;
  606. case CLK_LexAfterModuleImport:
  607. LexAfterModuleImport(Result);
  608. ReturnedToken = true;
  609. break;
  610. }
  611. } while (!ReturnedToken);
  612. LastTokenWasAt = Result.is(tok::at);
  613. }
  614. /// \brief Lex a token following the 'import' contextual keyword.
  615. ///
  616. void Preprocessor::LexAfterModuleImport(Token &Result) {
  617. // Figure out what kind of lexer we actually have.
  618. recomputeCurLexerKind();
  619. // Lex the next token.
  620. Lex(Result);
  621. // The token sequence
  622. //
  623. // import identifier (. identifier)*
  624. //
  625. // indicates a module import directive. We already saw the 'import'
  626. // contextual keyword, so now we're looking for the identifiers.
  627. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  628. // We expected to see an identifier here, and we did; continue handling
  629. // identifiers.
  630. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  631. Result.getLocation()));
  632. ModuleImportExpectsIdentifier = false;
  633. CurLexerKind = CLK_LexAfterModuleImport;
  634. return;
  635. }
  636. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  637. // see the next identifier.
  638. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  639. ModuleImportExpectsIdentifier = true;
  640. CurLexerKind = CLK_LexAfterModuleImport;
  641. return;
  642. }
  643. // If we have a non-empty module path, load the named module.
  644. if (!ModuleImportPath.empty() && getLangOpts().Modules) {
  645. Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  646. ModuleImportPath,
  647. Module::MacrosVisible,
  648. /*IsIncludeDirective=*/false);
  649. if (Callbacks)
  650. Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
  651. }
  652. }
  653. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  654. const char *DiagnosticTag,
  655. bool AllowMacroExpansion) {
  656. // We need at least one string literal.
  657. if (Result.isNot(tok::string_literal)) {
  658. Diag(Result, diag::err_expected_string_literal)
  659. << /*Source='in...'*/0 << DiagnosticTag;
  660. return false;
  661. }
  662. // Lex string literal tokens, optionally with macro expansion.
  663. SmallVector<Token, 4> StrToks;
  664. do {
  665. StrToks.push_back(Result);
  666. if (Result.hasUDSuffix())
  667. Diag(Result, diag::err_invalid_string_udl);
  668. if (AllowMacroExpansion)
  669. Lex(Result);
  670. else
  671. LexUnexpandedToken(Result);
  672. } while (Result.is(tok::string_literal));
  673. // Concatenate and parse the strings.
  674. StringLiteralParser Literal(StrToks, *this);
  675. assert(Literal.isAscii() && "Didn't allow wide strings in");
  676. if (Literal.hadError)
  677. return false;
  678. if (Literal.Pascal) {
  679. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  680. << /*Source='in...'*/0 << DiagnosticTag;
  681. return false;
  682. }
  683. String = Literal.GetString();
  684. return true;
  685. }
  686. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  687. assert(Tok.is(tok::numeric_constant));
  688. SmallString<8> IntegerBuffer;
  689. bool NumberInvalid = false;
  690. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  691. if (NumberInvalid)
  692. return false;
  693. NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
  694. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  695. return false;
  696. llvm::APInt APVal(64, 0);
  697. if (Literal.GetIntegerValue(APVal))
  698. return false;
  699. Lex(Tok);
  700. Value = APVal.getLimitedValue();
  701. return true;
  702. }
  703. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  704. assert(Handler && "NULL comment handler");
  705. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  706. CommentHandlers.end() && "Comment handler already registered");
  707. CommentHandlers.push_back(Handler);
  708. }
  709. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  710. std::vector<CommentHandler *>::iterator Pos
  711. = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  712. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  713. CommentHandlers.erase(Pos);
  714. }
  715. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  716. bool AnyPendingTokens = false;
  717. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  718. HEnd = CommentHandlers.end();
  719. H != HEnd; ++H) {
  720. if ((*H)->HandleComment(*this, Comment))
  721. AnyPendingTokens = true;
  722. }
  723. if (!AnyPendingTokens || getCommentRetentionState())
  724. return false;
  725. Lex(result);
  726. return true;
  727. }
  728. ModuleLoader::~ModuleLoader() { }
  729. CommentHandler::~CommentHandler() { }
  730. CodeCompletionHandler::~CodeCompletionHandler() { }
  731. void Preprocessor::createPreprocessingRecord() {
  732. if (Record)
  733. return;
  734. Record = new PreprocessingRecord(getSourceManager());
  735. addPPCallbacks(Record);
  736. }