Preprocessor.cpp 24 KB

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