Preprocessor.cpp 25 KB

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