Preprocessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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/SmallVector.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. }
  147. void Preprocessor::setPTHManager(PTHManager* pm) {
  148. PTH.reset(pm);
  149. FileMgr.addStatCache(PTH->createStatCache());
  150. }
  151. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  152. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  153. << getSpelling(Tok) << "'";
  154. if (!DumpFlags) return;
  155. llvm::errs() << "\t";
  156. if (Tok.isAtStartOfLine())
  157. llvm::errs() << " [StartOfLine]";
  158. if (Tok.hasLeadingSpace())
  159. llvm::errs() << " [LeadingSpace]";
  160. if (Tok.isExpandDisabled())
  161. llvm::errs() << " [ExpandDisabled]";
  162. if (Tok.needsCleaning()) {
  163. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  164. llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
  165. << "']";
  166. }
  167. llvm::errs() << "\tLoc=<";
  168. DumpLocation(Tok.getLocation());
  169. llvm::errs() << ">";
  170. }
  171. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  172. Loc.dump(SourceMgr);
  173. }
  174. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  175. llvm::errs() << "MACRO: ";
  176. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  177. DumpToken(MI.getReplacementToken(i));
  178. llvm::errs() << " ";
  179. }
  180. llvm::errs() << "\n";
  181. }
  182. void Preprocessor::PrintStats() {
  183. llvm::errs() << "\n*** Preprocessor Stats:\n";
  184. llvm::errs() << NumDirectives << " directives found:\n";
  185. llvm::errs() << " " << NumDefined << " #define.\n";
  186. llvm::errs() << " " << NumUndefined << " #undef.\n";
  187. llvm::errs() << " #include/#include_next/#import:\n";
  188. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  189. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  190. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  191. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  192. llvm::errs() << " " << NumEndif << " #endif.\n";
  193. llvm::errs() << " " << NumPragma << " #pragma.\n";
  194. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  195. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  196. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  197. << NumFastMacroExpanded << " on the fast path.\n";
  198. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  199. << " token paste (##) operations performed, "
  200. << NumFastTokenPaste << " on the fast path.\n";
  201. }
  202. Preprocessor::macro_iterator
  203. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  204. if (IncludeExternalMacros && ExternalSource &&
  205. !ReadMacrosFromExternalSource) {
  206. ReadMacrosFromExternalSource = true;
  207. ExternalSource->ReadDefinedMacros();
  208. }
  209. return Macros.begin();
  210. }
  211. size_t Preprocessor::getTotalMemory() const {
  212. return BP.getTotalMemory()
  213. + llvm::capacity_in_bytes(MacroExpandedTokens)
  214. + Predefines.capacity() /* Predefines buffer. */
  215. + llvm::capacity_in_bytes(Macros)
  216. + llvm::capacity_in_bytes(PragmaPushMacroInfo)
  217. + llvm::capacity_in_bytes(PoisonReasons)
  218. + llvm::capacity_in_bytes(CommentHandlers);
  219. }
  220. Preprocessor::macro_iterator
  221. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  222. if (IncludeExternalMacros && ExternalSource &&
  223. !ReadMacrosFromExternalSource) {
  224. ReadMacrosFromExternalSource = true;
  225. ExternalSource->ReadDefinedMacros();
  226. }
  227. return Macros.end();
  228. }
  229. void Preprocessor::recomputeCurLexerKind() {
  230. if (CurLexer)
  231. CurLexerKind = CLK_Lexer;
  232. else if (CurPTHLexer)
  233. CurLexerKind = CLK_PTHLexer;
  234. else if (CurTokenLexer)
  235. CurLexerKind = CLK_TokenLexer;
  236. else
  237. CurLexerKind = CLK_CachingLexer;
  238. }
  239. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  240. unsigned CompleteLine,
  241. unsigned CompleteColumn) {
  242. assert(File);
  243. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  244. assert(!CodeCompletionFile && "Already set");
  245. using llvm::MemoryBuffer;
  246. // Load the actual file's contents.
  247. bool Invalid = false;
  248. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  249. if (Invalid)
  250. return true;
  251. // Find the byte position of the truncation point.
  252. const char *Position = Buffer->getBufferStart();
  253. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  254. for (; *Position; ++Position) {
  255. if (*Position != '\r' && *Position != '\n')
  256. continue;
  257. // Eat \r\n or \n\r as a single line.
  258. if ((Position[1] == '\r' || Position[1] == '\n') &&
  259. Position[0] != Position[1])
  260. ++Position;
  261. ++Position;
  262. break;
  263. }
  264. }
  265. Position += CompleteColumn - 1;
  266. // Insert '\0' at the code-completion point.
  267. if (Position < Buffer->getBufferEnd()) {
  268. CodeCompletionFile = File;
  269. CodeCompletionOffset = Position - Buffer->getBufferStart();
  270. MemoryBuffer *NewBuffer =
  271. MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
  272. Buffer->getBufferIdentifier());
  273. char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
  274. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  275. *NewPos = '\0';
  276. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  277. SourceMgr.overrideFileContents(File, NewBuffer);
  278. }
  279. return false;
  280. }
  281. void Preprocessor::CodeCompleteNaturalLanguage() {
  282. if (CodeComplete)
  283. CodeComplete->CodeCompleteNaturalLanguage();
  284. setCodeCompletionReached();
  285. }
  286. /// getSpelling - This method is used to get the spelling of a token into a
  287. /// SmallVector. Note that the returned StringRef may not point to the
  288. /// supplied buffer if a copy can be avoided.
  289. StringRef Preprocessor::getSpelling(const Token &Tok,
  290. SmallVectorImpl<char> &Buffer,
  291. bool *Invalid) const {
  292. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  293. if (Tok.isNot(tok::raw_identifier)) {
  294. // Try the fast path.
  295. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  296. return II->getName();
  297. }
  298. // Resize the buffer if we need to copy into it.
  299. if (Tok.needsCleaning())
  300. Buffer.resize(Tok.getLength());
  301. const char *Ptr = Buffer.data();
  302. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  303. return StringRef(Ptr, Len);
  304. }
  305. /// CreateString - Plop the specified string into a scratch buffer and return a
  306. /// location for it. If specified, the source location provides a source
  307. /// location for the token.
  308. void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
  309. SourceLocation ExpansionLocStart,
  310. SourceLocation ExpansionLocEnd) {
  311. Tok.setLength(Len);
  312. const char *DestPtr;
  313. SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
  314. if (ExpansionLocStart.isValid())
  315. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  316. ExpansionLocEnd, Len);
  317. Tok.setLocation(Loc);
  318. // If this is a raw identifier or a literal token, set the pointer data.
  319. if (Tok.is(tok::raw_identifier))
  320. Tok.setRawIdentifierData(DestPtr);
  321. else if (Tok.isLiteral())
  322. Tok.setLiteralData(DestPtr);
  323. }
  324. Module *Preprocessor::getCurrentModule() {
  325. if (getLangOptions().CurrentModule.empty())
  326. return 0;
  327. return getHeaderSearchInfo().getModule(getLangOptions().CurrentModule);
  328. }
  329. //===----------------------------------------------------------------------===//
  330. // Preprocessor Initialization Methods
  331. //===----------------------------------------------------------------------===//
  332. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  333. /// which implicitly adds the builtin defines etc.
  334. void Preprocessor::EnterMainSourceFile() {
  335. // We do not allow the preprocessor to reenter the main file. Doing so will
  336. // cause FileID's to accumulate information from both runs (e.g. #line
  337. // information) and predefined macros aren't guaranteed to be set properly.
  338. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  339. FileID MainFileID = SourceMgr.getMainFileID();
  340. // Enter the main file source buffer.
  341. EnterSourceFile(MainFileID, 0, SourceLocation());
  342. // If we've been asked to skip bytes in the main file (e.g., as part of a
  343. // precompiled preamble), do so now.
  344. if (SkipMainFilePreamble.first > 0)
  345. CurLexer->SkipBytes(SkipMainFilePreamble.first,
  346. SkipMainFilePreamble.second);
  347. // Tell the header info that the main file was entered. If the file is later
  348. // #imported, it won't be re-entered.
  349. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  350. HeaderInfo.IncrementIncludeCount(FE);
  351. // Preprocess Predefines to populate the initial preprocessor state.
  352. llvm::MemoryBuffer *SB =
  353. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  354. assert(SB && "Cannot create predefined source buffer");
  355. FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
  356. assert(!FID.isInvalid() && "Could not create FileID for predefines?");
  357. // Start parsing the predefines.
  358. EnterSourceFile(FID, 0, SourceLocation());
  359. }
  360. void Preprocessor::EndSourceFile() {
  361. // Notify the client that we reached the end of the source file.
  362. if (Callbacks)
  363. Callbacks->EndOfMainFile();
  364. }
  365. //===----------------------------------------------------------------------===//
  366. // Lexer Event Handling.
  367. //===----------------------------------------------------------------------===//
  368. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  369. /// identifier information for the token and install it into the token,
  370. /// updating the token kind accordingly.
  371. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  372. assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
  373. // Look up this token, see if it is a macro, or if it is a language keyword.
  374. IdentifierInfo *II;
  375. if (!Identifier.needsCleaning()) {
  376. // No cleaning needed, just use the characters from the lexed buffer.
  377. II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
  378. Identifier.getLength()));
  379. } else {
  380. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  381. llvm::SmallString<64> IdentifierBuffer;
  382. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  383. II = getIdentifierInfo(CleanedStr);
  384. }
  385. // Update the token info (identifier info and appropriate token kind).
  386. Identifier.setIdentifierInfo(II);
  387. Identifier.setKind(II->getTokenID());
  388. return II;
  389. }
  390. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  391. PoisonReasons[II] = DiagID;
  392. }
  393. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  394. assert(Ident__exception_code && Ident__exception_info);
  395. assert(Ident___exception_code && Ident___exception_info);
  396. Ident__exception_code->setIsPoisoned(Poison);
  397. Ident___exception_code->setIsPoisoned(Poison);
  398. Ident_GetExceptionCode->setIsPoisoned(Poison);
  399. Ident__exception_info->setIsPoisoned(Poison);
  400. Ident___exception_info->setIsPoisoned(Poison);
  401. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  402. Ident__abnormal_termination->setIsPoisoned(Poison);
  403. Ident___abnormal_termination->setIsPoisoned(Poison);
  404. Ident_AbnormalTermination->setIsPoisoned(Poison);
  405. }
  406. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  407. assert(Identifier.getIdentifierInfo() &&
  408. "Can't handle identifiers without identifier info!");
  409. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  410. PoisonReasons.find(Identifier.getIdentifierInfo());
  411. if(it == PoisonReasons.end())
  412. Diag(Identifier, diag::err_pp_used_poisoned_id);
  413. else
  414. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  415. }
  416. /// HandleIdentifier - This callback is invoked when the lexer reads an
  417. /// identifier. This callback looks up the identifier in the map and/or
  418. /// potentially macro expands it or turns it into a named token (like 'for').
  419. ///
  420. /// Note that callers of this method are guarded by checking the
  421. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  422. /// IdentifierInfo methods that compute these properties will need to change to
  423. /// match.
  424. void Preprocessor::HandleIdentifier(Token &Identifier) {
  425. assert(Identifier.getIdentifierInfo() &&
  426. "Can't handle identifiers without identifier info!");
  427. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  428. // If the information about this identifier is out of date, update it from
  429. // the external source.
  430. if (II.isOutOfDate()) {
  431. ExternalSource->updateOutOfDateIdentifier(II);
  432. Identifier.setKind(II.getTokenID());
  433. }
  434. // If this identifier was poisoned, and if it was not produced from a macro
  435. // expansion, emit an error.
  436. if (II.isPoisoned() && CurPPLexer) {
  437. HandlePoisonedIdentifier(Identifier);
  438. }
  439. // If this is a macro to be expanded, do it.
  440. if (MacroInfo *MI = getMacroInfo(&II)) {
  441. if (!DisableMacroExpansion) {
  442. if (Identifier.isExpandDisabled()) {
  443. Diag(Identifier, diag::pp_disabled_macro_expansion);
  444. } else if (MI->isEnabled()) {
  445. if (!HandleMacroExpandedIdentifier(Identifier, MI))
  446. return;
  447. } else {
  448. // C99 6.10.3.4p2 says that a disabled macro may never again be
  449. // expanded, even if it's in a context where it could be expanded in the
  450. // future.
  451. Identifier.setFlag(Token::DisableExpand);
  452. Diag(Identifier, diag::pp_disabled_macro_expansion);
  453. }
  454. }
  455. }
  456. // If this identifier is a keyword in C++11, produce a warning. Don't warn if
  457. // we're not considering macro expansion, since this identifier might be the
  458. // name of a macro.
  459. // FIXME: This warning is disabled in cases where it shouldn't be, like
  460. // "#define constexpr constexpr", "int constexpr;"
  461. if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
  462. Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
  463. // Don't diagnose this keyword again in this translation unit.
  464. II.setIsCXX11CompatKeyword(false);
  465. }
  466. // C++ 2.11p2: If this is an alternative representation of a C++ operator,
  467. // then we act as if it is the actual operator and not the textual
  468. // representation of it.
  469. if (II.isCPlusPlusOperatorKeyword())
  470. Identifier.setIdentifierInfo(0);
  471. // If this is an extension token, diagnose its use.
  472. // We avoid diagnosing tokens that originate from macro definitions.
  473. // FIXME: This warning is disabled in cases where it shouldn't be,
  474. // like "#define TY typeof", "TY(1) x".
  475. if (II.isExtensionToken() && !DisableMacroExpansion)
  476. Diag(Identifier, diag::ext_token_used);
  477. // If this is the 'import' contextual keyword, note that the next token
  478. // indicates a module name.
  479. //
  480. // Note that we do not treat 'import' as a contextual keyword when we're
  481. // in a caching lexer, because caching lexers only get used in contexts where
  482. // import declarations are disallowed.
  483. if (II.isImport() && !InMacroArgs && !DisableMacroExpansion &&
  484. getLangOptions().Modules && CurLexerKind != CLK_CachingLexer) {
  485. ModuleImportLoc = Identifier.getLocation();
  486. ModuleImportPath.clear();
  487. ModuleImportExpectsIdentifier = true;
  488. CurLexerKind = CLK_LexAfterModuleImport;
  489. }
  490. }
  491. /// \brief Lex a token following the 'import' contextual keyword.
  492. ///
  493. void Preprocessor::LexAfterModuleImport(Token &Result) {
  494. // Figure out what kind of lexer we actually have.
  495. recomputeCurLexerKind();
  496. // Lex the next token.
  497. Lex(Result);
  498. // The token sequence
  499. //
  500. // import identifier (. identifier)*
  501. //
  502. // indicates a module import directive. We already saw the 'import'
  503. // contextual keyword, so now we're looking for the identifiers.
  504. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  505. // We expected to see an identifier here, and we did; continue handling
  506. // identifiers.
  507. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  508. Result.getLocation()));
  509. ModuleImportExpectsIdentifier = false;
  510. CurLexerKind = CLK_LexAfterModuleImport;
  511. return;
  512. }
  513. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  514. // see the next identifier.
  515. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  516. ModuleImportExpectsIdentifier = true;
  517. CurLexerKind = CLK_LexAfterModuleImport;
  518. return;
  519. }
  520. // If we have a non-empty module path, load the named module.
  521. if (!ModuleImportPath.empty())
  522. (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath,
  523. Module::MacrosVisible,
  524. /*IsIncludeDirective=*/false);
  525. }
  526. void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
  527. assert(Handler && "NULL comment handler");
  528. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  529. CommentHandlers.end() && "Comment handler already registered");
  530. CommentHandlers.push_back(Handler);
  531. }
  532. void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
  533. std::vector<CommentHandler *>::iterator Pos
  534. = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  535. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  536. CommentHandlers.erase(Pos);
  537. }
  538. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  539. bool AnyPendingTokens = false;
  540. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  541. HEnd = CommentHandlers.end();
  542. H != HEnd; ++H) {
  543. if ((*H)->HandleComment(*this, Comment))
  544. AnyPendingTokens = true;
  545. }
  546. if (!AnyPendingTokens || getCommentRetentionState())
  547. return false;
  548. Lex(result);
  549. return true;
  550. }
  551. ModuleLoader::~ModuleLoader() { }
  552. CommentHandler::~CommentHandler() { }
  553. CodeCompletionHandler::~CodeCompletionHandler() { }
  554. void Preprocessor::createPreprocessingRecord(
  555. bool IncludeNestedMacroExpansions) {
  556. if (Record)
  557. return;
  558. Record = new PreprocessingRecord(getSourceManager(),
  559. IncludeNestedMacroExpansions);
  560. addPPCallbacks(Record);
  561. }