Preprocessor.cpp 30 KB

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