Preprocessor.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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/Basic/SourceManager.h"
  37. #include "clang/Basic/FileManager.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "llvm/ADT/APFloat.h"
  40. #include "llvm/ADT/SmallVector.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. using namespace clang;
  44. //===----------------------------------------------------------------------===//
  45. ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
  46. Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
  47. const TargetInfo &target, SourceManager &SM,
  48. HeaderSearch &Headers,
  49. IdentifierInfoLookup* IILookup,
  50. bool OwnsHeaders)
  51. : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
  52. SourceMgr(SM), HeaderInfo(Headers), ExternalSource(0),
  53. Identifiers(opts, IILookup), BuiltinInfo(Target), CodeCompletionFile(0),
  54. CurPPLexer(0), CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0) {
  55. ScratchBuf = new ScratchBuffer(SourceMgr);
  56. CounterValue = 0; // __COUNTER__ starts at 0.
  57. OwnsHeaderSearch = OwnsHeaders;
  58. // Clear stats.
  59. NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
  60. NumIf = NumElse = NumEndif = 0;
  61. NumEnteredSourceFiles = 0;
  62. NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
  63. NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
  64. MaxIncludeStackDepth = 0;
  65. NumSkipped = 0;
  66. // Default to discarding comments.
  67. KeepComments = false;
  68. KeepMacroComments = false;
  69. // Macro expansion is enabled.
  70. DisableMacroExpansion = false;
  71. InMacroArgs = false;
  72. NumCachedTokenLexers = 0;
  73. CachedLexPos = 0;
  74. // We haven't read anything from the external source.
  75. ReadMacrosFromExternalSource = false;
  76. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
  77. // This gets unpoisoned where it is allowed.
  78. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  79. // Initialize the pragma handlers.
  80. PragmaHandlers = new PragmaNamespace(0);
  81. RegisterBuiltinPragmas();
  82. // Initialize builtin macros like __LINE__ and friends.
  83. RegisterBuiltinMacros();
  84. }
  85. Preprocessor::~Preprocessor() {
  86. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  87. while (!IncludeMacroStack.empty()) {
  88. delete IncludeMacroStack.back().TheLexer;
  89. delete IncludeMacroStack.back().TheTokenLexer;
  90. IncludeMacroStack.pop_back();
  91. }
  92. // Free any macro definitions.
  93. for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
  94. Macros.begin(), E = Macros.end(); I != E; ++I) {
  95. // We don't need to free the MacroInfo objects directly. These
  96. // will be released when the BumpPtrAllocator 'BP' object gets
  97. // destroyed. We still need to run the dtor, however, to free
  98. // memory alocated by MacroInfo.
  99. I->second->Destroy(BP);
  100. I->first->setHasMacroDefinition(false);
  101. }
  102. // Free any cached macro expanders.
  103. for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
  104. delete TokenLexerCache[i];
  105. // Free any cached MacroArgs.
  106. for (MacroArgs *ArgList = MacroArgCache; ArgList; )
  107. ArgList = ArgList->deallocate();
  108. // Release pragma information.
  109. delete PragmaHandlers;
  110. // Delete the scratch buffer info.
  111. delete ScratchBuf;
  112. // Delete the header search info, if we own it.
  113. if (OwnsHeaderSearch)
  114. delete &HeaderInfo;
  115. delete Callbacks;
  116. }
  117. void Preprocessor::setPTHManager(PTHManager* pm) {
  118. PTH.reset(pm);
  119. FileMgr.addStatCache(PTH->createStatCache());
  120. }
  121. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  122. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  123. << getSpelling(Tok) << "'";
  124. if (!DumpFlags) return;
  125. llvm::errs() << "\t";
  126. if (Tok.isAtStartOfLine())
  127. llvm::errs() << " [StartOfLine]";
  128. if (Tok.hasLeadingSpace())
  129. llvm::errs() << " [LeadingSpace]";
  130. if (Tok.isExpandDisabled())
  131. llvm::errs() << " [ExpandDisabled]";
  132. if (Tok.needsCleaning()) {
  133. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  134. llvm::errs() << " [UnClean='" << std::string(Start, Start+Tok.getLength())
  135. << "']";
  136. }
  137. llvm::errs() << "\tLoc=<";
  138. DumpLocation(Tok.getLocation());
  139. llvm::errs() << ">";
  140. }
  141. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  142. Loc.dump(SourceMgr);
  143. }
  144. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  145. llvm::errs() << "MACRO: ";
  146. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  147. DumpToken(MI.getReplacementToken(i));
  148. llvm::errs() << " ";
  149. }
  150. llvm::errs() << "\n";
  151. }
  152. void Preprocessor::PrintStats() {
  153. llvm::errs() << "\n*** Preprocessor Stats:\n";
  154. llvm::errs() << NumDirectives << " directives found:\n";
  155. llvm::errs() << " " << NumDefined << " #define.\n";
  156. llvm::errs() << " " << NumUndefined << " #undef.\n";
  157. llvm::errs() << " #include/#include_next/#import:\n";
  158. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  159. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  160. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  161. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  162. llvm::errs() << " " << NumEndif << " #endif.\n";
  163. llvm::errs() << " " << NumPragma << " #pragma.\n";
  164. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  165. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  166. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  167. << NumFastMacroExpanded << " on the fast path.\n";
  168. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  169. << " token paste (##) operations performed, "
  170. << NumFastTokenPaste << " on the fast path.\n";
  171. }
  172. Preprocessor::macro_iterator
  173. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  174. if (IncludeExternalMacros && ExternalSource &&
  175. !ReadMacrosFromExternalSource) {
  176. ReadMacrosFromExternalSource = true;
  177. ExternalSource->ReadDefinedMacros();
  178. }
  179. return Macros.begin();
  180. }
  181. Preprocessor::macro_iterator
  182. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  183. if (IncludeExternalMacros && ExternalSource &&
  184. !ReadMacrosFromExternalSource) {
  185. ReadMacrosFromExternalSource = true;
  186. ExternalSource->ReadDefinedMacros();
  187. }
  188. return Macros.end();
  189. }
  190. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  191. unsigned TruncateAtLine,
  192. unsigned TruncateAtColumn) {
  193. using llvm::MemoryBuffer;
  194. CodeCompletionFile = File;
  195. // Okay to clear out the code-completion point by passing NULL.
  196. if (!CodeCompletionFile)
  197. return false;
  198. // Load the actual file's contents.
  199. bool Invalid = false;
  200. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  201. if (Invalid)
  202. return true;
  203. // Find the byte position of the truncation point.
  204. const char *Position = Buffer->getBufferStart();
  205. for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
  206. for (; *Position; ++Position) {
  207. if (*Position != '\r' && *Position != '\n')
  208. continue;
  209. // Eat \r\n or \n\r as a single line.
  210. if ((Position[1] == '\r' || Position[1] == '\n') &&
  211. Position[0] != Position[1])
  212. ++Position;
  213. ++Position;
  214. break;
  215. }
  216. }
  217. Position += TruncateAtColumn - 1;
  218. // Truncate the buffer.
  219. if (Position < Buffer->getBufferEnd()) {
  220. MemoryBuffer *TruncatedBuffer
  221. = MemoryBuffer::getMemBufferCopy(Buffer->getBufferStart(), Position,
  222. Buffer->getBufferIdentifier());
  223. SourceMgr.overrideFileContents(File, TruncatedBuffer);
  224. }
  225. return false;
  226. }
  227. bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
  228. return CodeCompletionFile && FileLoc.isFileID() &&
  229. SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
  230. == CodeCompletionFile;
  231. }
  232. //===----------------------------------------------------------------------===//
  233. // Token Spelling
  234. //===----------------------------------------------------------------------===//
  235. /// getSpelling() - Return the 'spelling' of this token. The spelling of a
  236. /// token are the characters used to represent the token in the source file
  237. /// after trigraph expansion and escaped-newline folding. In particular, this
  238. /// wants to get the true, uncanonicalized, spelling of things like digraphs
  239. /// UCNs, etc.
  240. std::string Preprocessor::getSpelling(const Token &Tok,
  241. const SourceManager &SourceMgr,
  242. const LangOptions &Features,
  243. bool *Invalid) {
  244. assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
  245. // If this token contains nothing interesting, return it directly.
  246. bool CharDataInvalid = false;
  247. const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
  248. &CharDataInvalid);
  249. if (Invalid)
  250. *Invalid = CharDataInvalid;
  251. if (CharDataInvalid)
  252. return std::string();
  253. if (!Tok.needsCleaning())
  254. return std::string(TokStart, TokStart+Tok.getLength());
  255. std::string Result;
  256. Result.reserve(Tok.getLength());
  257. // Otherwise, hard case, relex the characters into the string.
  258. for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
  259. Ptr != End; ) {
  260. unsigned CharSize;
  261. Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
  262. Ptr += CharSize;
  263. }
  264. assert(Result.size() != unsigned(Tok.getLength()) &&
  265. "NeedsCleaning flag set on something that didn't need cleaning!");
  266. return Result;
  267. }
  268. /// getSpelling() - Return the 'spelling' of this token. The spelling of a
  269. /// token are the characters used to represent the token in the source file
  270. /// after trigraph expansion and escaped-newline folding. In particular, this
  271. /// wants to get the true, uncanonicalized, spelling of things like digraphs
  272. /// UCNs, etc.
  273. std::string Preprocessor::getSpelling(const Token &Tok, bool *Invalid) const {
  274. return getSpelling(Tok, SourceMgr, Features, Invalid);
  275. }
  276. /// getSpelling - This method is used to get the spelling of a token into a
  277. /// preallocated buffer, instead of as an std::string. The caller is required
  278. /// to allocate enough space for the token, which is guaranteed to be at least
  279. /// Tok.getLength() bytes long. The actual length of the token is returned.
  280. ///
  281. /// Note that this method may do two possible things: it may either fill in
  282. /// the buffer specified with characters, or it may *change the input pointer*
  283. /// to point to a constant buffer with the data already in it (avoiding a
  284. /// copy). The caller is not allowed to modify the returned buffer pointer
  285. /// if an internal buffer is returned.
  286. unsigned Preprocessor::getSpelling(const Token &Tok,
  287. const char *&Buffer, bool *Invalid) const {
  288. assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
  289. // If this token is an identifier, just return the string from the identifier
  290. // table, which is very quick.
  291. if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
  292. Buffer = II->getNameStart();
  293. return II->getLength();
  294. }
  295. // Otherwise, compute the start of the token in the input lexer buffer.
  296. const char *TokStart = 0;
  297. if (Tok.isLiteral())
  298. TokStart = Tok.getLiteralData();
  299. if (TokStart == 0) {
  300. bool CharDataInvalid = false;
  301. TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
  302. if (Invalid)
  303. *Invalid = CharDataInvalid;
  304. if (CharDataInvalid) {
  305. Buffer = "";
  306. return 0;
  307. }
  308. }
  309. // If this token contains nothing interesting, return it directly.
  310. if (!Tok.needsCleaning()) {
  311. Buffer = TokStart;
  312. return Tok.getLength();
  313. }
  314. // Otherwise, hard case, relex the characters into the string.
  315. char *OutBuf = const_cast<char*>(Buffer);
  316. for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
  317. Ptr != End; ) {
  318. unsigned CharSize;
  319. *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
  320. Ptr += CharSize;
  321. }
  322. assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
  323. "NeedsCleaning flag set on something that didn't need cleaning!");
  324. return OutBuf-Buffer;
  325. }
  326. /// getSpelling - This method is used to get the spelling of a token into a
  327. /// SmallVector. Note that the returned StringRef may not point to the
  328. /// supplied buffer if a copy can be avoided.
  329. llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
  330. llvm::SmallVectorImpl<char> &Buffer,
  331. bool *Invalid) const {
  332. // Try the fast path.
  333. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  334. return II->getName();
  335. // Resize the buffer if we need to copy into it.
  336. if (Tok.needsCleaning())
  337. Buffer.resize(Tok.getLength());
  338. const char *Ptr = Buffer.data();
  339. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  340. return llvm::StringRef(Ptr, Len);
  341. }
  342. /// CreateString - Plop the specified string into a scratch buffer and return a
  343. /// location for it. If specified, the source location provides a source
  344. /// location for the token.
  345. void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
  346. SourceLocation InstantiationLoc) {
  347. Tok.setLength(Len);
  348. const char *DestPtr;
  349. SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
  350. if (InstantiationLoc.isValid())
  351. Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
  352. InstantiationLoc, Len);
  353. Tok.setLocation(Loc);
  354. // If this is a literal token, set the pointer data.
  355. if (Tok.isLiteral())
  356. Tok.setLiteralData(DestPtr);
  357. }
  358. /// AdvanceToTokenCharacter - Given a location that specifies the start of a
  359. /// token, return a new location that specifies a character within the token.
  360. SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
  361. unsigned CharNo) {
  362. // Figure out how many physical characters away the specified instantiation
  363. // character is. This needs to take into consideration newlines and
  364. // trigraphs.
  365. bool Invalid = false;
  366. const char *TokPtr = SourceMgr.getCharacterData(TokStart, &Invalid);
  367. // If they request the first char of the token, we're trivially done.
  368. if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
  369. return TokStart;
  370. unsigned PhysOffset = 0;
  371. // The usual case is that tokens don't contain anything interesting. Skip
  372. // over the uninteresting characters. If a token only consists of simple
  373. // chars, this method is extremely fast.
  374. while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
  375. if (CharNo == 0)
  376. return TokStart.getFileLocWithOffset(PhysOffset);
  377. ++TokPtr, --CharNo, ++PhysOffset;
  378. }
  379. // If we have a character that may be a trigraph or escaped newline, use a
  380. // lexer to parse it correctly.
  381. for (; CharNo; --CharNo) {
  382. unsigned Size;
  383. Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
  384. TokPtr += Size;
  385. PhysOffset += Size;
  386. }
  387. // Final detail: if we end up on an escaped newline, we want to return the
  388. // location of the actual byte of the token. For example foo\<newline>bar
  389. // advanced by 3 should return the location of b, not of \\. One compounding
  390. // detail of this is that the escape may be made by a trigraph.
  391. if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
  392. PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
  393. return TokStart.getFileLocWithOffset(PhysOffset);
  394. }
  395. SourceLocation Preprocessor::getLocForEndOfToken(SourceLocation Loc,
  396. unsigned Offset) {
  397. if (Loc.isInvalid() || !Loc.isFileID())
  398. return SourceLocation();
  399. unsigned Len = Lexer::MeasureTokenLength(Loc, getSourceManager(), Features);
  400. if (Len > Offset)
  401. Len = Len - Offset;
  402. else
  403. return Loc;
  404. return AdvanceToTokenCharacter(Loc, Len);
  405. }
  406. //===----------------------------------------------------------------------===//
  407. // Preprocessor Initialization Methods
  408. //===----------------------------------------------------------------------===//
  409. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  410. /// which implicitly adds the builtin defines etc.
  411. bool Preprocessor::EnterMainSourceFile() {
  412. // We do not allow the preprocessor to reenter the main file. Doing so will
  413. // cause FileID's to accumulate information from both runs (e.g. #line
  414. // information) and predefined macros aren't guaranteed to be set properly.
  415. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  416. FileID MainFileID = SourceMgr.getMainFileID();
  417. // Enter the main file source buffer.
  418. std::string ErrorStr;
  419. if (EnterSourceFile(MainFileID, 0, ErrorStr))
  420. return true;
  421. // Tell the header info that the main file was entered. If the file is later
  422. // #imported, it won't be re-entered.
  423. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  424. HeaderInfo.IncrementIncludeCount(FE);
  425. // Preprocess Predefines to populate the initial preprocessor state.
  426. llvm::MemoryBuffer *SB =
  427. llvm::MemoryBuffer::getMemBufferCopy(Predefines.data(),
  428. Predefines.data() + Predefines.size(),
  429. "<built-in>");
  430. assert(SB && "Cannot fail to create predefined source buffer");
  431. FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
  432. assert(!FID.isInvalid() && "Could not create FileID for predefines?");
  433. // Start parsing the predefines.
  434. return EnterSourceFile(FID, 0, ErrorStr);
  435. }
  436. void Preprocessor::EndSourceFile() {
  437. // Notify the client that we reached the end of the source file.
  438. if (Callbacks)
  439. Callbacks->EndOfMainFile();
  440. }
  441. //===----------------------------------------------------------------------===//
  442. // Lexer Event Handling.
  443. //===----------------------------------------------------------------------===//
  444. /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
  445. /// identifier information for the token and install it into the token.
  446. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
  447. const char *BufPtr) const {
  448. assert(Identifier.is(tok::identifier) && "Not an identifier!");
  449. assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
  450. // Look up this token, see if it is a macro, or if it is a language keyword.
  451. IdentifierInfo *II;
  452. if (BufPtr && !Identifier.needsCleaning()) {
  453. // No cleaning needed, just use the characters from the lexed buffer.
  454. II = getIdentifierInfo(llvm::StringRef(BufPtr, Identifier.getLength()));
  455. } else {
  456. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  457. llvm::SmallString<64> IdentifierBuffer;
  458. llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  459. II = getIdentifierInfo(CleanedStr);
  460. }
  461. Identifier.setIdentifierInfo(II);
  462. return II;
  463. }
  464. /// HandleIdentifier - This callback is invoked when the lexer reads an
  465. /// identifier. This callback looks up the identifier in the map and/or
  466. /// potentially macro expands it or turns it into a named token (like 'for').
  467. ///
  468. /// Note that callers of this method are guarded by checking the
  469. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  470. /// IdentifierInfo methods that compute these properties will need to change to
  471. /// match.
  472. void Preprocessor::HandleIdentifier(Token &Identifier) {
  473. assert(Identifier.getIdentifierInfo() &&
  474. "Can't handle identifiers without identifier info!");
  475. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  476. // If this identifier was poisoned, and if it was not produced from a macro
  477. // expansion, emit an error.
  478. if (II.isPoisoned() && CurPPLexer) {
  479. if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
  480. Diag(Identifier, diag::err_pp_used_poisoned_id);
  481. else
  482. Diag(Identifier, diag::ext_pp_bad_vaargs_use);
  483. }
  484. // If this is a macro to be expanded, do it.
  485. if (MacroInfo *MI = getMacroInfo(&II)) {
  486. if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
  487. if (MI->isEnabled()) {
  488. if (!HandleMacroExpandedIdentifier(Identifier, MI))
  489. return;
  490. } else {
  491. // C99 6.10.3.4p2 says that a disabled macro may never again be
  492. // expanded, even if it's in a context where it could be expanded in the
  493. // future.
  494. Identifier.setFlag(Token::DisableExpand);
  495. }
  496. }
  497. }
  498. // C++ 2.11p2: If this is an alternative representation of a C++ operator,
  499. // then we act as if it is the actual operator and not the textual
  500. // representation of it.
  501. if (II.isCPlusPlusOperatorKeyword())
  502. Identifier.setIdentifierInfo(0);
  503. // If this is an extension token, diagnose its use.
  504. // We avoid diagnosing tokens that originate from macro definitions.
  505. // FIXME: This warning is disabled in cases where it shouldn't be,
  506. // like "#define TY typeof", "TY(1) x".
  507. if (II.isExtensionToken() && !DisableMacroExpansion)
  508. Diag(Identifier, diag::ext_token_used);
  509. }
  510. void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
  511. assert(Handler && "NULL comment handler");
  512. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  513. CommentHandlers.end() && "Comment handler already registered");
  514. CommentHandlers.push_back(Handler);
  515. }
  516. void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
  517. std::vector<CommentHandler *>::iterator Pos
  518. = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  519. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  520. CommentHandlers.erase(Pos);
  521. }
  522. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  523. bool AnyPendingTokens = false;
  524. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  525. HEnd = CommentHandlers.end();
  526. H != HEnd; ++H) {
  527. if ((*H)->HandleComment(*this, Comment))
  528. AnyPendingTokens = true;
  529. }
  530. if (!AnyPendingTokens || getCommentRetentionState())
  531. return false;
  532. Lex(result);
  533. return true;
  534. }
  535. CommentHandler::~CommentHandler() { }
  536. void Preprocessor::createPreprocessingRecord() {
  537. if (Record)
  538. return;
  539. Record = new PreprocessingRecord;
  540. addPPCallbacks(Record);
  541. }