Preprocessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. /// getSpelling - This method is used to get the spelling of a token into a
  288. /// SmallVector. Note that the returned StringRef may not point to the
  289. /// supplied buffer if a copy can be avoided.
  290. StringRef Preprocessor::getSpelling(const Token &Tok,
  291. SmallVectorImpl<char> &Buffer,
  292. bool *Invalid) const {
  293. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  294. if (Tok.isNot(tok::raw_identifier)) {
  295. // Try the fast path.
  296. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  297. return II->getName();
  298. }
  299. // Resize the buffer if we need to copy into it.
  300. if (Tok.needsCleaning())
  301. Buffer.resize(Tok.getLength());
  302. const char *Ptr = Buffer.data();
  303. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  304. return StringRef(Ptr, Len);
  305. }
  306. /// CreateString - Plop the specified string into a scratch buffer and return a
  307. /// location for it. If specified, the source location provides a source
  308. /// location for the token.
  309. void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
  310. SourceLocation ExpansionLocStart,
  311. SourceLocation ExpansionLocEnd) {
  312. Tok.setLength(Len);
  313. const char *DestPtr;
  314. SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
  315. if (ExpansionLocStart.isValid())
  316. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  317. ExpansionLocEnd, Len);
  318. Tok.setLocation(Loc);
  319. // If this is a raw identifier or a literal token, set the pointer data.
  320. if (Tok.is(tok::raw_identifier))
  321. Tok.setRawIdentifierData(DestPtr);
  322. else if (Tok.isLiteral())
  323. Tok.setLiteralData(DestPtr);
  324. }
  325. Module *Preprocessor::getCurrentModule() {
  326. if (getLangOptions().CurrentModule.empty())
  327. return 0;
  328. return getHeaderSearchInfo().lookupModule(getLangOptions().CurrentModule);
  329. }
  330. //===----------------------------------------------------------------------===//
  331. // Preprocessor Initialization Methods
  332. //===----------------------------------------------------------------------===//
  333. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  334. /// which implicitly adds the builtin defines etc.
  335. void Preprocessor::EnterMainSourceFile() {
  336. // We do not allow the preprocessor to reenter the main file. Doing so will
  337. // cause FileID's to accumulate information from both runs (e.g. #line
  338. // information) and predefined macros aren't guaranteed to be set properly.
  339. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  340. FileID MainFileID = SourceMgr.getMainFileID();
  341. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  342. // a main file.
  343. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  344. // Enter the main file source buffer.
  345. EnterSourceFile(MainFileID, 0, SourceLocation());
  346. // If we've been asked to skip bytes in the main file (e.g., as part of a
  347. // precompiled preamble), do so now.
  348. if (SkipMainFilePreamble.first > 0)
  349. CurLexer->SkipBytes(SkipMainFilePreamble.first,
  350. SkipMainFilePreamble.second);
  351. // Tell the header info that the main file was entered. If the file is later
  352. // #imported, it won't be re-entered.
  353. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  354. HeaderInfo.IncrementIncludeCount(FE);
  355. }
  356. // Preprocess Predefines to populate the initial preprocessor state.
  357. llvm::MemoryBuffer *SB =
  358. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  359. assert(SB && "Cannot create predefined source buffer");
  360. FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
  361. assert(!FID.isInvalid() && "Could not create FileID for predefines?");
  362. // Start parsing the predefines.
  363. EnterSourceFile(FID, 0, SourceLocation());
  364. }
  365. void Preprocessor::EndSourceFile() {
  366. // Notify the client that we reached the end of the source file.
  367. if (Callbacks)
  368. Callbacks->EndOfMainFile();
  369. }
  370. //===----------------------------------------------------------------------===//
  371. // Lexer Event Handling.
  372. //===----------------------------------------------------------------------===//
  373. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  374. /// identifier information for the token and install it into the token,
  375. /// updating the token kind accordingly.
  376. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  377. assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
  378. // Look up this token, see if it is a macro, or if it is a language keyword.
  379. IdentifierInfo *II;
  380. if (!Identifier.needsCleaning()) {
  381. // No cleaning needed, just use the characters from the lexed buffer.
  382. II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
  383. Identifier.getLength()));
  384. } else {
  385. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  386. SmallString<64> IdentifierBuffer;
  387. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  388. II = getIdentifierInfo(CleanedStr);
  389. }
  390. // Update the token info (identifier info and appropriate token kind).
  391. Identifier.setIdentifierInfo(II);
  392. Identifier.setKind(II->getTokenID());
  393. return II;
  394. }
  395. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  396. PoisonReasons[II] = DiagID;
  397. }
  398. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  399. assert(Ident__exception_code && Ident__exception_info);
  400. assert(Ident___exception_code && Ident___exception_info);
  401. Ident__exception_code->setIsPoisoned(Poison);
  402. Ident___exception_code->setIsPoisoned(Poison);
  403. Ident_GetExceptionCode->setIsPoisoned(Poison);
  404. Ident__exception_info->setIsPoisoned(Poison);
  405. Ident___exception_info->setIsPoisoned(Poison);
  406. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  407. Ident__abnormal_termination->setIsPoisoned(Poison);
  408. Ident___abnormal_termination->setIsPoisoned(Poison);
  409. Ident_AbnormalTermination->setIsPoisoned(Poison);
  410. }
  411. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  412. assert(Identifier.getIdentifierInfo() &&
  413. "Can't handle identifiers without identifier info!");
  414. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  415. PoisonReasons.find(Identifier.getIdentifierInfo());
  416. if(it == PoisonReasons.end())
  417. Diag(Identifier, diag::err_pp_used_poisoned_id);
  418. else
  419. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  420. }
  421. /// HandleIdentifier - This callback is invoked when the lexer reads an
  422. /// identifier. This callback looks up the identifier in the map and/or
  423. /// potentially macro expands it or turns it into a named token (like 'for').
  424. ///
  425. /// Note that callers of this method are guarded by checking the
  426. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  427. /// IdentifierInfo methods that compute these properties will need to change to
  428. /// match.
  429. void Preprocessor::HandleIdentifier(Token &Identifier) {
  430. assert(Identifier.getIdentifierInfo() &&
  431. "Can't handle identifiers without identifier info!");
  432. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  433. // If the information about this identifier is out of date, update it from
  434. // the external source.
  435. if (II.isOutOfDate()) {
  436. ExternalSource->updateOutOfDateIdentifier(II);
  437. Identifier.setKind(II.getTokenID());
  438. }
  439. // If this identifier was poisoned, and if it was not produced from a macro
  440. // expansion, emit an error.
  441. if (II.isPoisoned() && CurPPLexer) {
  442. HandlePoisonedIdentifier(Identifier);
  443. }
  444. // If this is a macro to be expanded, do it.
  445. if (MacroInfo *MI = getMacroInfo(&II)) {
  446. if (!DisableMacroExpansion) {
  447. if (Identifier.isExpandDisabled()) {
  448. Diag(Identifier, diag::pp_disabled_macro_expansion);
  449. } else if (MI->isEnabled()) {
  450. if (!HandleMacroExpandedIdentifier(Identifier, MI))
  451. return;
  452. } else {
  453. // C99 6.10.3.4p2 says that a disabled macro may never again be
  454. // expanded, even if it's in a context where it could be expanded in the
  455. // future.
  456. Identifier.setFlag(Token::DisableExpand);
  457. Diag(Identifier, diag::pp_disabled_macro_expansion);
  458. }
  459. }
  460. }
  461. // If this identifier is a keyword in C++11, produce a warning. Don't warn if
  462. // we're not considering macro expansion, since this identifier might be the
  463. // name of a macro.
  464. // FIXME: This warning is disabled in cases where it shouldn't be, like
  465. // "#define constexpr constexpr", "int constexpr;"
  466. if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
  467. Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
  468. // Don't diagnose this keyword again in this translation unit.
  469. II.setIsCXX11CompatKeyword(false);
  470. }
  471. // C++ 2.11p2: If this is an alternative representation of a C++ operator,
  472. // then we act as if it is the actual operator and not the textual
  473. // representation of it.
  474. if (II.isCPlusPlusOperatorKeyword())
  475. Identifier.setIdentifierInfo(0);
  476. // If this is an extension token, diagnose its use.
  477. // We avoid diagnosing tokens that originate from macro definitions.
  478. // FIXME: This warning is disabled in cases where it shouldn't be,
  479. // like "#define TY typeof", "TY(1) x".
  480. if (II.isExtensionToken() && !DisableMacroExpansion)
  481. Diag(Identifier, diag::ext_token_used);
  482. // If this is the 'import' contextual keyword, note that the next token
  483. // indicates a module name.
  484. //
  485. // Note that we do not treat 'import' as a contextual keyword when we're
  486. // in a caching lexer, because caching lexers only get used in contexts where
  487. // import declarations are disallowed.
  488. if (II.isImport() && !InMacroArgs && !DisableMacroExpansion &&
  489. getLangOptions().Modules && CurLexerKind != CLK_CachingLexer) {
  490. ModuleImportLoc = Identifier.getLocation();
  491. ModuleImportPath.clear();
  492. ModuleImportExpectsIdentifier = true;
  493. CurLexerKind = CLK_LexAfterModuleImport;
  494. }
  495. }
  496. /// \brief Lex a token following the 'import' contextual keyword.
  497. ///
  498. void Preprocessor::LexAfterModuleImport(Token &Result) {
  499. // Figure out what kind of lexer we actually have.
  500. recomputeCurLexerKind();
  501. // Lex the next token.
  502. Lex(Result);
  503. // The token sequence
  504. //
  505. // import identifier (. identifier)*
  506. //
  507. // indicates a module import directive. We already saw the 'import'
  508. // contextual keyword, so now we're looking for the identifiers.
  509. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  510. // We expected to see an identifier here, and we did; continue handling
  511. // identifiers.
  512. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  513. Result.getLocation()));
  514. ModuleImportExpectsIdentifier = false;
  515. CurLexerKind = CLK_LexAfterModuleImport;
  516. return;
  517. }
  518. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  519. // see the next identifier.
  520. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  521. ModuleImportExpectsIdentifier = true;
  522. CurLexerKind = CLK_LexAfterModuleImport;
  523. return;
  524. }
  525. // If we have a non-empty module path, load the named module.
  526. if (!ModuleImportPath.empty())
  527. (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath,
  528. Module::MacrosVisible,
  529. /*IsIncludeDirective=*/false);
  530. }
  531. void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
  532. assert(Handler && "NULL comment handler");
  533. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  534. CommentHandlers.end() && "Comment handler already registered");
  535. CommentHandlers.push_back(Handler);
  536. }
  537. void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
  538. std::vector<CommentHandler *>::iterator Pos
  539. = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  540. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  541. CommentHandlers.erase(Pos);
  542. }
  543. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  544. bool AnyPendingTokens = false;
  545. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  546. HEnd = CommentHandlers.end();
  547. H != HEnd; ++H) {
  548. if ((*H)->HandleComment(*this, Comment))
  549. AnyPendingTokens = true;
  550. }
  551. if (!AnyPendingTokens || getCommentRetentionState())
  552. return false;
  553. Lex(result);
  554. return true;
  555. }
  556. ModuleLoader::~ModuleLoader() { }
  557. CommentHandler::~CommentHandler() { }
  558. CodeCompletionHandler::~CodeCompletionHandler() { }
  559. void Preprocessor::createPreprocessingRecord(
  560. bool IncludeNestedMacroExpansions) {
  561. if (Record)
  562. return;
  563. Record = new PreprocessingRecord(getSourceManager(),
  564. IncludeNestedMacroExpansions);
  565. addPPCallbacks(Record);
  566. }