Preprocessor.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 "MacroArgs.h"
  29. #include "clang/Lex/ExternalPreprocessorSource.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/MacroInfo.h"
  32. #include "clang/Lex/Pragma.h"
  33. #include "clang/Lex/PreprocessingRecord.h"
  34. #include "clang/Lex/ScratchBuffer.h"
  35. #include "clang/Lex/LexDiagnostic.h"
  36. #include "clang/Lex/CodeCompletionHandler.h"
  37. #include "clang/Basic/SourceManager.h"
  38. #include "clang/Basic/FileManager.h"
  39. #include "clang/Basic/TargetInfo.h"
  40. #include "llvm/ADT/APFloat.h"
  41. #include "llvm/ADT/SmallVector.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. using namespace clang;
  45. //===----------------------------------------------------------------------===//
  46. ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
  47. Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
  48. const TargetInfo &target, SourceManager &SM,
  49. HeaderSearch &Headers,
  50. IdentifierInfoLookup* IILookup,
  51. bool OwnsHeaders)
  52. : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
  53. SourceMgr(SM),
  54. HeaderInfo(Headers), ExternalSource(0),
  55. Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
  56. CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
  57. CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
  58. MICache(0) {
  59. ScratchBuf = new ScratchBuffer(SourceMgr);
  60. CounterValue = 0; // __COUNTER__ starts at 0.
  61. OwnsHeaderSearch = OwnsHeaders;
  62. // Clear stats.
  63. NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
  64. NumIf = NumElse = NumEndif = 0;
  65. NumEnteredSourceFiles = 0;
  66. NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
  67. NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
  68. MaxIncludeStackDepth = 0;
  69. NumSkipped = 0;
  70. // Default to discarding comments.
  71. KeepComments = false;
  72. KeepMacroComments = false;
  73. // Macro expansion is enabled.
  74. DisableMacroExpansion = false;
  75. InMacroArgs = false;
  76. NumCachedTokenLexers = 0;
  77. CachedLexPos = 0;
  78. // We haven't read anything from the external source.
  79. ReadMacrosFromExternalSource = false;
  80. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
  81. // This gets unpoisoned where it is allowed.
  82. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  83. // Initialize the pragma handlers.
  84. PragmaHandlers = new PragmaNamespace(llvm::StringRef());
  85. RegisterBuiltinPragmas();
  86. // Initialize builtin macros like __LINE__ and friends.
  87. RegisterBuiltinMacros();
  88. }
  89. Preprocessor::~Preprocessor() {
  90. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  91. while (!IncludeMacroStack.empty()) {
  92. delete IncludeMacroStack.back().TheLexer;
  93. delete IncludeMacroStack.back().TheTokenLexer;
  94. IncludeMacroStack.pop_back();
  95. }
  96. // Free any macro definitions.
  97. for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
  98. I->MI.Destroy();
  99. // Free any cached macro expanders.
  100. for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
  101. delete TokenLexerCache[i];
  102. // Free any cached MacroArgs.
  103. for (MacroArgs *ArgList = MacroArgCache; ArgList; )
  104. ArgList = ArgList->deallocate();
  105. // Release pragma information.
  106. delete PragmaHandlers;
  107. // Delete the scratch buffer info.
  108. delete ScratchBuf;
  109. // Delete the header search info, if we own it.
  110. if (OwnsHeaderSearch)
  111. delete &HeaderInfo;
  112. delete Callbacks;
  113. }
  114. void Preprocessor::setPTHManager(PTHManager* pm) {
  115. PTH.reset(pm);
  116. FileMgr.addStatCache(PTH->createStatCache());
  117. }
  118. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  119. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  120. << getSpelling(Tok) << "'";
  121. if (!DumpFlags) return;
  122. llvm::errs() << "\t";
  123. if (Tok.isAtStartOfLine())
  124. llvm::errs() << " [StartOfLine]";
  125. if (Tok.hasLeadingSpace())
  126. llvm::errs() << " [LeadingSpace]";
  127. if (Tok.isExpandDisabled())
  128. llvm::errs() << " [ExpandDisabled]";
  129. if (Tok.needsCleaning()) {
  130. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  131. llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
  132. << "']";
  133. }
  134. llvm::errs() << "\tLoc=<";
  135. DumpLocation(Tok.getLocation());
  136. llvm::errs() << ">";
  137. }
  138. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  139. Loc.dump(SourceMgr);
  140. }
  141. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  142. llvm::errs() << "MACRO: ";
  143. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  144. DumpToken(MI.getReplacementToken(i));
  145. llvm::errs() << " ";
  146. }
  147. llvm::errs() << "\n";
  148. }
  149. void Preprocessor::PrintStats() {
  150. llvm::errs() << "\n*** Preprocessor Stats:\n";
  151. llvm::errs() << NumDirectives << " directives found:\n";
  152. llvm::errs() << " " << NumDefined << " #define.\n";
  153. llvm::errs() << " " << NumUndefined << " #undef.\n";
  154. llvm::errs() << " #include/#include_next/#import:\n";
  155. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  156. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  157. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  158. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  159. llvm::errs() << " " << NumEndif << " #endif.\n";
  160. llvm::errs() << " " << NumPragma << " #pragma.\n";
  161. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  162. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  163. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  164. << NumFastMacroExpanded << " on the fast path.\n";
  165. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  166. << " token paste (##) operations performed, "
  167. << NumFastTokenPaste << " on the fast path.\n";
  168. }
  169. Preprocessor::macro_iterator
  170. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  171. if (IncludeExternalMacros && ExternalSource &&
  172. !ReadMacrosFromExternalSource) {
  173. ReadMacrosFromExternalSource = true;
  174. ExternalSource->ReadDefinedMacros();
  175. }
  176. return Macros.begin();
  177. }
  178. Preprocessor::macro_iterator
  179. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  180. if (IncludeExternalMacros && ExternalSource &&
  181. !ReadMacrosFromExternalSource) {
  182. ReadMacrosFromExternalSource = true;
  183. ExternalSource->ReadDefinedMacros();
  184. }
  185. return Macros.end();
  186. }
  187. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  188. unsigned TruncateAtLine,
  189. unsigned TruncateAtColumn) {
  190. using llvm::MemoryBuffer;
  191. CodeCompletionFile = File;
  192. // Okay to clear out the code-completion point by passing NULL.
  193. if (!CodeCompletionFile)
  194. return false;
  195. // Load the actual file's contents.
  196. bool Invalid = false;
  197. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  198. if (Invalid)
  199. return true;
  200. // Find the byte position of the truncation point.
  201. const char *Position = Buffer->getBufferStart();
  202. for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
  203. for (; *Position; ++Position) {
  204. if (*Position != '\r' && *Position != '\n')
  205. continue;
  206. // Eat \r\n or \n\r as a single line.
  207. if ((Position[1] == '\r' || Position[1] == '\n') &&
  208. Position[0] != Position[1])
  209. ++Position;
  210. ++Position;
  211. break;
  212. }
  213. }
  214. Position += TruncateAtColumn - 1;
  215. // Truncate the buffer.
  216. if (Position < Buffer->getBufferEnd()) {
  217. llvm::StringRef Data(Buffer->getBufferStart(),
  218. Position-Buffer->getBufferStart());
  219. MemoryBuffer *TruncatedBuffer
  220. = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
  221. SourceMgr.overrideFileContents(File, TruncatedBuffer);
  222. }
  223. return false;
  224. }
  225. bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
  226. return CodeCompletionFile && FileLoc.isFileID() &&
  227. SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
  228. == CodeCompletionFile;
  229. }
  230. void Preprocessor::CodeCompleteNaturalLanguage() {
  231. SetCodeCompletionPoint(0, 0, 0);
  232. getDiagnostics().setSuppressAllDiagnostics(true);
  233. if (CodeComplete)
  234. CodeComplete->CodeCompleteNaturalLanguage();
  235. }
  236. /// getSpelling - This method is used to get the spelling of a token into a
  237. /// SmallVector. Note that the returned StringRef may not point to the
  238. /// supplied buffer if a copy can be avoided.
  239. llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
  240. llvm::SmallVectorImpl<char> &Buffer,
  241. bool *Invalid) const {
  242. // Try the fast path.
  243. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  244. return II->getName();
  245. // Resize the buffer if we need to copy into it.
  246. if (Tok.needsCleaning())
  247. Buffer.resize(Tok.getLength());
  248. const char *Ptr = Buffer.data();
  249. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  250. return llvm::StringRef(Ptr, Len);
  251. }
  252. /// CreateString - Plop the specified string into a scratch buffer and return a
  253. /// location for it. If specified, the source location provides a source
  254. /// location for the token.
  255. void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
  256. SourceLocation InstantiationLoc) {
  257. Tok.setLength(Len);
  258. const char *DestPtr;
  259. SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
  260. if (InstantiationLoc.isValid())
  261. Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
  262. InstantiationLoc, Len);
  263. Tok.setLocation(Loc);
  264. // If this is a literal token, set the pointer data.
  265. if (Tok.isLiteral())
  266. Tok.setLiteralData(DestPtr);
  267. }
  268. //===----------------------------------------------------------------------===//
  269. // Preprocessor Initialization Methods
  270. //===----------------------------------------------------------------------===//
  271. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  272. /// which implicitly adds the builtin defines etc.
  273. void Preprocessor::EnterMainSourceFile() {
  274. // We do not allow the preprocessor to reenter the main file. Doing so will
  275. // cause FileID's to accumulate information from both runs (e.g. #line
  276. // information) and predefined macros aren't guaranteed to be set properly.
  277. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  278. FileID MainFileID = SourceMgr.getMainFileID();
  279. // Enter the main file source buffer.
  280. EnterSourceFile(MainFileID, 0, SourceLocation());
  281. // If we've been asked to skip bytes in the main file (e.g., as part of a
  282. // precompiled preamble), do so now.
  283. if (SkipMainFilePreamble.first > 0)
  284. CurLexer->SkipBytes(SkipMainFilePreamble.first,
  285. SkipMainFilePreamble.second);
  286. // Tell the header info that the main file was entered. If the file is later
  287. // #imported, it won't be re-entered.
  288. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  289. HeaderInfo.IncrementIncludeCount(FE);
  290. // Preprocess Predefines to populate the initial preprocessor state.
  291. llvm::MemoryBuffer *SB =
  292. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  293. assert(SB && "Cannot create predefined source buffer");
  294. FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
  295. assert(!FID.isInvalid() && "Could not create FileID for predefines?");
  296. // Start parsing the predefines.
  297. EnterSourceFile(FID, 0, SourceLocation());
  298. }
  299. void Preprocessor::EndSourceFile() {
  300. // Notify the client that we reached the end of the source file.
  301. if (Callbacks)
  302. Callbacks->EndOfMainFile();
  303. }
  304. //===----------------------------------------------------------------------===//
  305. // Lexer Event Handling.
  306. //===----------------------------------------------------------------------===//
  307. /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
  308. /// identifier information for the token and install it into the token.
  309. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
  310. const char *BufPtr) const {
  311. assert(Identifier.is(tok::identifier) && "Not an identifier!");
  312. assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
  313. // Look up this token, see if it is a macro, or if it is a language keyword.
  314. IdentifierInfo *II;
  315. if (BufPtr && !Identifier.needsCleaning()) {
  316. // No cleaning needed, just use the characters from the lexed buffer.
  317. II = getIdentifierInfo(llvm::StringRef(BufPtr, Identifier.getLength()));
  318. } else {
  319. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  320. llvm::SmallString<64> IdentifierBuffer;
  321. llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  322. II = getIdentifierInfo(CleanedStr);
  323. }
  324. Identifier.setIdentifierInfo(II);
  325. return II;
  326. }
  327. /// HandleIdentifier - This callback is invoked when the lexer reads an
  328. /// identifier. This callback looks up the identifier in the map and/or
  329. /// potentially macro expands it or turns it into a named token (like 'for').
  330. ///
  331. /// Note that callers of this method are guarded by checking the
  332. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  333. /// IdentifierInfo methods that compute these properties will need to change to
  334. /// match.
  335. void Preprocessor::HandleIdentifier(Token &Identifier) {
  336. assert(Identifier.getIdentifierInfo() &&
  337. "Can't handle identifiers without identifier info!");
  338. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  339. // If this identifier was poisoned, and if it was not produced from a macro
  340. // expansion, emit an error.
  341. if (II.isPoisoned() && CurPPLexer) {
  342. if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
  343. Diag(Identifier, diag::err_pp_used_poisoned_id);
  344. else
  345. Diag(Identifier, diag::ext_pp_bad_vaargs_use);
  346. }
  347. // If this is a macro to be expanded, do it.
  348. if (MacroInfo *MI = getMacroInfo(&II)) {
  349. if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
  350. if (MI->isEnabled()) {
  351. if (!HandleMacroExpandedIdentifier(Identifier, MI))
  352. return;
  353. } else {
  354. // C99 6.10.3.4p2 says that a disabled macro may never again be
  355. // expanded, even if it's in a context where it could be expanded in the
  356. // future.
  357. Identifier.setFlag(Token::DisableExpand);
  358. }
  359. }
  360. }
  361. // C++ 2.11p2: If this is an alternative representation of a C++ operator,
  362. // then we act as if it is the actual operator and not the textual
  363. // representation of it.
  364. if (II.isCPlusPlusOperatorKeyword())
  365. Identifier.setIdentifierInfo(0);
  366. // If this is an extension token, diagnose its use.
  367. // We avoid diagnosing tokens that originate from macro definitions.
  368. // FIXME: This warning is disabled in cases where it shouldn't be,
  369. // like "#define TY typeof", "TY(1) x".
  370. if (II.isExtensionToken() && !DisableMacroExpansion)
  371. Diag(Identifier, diag::ext_token_used);
  372. }
  373. void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
  374. assert(Handler && "NULL comment handler");
  375. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  376. CommentHandlers.end() && "Comment handler already registered");
  377. CommentHandlers.push_back(Handler);
  378. }
  379. void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
  380. std::vector<CommentHandler *>::iterator Pos
  381. = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  382. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  383. CommentHandlers.erase(Pos);
  384. }
  385. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  386. bool AnyPendingTokens = false;
  387. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  388. HEnd = CommentHandlers.end();
  389. H != HEnd; ++H) {
  390. if ((*H)->HandleComment(*this, Comment))
  391. AnyPendingTokens = true;
  392. }
  393. if (!AnyPendingTokens || getCommentRetentionState())
  394. return false;
  395. Lex(result);
  396. return true;
  397. }
  398. CommentHandler::~CommentHandler() { }
  399. CodeCompletionHandler::~CodeCompletionHandler() { }
  400. void Preprocessor::createPreprocessingRecord() {
  401. if (Record)
  402. return;
  403. Record = new PreprocessingRecord;
  404. addPPCallbacks(Record);
  405. }