Preprocessor.cpp 29 KB

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