Preprocessor.cpp 30 KB

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