Preprocessor.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Preprocessor interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //
  13. // Options to support:
  14. // -H - Print the name of each header file used.
  15. // -d[DNI] - Dump various things.
  16. // -fworking-directory - #line's with preprocessor's working dir.
  17. // -fpreprocessed
  18. // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
  19. // -W*
  20. // -w
  21. //
  22. // Messages to emit:
  23. // "Multiple include guards may be useful for:\n"
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Basic/FileManager.h"
  28. #include "clang/Basic/FileSystemStatCache.h"
  29. #include "clang/Basic/IdentifierTable.h"
  30. #include "clang/Basic/LLVM.h"
  31. #include "clang/Basic/LangOptions.h"
  32. #include "clang/Basic/Module.h"
  33. #include "clang/Basic/SourceLocation.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "clang/Lex/CodeCompletionHandler.h"
  37. #include "clang/Lex/ExternalPreprocessorSource.h"
  38. #include "clang/Lex/HeaderSearch.h"
  39. #include "clang/Lex/LexDiagnostic.h"
  40. #include "clang/Lex/Lexer.h"
  41. #include "clang/Lex/LiteralSupport.h"
  42. #include "clang/Lex/MacroArgs.h"
  43. #include "clang/Lex/MacroInfo.h"
  44. #include "clang/Lex/ModuleLoader.h"
  45. #include "clang/Lex/Pragma.h"
  46. #include "clang/Lex/PreprocessingRecord.h"
  47. #include "clang/Lex/PreprocessorLexer.h"
  48. #include "clang/Lex/PreprocessorOptions.h"
  49. #include "clang/Lex/ScratchBuffer.h"
  50. #include "clang/Lex/Token.h"
  51. #include "clang/Lex/TokenLexer.h"
  52. #include "llvm/ADT/APInt.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/DenseMap.h"
  55. #include "llvm/ADT/SmallString.h"
  56. #include "llvm/ADT/SmallVector.h"
  57. #include "llvm/ADT/STLExtras.h"
  58. #include "llvm/ADT/StringRef.h"
  59. #include "llvm/ADT/StringSwitch.h"
  60. #include "llvm/Support/Capacity.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/MemoryBuffer.h"
  63. #include "llvm/Support/raw_ostream.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <memory>
  67. #include <string>
  68. #include <utility>
  69. #include <vector>
  70. using namespace clang;
  71. LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
  72. ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
  73. Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
  74. DiagnosticsEngine &diags, LangOptions &opts,
  75. SourceManager &SM, HeaderSearch &Headers,
  76. ModuleLoader &TheModuleLoader,
  77. IdentifierInfoLookup *IILookup, bool OwnsHeaders,
  78. TranslationUnitKind TUKind)
  79. : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
  80. FileMgr(Headers.getFileMgr()), SourceMgr(SM),
  81. ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
  82. TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
  83. // As the language options may have not been loaded yet (when
  84. // deserializing an ASTUnit), adding keywords to the identifier table is
  85. // deferred to Preprocessor::Initialize().
  86. Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
  87. TUKind(TUKind), SkipMainFilePreamble(0, true),
  88. CurSubmoduleState(&NullSubmoduleState) {
  89. OwnsHeaderSearch = OwnsHeaders;
  90. // Default to discarding comments.
  91. KeepComments = false;
  92. KeepMacroComments = false;
  93. SuppressIncludeNotFoundError = false;
  94. // Macro expansion is enabled.
  95. DisableMacroExpansion = false;
  96. MacroExpansionInDirectivesOverride = false;
  97. InMacroArgs = false;
  98. ArgMacro = nullptr;
  99. InMacroArgPreExpansion = false;
  100. NumCachedTokenLexers = 0;
  101. PragmasEnabled = true;
  102. ParsingIfOrElifDirective = false;
  103. PreprocessedOutput = false;
  104. // We haven't read anything from the external source.
  105. ReadMacrosFromExternalSource = false;
  106. // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
  107. // a macro. They get unpoisoned where it is allowed.
  108. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  109. SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
  110. if (getLangOpts().CPlusPlus2a) {
  111. (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
  112. SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
  113. } else {
  114. Ident__VA_OPT__ = nullptr;
  115. }
  116. // Initialize the pragma handlers.
  117. RegisterBuiltinPragmas();
  118. // Initialize builtin macros like __LINE__ and friends.
  119. RegisterBuiltinMacros();
  120. if(LangOpts.Borland) {
  121. Ident__exception_info = getIdentifierInfo("_exception_info");
  122. Ident___exception_info = getIdentifierInfo("__exception_info");
  123. Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
  124. Ident__exception_code = getIdentifierInfo("_exception_code");
  125. Ident___exception_code = getIdentifierInfo("__exception_code");
  126. Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
  127. Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
  128. Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
  129. Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
  130. } else {
  131. Ident__exception_info = Ident__exception_code = nullptr;
  132. Ident__abnormal_termination = Ident___exception_info = nullptr;
  133. Ident___exception_code = Ident___abnormal_termination = nullptr;
  134. Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
  135. Ident_AbnormalTermination = nullptr;
  136. }
  137. // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
  138. if (usingPCHWithPragmaHdrStop())
  139. SkippingUntilPragmaHdrStop = true;
  140. // If using a PCH with a through header, start skipping tokens.
  141. if (!this->PPOpts->PCHThroughHeader.empty() &&
  142. !this->PPOpts->ImplicitPCHInclude.empty())
  143. SkippingUntilPCHThroughHeader = true;
  144. if (this->PPOpts->GeneratePreamble)
  145. PreambleConditionalStack.startRecording();
  146. }
  147. Preprocessor::~Preprocessor() {
  148. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  149. IncludeMacroStack.clear();
  150. // Destroy any macro definitions.
  151. while (MacroInfoChain *I = MIChainHead) {
  152. MIChainHead = I->Next;
  153. I->~MacroInfoChain();
  154. }
  155. // Free any cached macro expanders.
  156. // This populates MacroArgCache, so all TokenLexers need to be destroyed
  157. // before the code below that frees up the MacroArgCache list.
  158. std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
  159. CurTokenLexer.reset();
  160. // Free any cached MacroArgs.
  161. for (MacroArgs *ArgList = MacroArgCache; ArgList;)
  162. ArgList = ArgList->deallocate();
  163. // Delete the header search info, if we own it.
  164. if (OwnsHeaderSearch)
  165. delete &HeaderInfo;
  166. }
  167. void Preprocessor::Initialize(const TargetInfo &Target,
  168. const TargetInfo *AuxTarget) {
  169. assert((!this->Target || this->Target == &Target) &&
  170. "Invalid override of target information");
  171. this->Target = &Target;
  172. assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
  173. "Invalid override of aux target information.");
  174. this->AuxTarget = AuxTarget;
  175. // Initialize information about built-ins.
  176. BuiltinInfo.InitializeTarget(Target, AuxTarget);
  177. HeaderInfo.setTarget(Target);
  178. // Populate the identifier table with info about keywords for the current language.
  179. Identifiers.AddKeywords(LangOpts);
  180. }
  181. void Preprocessor::InitializeForModelFile() {
  182. NumEnteredSourceFiles = 0;
  183. // Reset pragmas
  184. PragmaHandlersBackup = std::move(PragmaHandlers);
  185. PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
  186. RegisterBuiltinPragmas();
  187. // Reset PredefinesFileID
  188. PredefinesFileID = FileID();
  189. }
  190. void Preprocessor::FinalizeForModelFile() {
  191. NumEnteredSourceFiles = 1;
  192. PragmaHandlers = std::move(PragmaHandlersBackup);
  193. }
  194. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  195. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  196. << getSpelling(Tok) << "'";
  197. if (!DumpFlags) return;
  198. llvm::errs() << "\t";
  199. if (Tok.isAtStartOfLine())
  200. llvm::errs() << " [StartOfLine]";
  201. if (Tok.hasLeadingSpace())
  202. llvm::errs() << " [LeadingSpace]";
  203. if (Tok.isExpandDisabled())
  204. llvm::errs() << " [ExpandDisabled]";
  205. if (Tok.needsCleaning()) {
  206. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  207. llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
  208. << "']";
  209. }
  210. llvm::errs() << "\tLoc=<";
  211. DumpLocation(Tok.getLocation());
  212. llvm::errs() << ">";
  213. }
  214. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  215. Loc.print(llvm::errs(), SourceMgr);
  216. }
  217. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  218. llvm::errs() << "MACRO: ";
  219. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  220. DumpToken(MI.getReplacementToken(i));
  221. llvm::errs() << " ";
  222. }
  223. llvm::errs() << "\n";
  224. }
  225. void Preprocessor::PrintStats() {
  226. llvm::errs() << "\n*** Preprocessor Stats:\n";
  227. llvm::errs() << NumDirectives << " directives found:\n";
  228. llvm::errs() << " " << NumDefined << " #define.\n";
  229. llvm::errs() << " " << NumUndefined << " #undef.\n";
  230. llvm::errs() << " #include/#include_next/#import:\n";
  231. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  232. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  233. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  234. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  235. llvm::errs() << " " << NumEndif << " #endif.\n";
  236. llvm::errs() << " " << NumPragma << " #pragma.\n";
  237. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  238. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  239. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  240. << NumFastMacroExpanded << " on the fast path.\n";
  241. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  242. << " token paste (##) operations performed, "
  243. << NumFastTokenPaste << " on the fast path.\n";
  244. llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
  245. llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
  246. llvm::errs() << "\n Macro Expanded Tokens: "
  247. << llvm::capacity_in_bytes(MacroExpandedTokens);
  248. llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
  249. // FIXME: List information for all submodules.
  250. llvm::errs() << "\n Macros: "
  251. << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
  252. llvm::errs() << "\n #pragma push_macro Info: "
  253. << llvm::capacity_in_bytes(PragmaPushMacroInfo);
  254. llvm::errs() << "\n Poison Reasons: "
  255. << llvm::capacity_in_bytes(PoisonReasons);
  256. llvm::errs() << "\n Comment Handlers: "
  257. << llvm::capacity_in_bytes(CommentHandlers) << "\n";
  258. }
  259. Preprocessor::macro_iterator
  260. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  261. if (IncludeExternalMacros && ExternalSource &&
  262. !ReadMacrosFromExternalSource) {
  263. ReadMacrosFromExternalSource = true;
  264. ExternalSource->ReadDefinedMacros();
  265. }
  266. // Make sure we cover all macros in visible modules.
  267. for (const ModuleMacro &Macro : ModuleMacros)
  268. CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
  269. return CurSubmoduleState->Macros.begin();
  270. }
  271. size_t Preprocessor::getTotalMemory() const {
  272. return BP.getTotalMemory()
  273. + llvm::capacity_in_bytes(MacroExpandedTokens)
  274. + Predefines.capacity() /* Predefines buffer. */
  275. // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
  276. // and ModuleMacros.
  277. + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
  278. + llvm::capacity_in_bytes(PragmaPushMacroInfo)
  279. + llvm::capacity_in_bytes(PoisonReasons)
  280. + llvm::capacity_in_bytes(CommentHandlers);
  281. }
  282. Preprocessor::macro_iterator
  283. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  284. if (IncludeExternalMacros && ExternalSource &&
  285. !ReadMacrosFromExternalSource) {
  286. ReadMacrosFromExternalSource = true;
  287. ExternalSource->ReadDefinedMacros();
  288. }
  289. return CurSubmoduleState->Macros.end();
  290. }
  291. /// Compares macro tokens with a specified token value sequence.
  292. static bool MacroDefinitionEquals(const MacroInfo *MI,
  293. ArrayRef<TokenValue> Tokens) {
  294. return Tokens.size() == MI->getNumTokens() &&
  295. std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
  296. }
  297. StringRef Preprocessor::getLastMacroWithSpelling(
  298. SourceLocation Loc,
  299. ArrayRef<TokenValue> Tokens) const {
  300. SourceLocation BestLocation;
  301. StringRef BestSpelling;
  302. for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
  303. I != E; ++I) {
  304. const MacroDirective::DefInfo
  305. Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
  306. if (!Def || !Def.getMacroInfo())
  307. continue;
  308. if (!Def.getMacroInfo()->isObjectLike())
  309. continue;
  310. if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
  311. continue;
  312. SourceLocation Location = Def.getLocation();
  313. // Choose the macro defined latest.
  314. if (BestLocation.isInvalid() ||
  315. (Location.isValid() &&
  316. SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
  317. BestLocation = Location;
  318. BestSpelling = I->first->getName();
  319. }
  320. }
  321. return BestSpelling;
  322. }
  323. void Preprocessor::recomputeCurLexerKind() {
  324. if (CurLexer)
  325. CurLexerKind = CLK_Lexer;
  326. else if (CurTokenLexer)
  327. CurLexerKind = CLK_TokenLexer;
  328. else
  329. CurLexerKind = CLK_CachingLexer;
  330. }
  331. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  332. unsigned CompleteLine,
  333. unsigned CompleteColumn) {
  334. assert(File);
  335. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  336. assert(!CodeCompletionFile && "Already set");
  337. using llvm::MemoryBuffer;
  338. // Load the actual file's contents.
  339. bool Invalid = false;
  340. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  341. if (Invalid)
  342. return true;
  343. // Find the byte position of the truncation point.
  344. const char *Position = Buffer->getBufferStart();
  345. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  346. for (; *Position; ++Position) {
  347. if (*Position != '\r' && *Position != '\n')
  348. continue;
  349. // Eat \r\n or \n\r as a single line.
  350. if ((Position[1] == '\r' || Position[1] == '\n') &&
  351. Position[0] != Position[1])
  352. ++Position;
  353. ++Position;
  354. break;
  355. }
  356. }
  357. Position += CompleteColumn - 1;
  358. // If pointing inside the preamble, adjust the position at the beginning of
  359. // the file after the preamble.
  360. if (SkipMainFilePreamble.first &&
  361. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
  362. if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
  363. Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
  364. }
  365. if (Position > Buffer->getBufferEnd())
  366. Position = Buffer->getBufferEnd();
  367. CodeCompletionFile = File;
  368. CodeCompletionOffset = Position - Buffer->getBufferStart();
  369. auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
  370. Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
  371. char *NewBuf = NewBuffer->getBufferStart();
  372. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  373. *NewPos = '\0';
  374. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  375. SourceMgr.overrideFileContents(File, std::move(NewBuffer));
  376. return false;
  377. }
  378. void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
  379. bool IsAngled) {
  380. if (CodeComplete)
  381. CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
  382. setCodeCompletionReached();
  383. }
  384. void Preprocessor::CodeCompleteNaturalLanguage() {
  385. if (CodeComplete)
  386. CodeComplete->CodeCompleteNaturalLanguage();
  387. setCodeCompletionReached();
  388. }
  389. /// getSpelling - This method is used to get the spelling of a token into a
  390. /// SmallVector. Note that the returned StringRef may not point to the
  391. /// supplied buffer if a copy can be avoided.
  392. StringRef Preprocessor::getSpelling(const Token &Tok,
  393. SmallVectorImpl<char> &Buffer,
  394. bool *Invalid) const {
  395. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  396. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
  397. // Try the fast path.
  398. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  399. return II->getName();
  400. }
  401. // Resize the buffer if we need to copy into it.
  402. if (Tok.needsCleaning())
  403. Buffer.resize(Tok.getLength());
  404. const char *Ptr = Buffer.data();
  405. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  406. return StringRef(Ptr, Len);
  407. }
  408. /// CreateString - Plop the specified string into a scratch buffer and return a
  409. /// location for it. If specified, the source location provides a source
  410. /// location for the token.
  411. void Preprocessor::CreateString(StringRef Str, Token &Tok,
  412. SourceLocation ExpansionLocStart,
  413. SourceLocation ExpansionLocEnd) {
  414. Tok.setLength(Str.size());
  415. const char *DestPtr;
  416. SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
  417. if (ExpansionLocStart.isValid())
  418. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  419. ExpansionLocEnd, Str.size());
  420. Tok.setLocation(Loc);
  421. // If this is a raw identifier or a literal token, set the pointer data.
  422. if (Tok.is(tok::raw_identifier))
  423. Tok.setRawIdentifierData(DestPtr);
  424. else if (Tok.isLiteral())
  425. Tok.setLiteralData(DestPtr);
  426. }
  427. SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
  428. auto &SM = getSourceManager();
  429. SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
  430. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
  431. bool Invalid = false;
  432. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  433. if (Invalid)
  434. return SourceLocation();
  435. // FIXME: We could consider re-using spelling for tokens we see repeatedly.
  436. const char *DestPtr;
  437. SourceLocation Spelling =
  438. ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
  439. return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
  440. }
  441. Module *Preprocessor::getCurrentModule() {
  442. if (!getLangOpts().isCompilingModule())
  443. return nullptr;
  444. return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
  445. }
  446. //===----------------------------------------------------------------------===//
  447. // Preprocessor Initialization Methods
  448. //===----------------------------------------------------------------------===//
  449. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  450. /// which implicitly adds the builtin defines etc.
  451. void Preprocessor::EnterMainSourceFile() {
  452. // We do not allow the preprocessor to reenter the main file. Doing so will
  453. // cause FileID's to accumulate information from both runs (e.g. #line
  454. // information) and predefined macros aren't guaranteed to be set properly.
  455. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  456. FileID MainFileID = SourceMgr.getMainFileID();
  457. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  458. // a main file.
  459. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  460. // Enter the main file source buffer.
  461. EnterSourceFile(MainFileID, nullptr, SourceLocation());
  462. // If we've been asked to skip bytes in the main file (e.g., as part of a
  463. // precompiled preamble), do so now.
  464. if (SkipMainFilePreamble.first > 0)
  465. CurLexer->SetByteOffset(SkipMainFilePreamble.first,
  466. SkipMainFilePreamble.second);
  467. // Tell the header info that the main file was entered. If the file is later
  468. // #imported, it won't be re-entered.
  469. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  470. HeaderInfo.IncrementIncludeCount(FE);
  471. }
  472. // Preprocess Predefines to populate the initial preprocessor state.
  473. std::unique_ptr<llvm::MemoryBuffer> SB =
  474. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  475. assert(SB && "Cannot create predefined source buffer");
  476. FileID FID = SourceMgr.createFileID(std::move(SB));
  477. assert(FID.isValid() && "Could not create FileID for predefines?");
  478. setPredefinesFileID(FID);
  479. // Start parsing the predefines.
  480. EnterSourceFile(FID, nullptr, SourceLocation());
  481. if (!PPOpts->PCHThroughHeader.empty()) {
  482. // Lookup and save the FileID for the through header. If it isn't found
  483. // in the search path, it's a fatal error.
  484. const DirectoryLookup *CurDir;
  485. Optional<FileEntryRef> File = LookupFile(
  486. SourceLocation(), PPOpts->PCHThroughHeader,
  487. /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir,
  488. /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
  489. /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
  490. /*IsFrameworkFound=*/nullptr);
  491. if (!File) {
  492. Diag(SourceLocation(), diag::err_pp_through_header_not_found)
  493. << PPOpts->PCHThroughHeader;
  494. return;
  495. }
  496. setPCHThroughHeaderFileID(
  497. SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
  498. }
  499. // Skip tokens from the Predefines and if needed the main file.
  500. if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
  501. (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
  502. SkipTokensWhileUsingPCH();
  503. }
  504. void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
  505. assert(PCHThroughHeaderFileID.isInvalid() &&
  506. "PCHThroughHeaderFileID already set!");
  507. PCHThroughHeaderFileID = FID;
  508. }
  509. bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
  510. assert(PCHThroughHeaderFileID.isValid() &&
  511. "Invalid PCH through header FileID");
  512. return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
  513. }
  514. bool Preprocessor::creatingPCHWithThroughHeader() {
  515. return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  516. PCHThroughHeaderFileID.isValid();
  517. }
  518. bool Preprocessor::usingPCHWithThroughHeader() {
  519. return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  520. PCHThroughHeaderFileID.isValid();
  521. }
  522. bool Preprocessor::creatingPCHWithPragmaHdrStop() {
  523. return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
  524. }
  525. bool Preprocessor::usingPCHWithPragmaHdrStop() {
  526. return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
  527. }
  528. /// Skip tokens until after the #include of the through header or
  529. /// until after a #pragma hdrstop is seen. Tokens in the predefines file
  530. /// and the main file may be skipped. If the end of the predefines file
  531. /// is reached, skipping continues into the main file. If the end of the
  532. /// main file is reached, it's a fatal error.
  533. void Preprocessor::SkipTokensWhileUsingPCH() {
  534. bool ReachedMainFileEOF = false;
  535. bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
  536. bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
  537. Token Tok;
  538. while (true) {
  539. bool InPredefines =
  540. (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
  541. switch (CurLexerKind) {
  542. case CLK_Lexer:
  543. CurLexer->Lex(Tok);
  544. break;
  545. case CLK_TokenLexer:
  546. CurTokenLexer->Lex(Tok);
  547. break;
  548. case CLK_CachingLexer:
  549. CachingLex(Tok);
  550. break;
  551. case CLK_LexAfterModuleImport:
  552. LexAfterModuleImport(Tok);
  553. break;
  554. }
  555. if (Tok.is(tok::eof) && !InPredefines) {
  556. ReachedMainFileEOF = true;
  557. break;
  558. }
  559. if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
  560. break;
  561. if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
  562. break;
  563. }
  564. if (ReachedMainFileEOF) {
  565. if (UsingPCHThroughHeader)
  566. Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
  567. << PPOpts->PCHThroughHeader << 1;
  568. else if (!PPOpts->PCHWithHdrStopCreate)
  569. Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
  570. }
  571. }
  572. void Preprocessor::replayPreambleConditionalStack() {
  573. // Restore the conditional stack from the preamble, if there is one.
  574. if (PreambleConditionalStack.isReplaying()) {
  575. assert(CurPPLexer &&
  576. "CurPPLexer is null when calling replayPreambleConditionalStack.");
  577. CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
  578. PreambleConditionalStack.doneReplaying();
  579. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  580. SkipExcludedConditionalBlock(
  581. PreambleConditionalStack.SkipInfo->HashTokenLoc,
  582. PreambleConditionalStack.SkipInfo->IfTokenLoc,
  583. PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
  584. PreambleConditionalStack.SkipInfo->FoundElse,
  585. PreambleConditionalStack.SkipInfo->ElseLoc);
  586. }
  587. }
  588. void Preprocessor::EndSourceFile() {
  589. // Notify the client that we reached the end of the source file.
  590. if (Callbacks)
  591. Callbacks->EndOfMainFile();
  592. }
  593. //===----------------------------------------------------------------------===//
  594. // Lexer Event Handling.
  595. //===----------------------------------------------------------------------===//
  596. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  597. /// identifier information for the token and install it into the token,
  598. /// updating the token kind accordingly.
  599. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  600. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  601. // Look up this token, see if it is a macro, or if it is a language keyword.
  602. IdentifierInfo *II;
  603. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  604. // No cleaning needed, just use the characters from the lexed buffer.
  605. II = getIdentifierInfo(Identifier.getRawIdentifier());
  606. } else {
  607. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  608. SmallString<64> IdentifierBuffer;
  609. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  610. if (Identifier.hasUCN()) {
  611. SmallString<64> UCNIdentifierBuffer;
  612. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  613. II = getIdentifierInfo(UCNIdentifierBuffer);
  614. } else {
  615. II = getIdentifierInfo(CleanedStr);
  616. }
  617. }
  618. // Update the token info (identifier info and appropriate token kind).
  619. Identifier.setIdentifierInfo(II);
  620. if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
  621. getSourceManager().isInSystemHeader(Identifier.getLocation()))
  622. Identifier.setKind(tok::identifier);
  623. else
  624. Identifier.setKind(II->getTokenID());
  625. return II;
  626. }
  627. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  628. PoisonReasons[II] = DiagID;
  629. }
  630. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  631. assert(Ident__exception_code && Ident__exception_info);
  632. assert(Ident___exception_code && Ident___exception_info);
  633. Ident__exception_code->setIsPoisoned(Poison);
  634. Ident___exception_code->setIsPoisoned(Poison);
  635. Ident_GetExceptionCode->setIsPoisoned(Poison);
  636. Ident__exception_info->setIsPoisoned(Poison);
  637. Ident___exception_info->setIsPoisoned(Poison);
  638. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  639. Ident__abnormal_termination->setIsPoisoned(Poison);
  640. Ident___abnormal_termination->setIsPoisoned(Poison);
  641. Ident_AbnormalTermination->setIsPoisoned(Poison);
  642. }
  643. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  644. assert(Identifier.getIdentifierInfo() &&
  645. "Can't handle identifiers without identifier info!");
  646. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  647. PoisonReasons.find(Identifier.getIdentifierInfo());
  648. if(it == PoisonReasons.end())
  649. Diag(Identifier, diag::err_pp_used_poisoned_id);
  650. else
  651. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  652. }
  653. /// Returns a diagnostic message kind for reporting a future keyword as
  654. /// appropriate for the identifier and specified language.
  655. static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
  656. const LangOptions &LangOpts) {
  657. assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
  658. if (LangOpts.CPlusPlus)
  659. return llvm::StringSwitch<diag::kind>(II.getName())
  660. #define CXX11_KEYWORD(NAME, FLAGS) \
  661. .Case(#NAME, diag::warn_cxx11_keyword)
  662. #define CXX2A_KEYWORD(NAME, FLAGS) \
  663. .Case(#NAME, diag::warn_cxx2a_keyword)
  664. #include "clang/Basic/TokenKinds.def"
  665. ;
  666. llvm_unreachable(
  667. "Keyword not known to come from a newer Standard or proposed Standard");
  668. }
  669. void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
  670. assert(II.isOutOfDate() && "not out of date");
  671. getExternalSource()->updateOutOfDateIdentifier(II);
  672. }
  673. /// HandleIdentifier - This callback is invoked when the lexer reads an
  674. /// identifier. This callback looks up the identifier in the map and/or
  675. /// potentially macro expands it or turns it into a named token (like 'for').
  676. ///
  677. /// Note that callers of this method are guarded by checking the
  678. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  679. /// IdentifierInfo methods that compute these properties will need to change to
  680. /// match.
  681. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  682. assert(Identifier.getIdentifierInfo() &&
  683. "Can't handle identifiers without identifier info!");
  684. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  685. // If the information about this identifier is out of date, update it from
  686. // the external source.
  687. // We have to treat __VA_ARGS__ in a special way, since it gets
  688. // serialized with isPoisoned = true, but our preprocessor may have
  689. // unpoisoned it if we're defining a C99 macro.
  690. if (II.isOutOfDate()) {
  691. bool CurrentIsPoisoned = false;
  692. const bool IsSpecialVariadicMacro =
  693. &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
  694. if (IsSpecialVariadicMacro)
  695. CurrentIsPoisoned = II.isPoisoned();
  696. updateOutOfDateIdentifier(II);
  697. Identifier.setKind(II.getTokenID());
  698. if (IsSpecialVariadicMacro)
  699. II.setIsPoisoned(CurrentIsPoisoned);
  700. }
  701. // If this identifier was poisoned, and if it was not produced from a macro
  702. // expansion, emit an error.
  703. if (II.isPoisoned() && CurPPLexer) {
  704. HandlePoisonedIdentifier(Identifier);
  705. }
  706. // If this is a macro to be expanded, do it.
  707. if (MacroDefinition MD = getMacroDefinition(&II)) {
  708. auto *MI = MD.getMacroInfo();
  709. assert(MI && "macro definition with no macro info?");
  710. if (!DisableMacroExpansion) {
  711. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  712. // C99 6.10.3p10: If the preprocessing token immediately after the
  713. // macro name isn't a '(', this macro should not be expanded.
  714. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  715. return HandleMacroExpandedIdentifier(Identifier, MD);
  716. } else {
  717. // C99 6.10.3.4p2 says that a disabled macro may never again be
  718. // expanded, even if it's in a context where it could be expanded in the
  719. // future.
  720. Identifier.setFlag(Token::DisableExpand);
  721. if (MI->isObjectLike() || isNextPPTokenLParen())
  722. Diag(Identifier, diag::pp_disabled_macro_expansion);
  723. }
  724. }
  725. }
  726. // If this identifier is a keyword in a newer Standard or proposed Standard,
  727. // produce a warning. Don't warn if we're not considering macro expansion,
  728. // since this identifier might be the name of a macro.
  729. // FIXME: This warning is disabled in cases where it shouldn't be, like
  730. // "#define constexpr constexpr", "int constexpr;"
  731. if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
  732. Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
  733. << II.getName();
  734. // Don't diagnose this keyword again in this translation unit.
  735. II.setIsFutureCompatKeyword(false);
  736. }
  737. // If this is an extension token, diagnose its use.
  738. // We avoid diagnosing tokens that originate from macro definitions.
  739. // FIXME: This warning is disabled in cases where it shouldn't be,
  740. // like "#define TY typeof", "TY(1) x".
  741. if (II.isExtensionToken() && !DisableMacroExpansion)
  742. Diag(Identifier, diag::ext_token_used);
  743. // If this is the 'import' contextual keyword following an '@', note
  744. // that the next token indicates a module name.
  745. //
  746. // Note that we do not treat 'import' as a contextual
  747. // keyword when we're in a caching lexer, because caching lexers only get
  748. // used in contexts where import declarations are disallowed.
  749. //
  750. // Likewise if this is the C++ Modules TS import keyword.
  751. if (((LastTokenWasAt && II.isModulesImport()) ||
  752. Identifier.is(tok::kw_import)) &&
  753. !InMacroArgs && !DisableMacroExpansion &&
  754. (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
  755. CurLexerKind != CLK_CachingLexer) {
  756. ModuleImportLoc = Identifier.getLocation();
  757. ModuleImportPath.clear();
  758. ModuleImportExpectsIdentifier = true;
  759. CurLexerKind = CLK_LexAfterModuleImport;
  760. }
  761. return true;
  762. }
  763. void Preprocessor::Lex(Token &Result) {
  764. ++LexLevel;
  765. // We loop here until a lex function returns a token; this avoids recursion.
  766. bool ReturnedToken;
  767. do {
  768. switch (CurLexerKind) {
  769. case CLK_Lexer:
  770. ReturnedToken = CurLexer->Lex(Result);
  771. break;
  772. case CLK_TokenLexer:
  773. ReturnedToken = CurTokenLexer->Lex(Result);
  774. break;
  775. case CLK_CachingLexer:
  776. CachingLex(Result);
  777. ReturnedToken = true;
  778. break;
  779. case CLK_LexAfterModuleImport:
  780. ReturnedToken = LexAfterModuleImport(Result);
  781. break;
  782. }
  783. } while (!ReturnedToken);
  784. if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
  785. // Remember the identifier before code completion token.
  786. setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
  787. setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
  788. // Set IdenfitierInfo to null to avoid confusing code that handles both
  789. // identifiers and completion tokens.
  790. Result.setIdentifierInfo(nullptr);
  791. }
  792. // Update ImportSeqState to track our position within a C++20 import-seq
  793. // if this token is being produced as a result of phase 4 of translation.
  794. if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
  795. !Result.getFlag(Token::IsReinjected)) {
  796. switch (Result.getKind()) {
  797. case tok::l_paren: case tok::l_square: case tok::l_brace:
  798. ImportSeqState.handleOpenBracket();
  799. break;
  800. case tok::r_paren: case tok::r_square:
  801. ImportSeqState.handleCloseBracket();
  802. break;
  803. case tok::r_brace:
  804. ImportSeqState.handleCloseBrace();
  805. break;
  806. case tok::semi:
  807. ImportSeqState.handleSemi();
  808. break;
  809. case tok::header_name:
  810. case tok::annot_header_unit:
  811. ImportSeqState.handleHeaderName();
  812. break;
  813. case tok::kw_export:
  814. ImportSeqState.handleExport();
  815. break;
  816. case tok::identifier:
  817. if (Result.getIdentifierInfo()->isModulesImport()) {
  818. ImportSeqState.handleImport();
  819. if (ImportSeqState.afterImportSeq()) {
  820. ModuleImportLoc = Result.getLocation();
  821. ModuleImportPath.clear();
  822. ModuleImportExpectsIdentifier = true;
  823. CurLexerKind = CLK_LexAfterModuleImport;
  824. }
  825. break;
  826. }
  827. LLVM_FALLTHROUGH;
  828. default:
  829. ImportSeqState.handleMisc();
  830. break;
  831. }
  832. }
  833. LastTokenWasAt = Result.is(tok::at);
  834. --LexLevel;
  835. if (OnToken && LexLevel == 0 && !Result.getFlag(Token::IsReinjected))
  836. OnToken(Result);
  837. }
  838. /// Lex a header-name token (including one formed from header-name-tokens if
  839. /// \p AllowConcatenation is \c true).
  840. ///
  841. /// \param FilenameTok Filled in with the next token. On success, this will
  842. /// be either a header_name token. On failure, it will be whatever other
  843. /// token was found instead.
  844. /// \param AllowMacroExpansion If \c true, allow the header name to be formed
  845. /// by macro expansion (concatenating tokens as necessary if the first
  846. /// token is a '<').
  847. /// \return \c true if we reached EOD or EOF while looking for a > token in
  848. /// a concatenated header name and diagnosed it. \c false otherwise.
  849. bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
  850. // Lex using header-name tokenization rules if tokens are being lexed from
  851. // a file. Just grab a token normally if we're in a macro expansion.
  852. if (CurPPLexer)
  853. CurPPLexer->LexIncludeFilename(FilenameTok);
  854. else
  855. Lex(FilenameTok);
  856. // This could be a <foo/bar.h> file coming from a macro expansion. In this
  857. // case, glue the tokens together into an angle_string_literal token.
  858. SmallString<128> FilenameBuffer;
  859. if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
  860. bool StartOfLine = FilenameTok.isAtStartOfLine();
  861. bool LeadingSpace = FilenameTok.hasLeadingSpace();
  862. bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
  863. SourceLocation Start = FilenameTok.getLocation();
  864. SourceLocation End;
  865. FilenameBuffer.push_back('<');
  866. // Consume tokens until we find a '>'.
  867. // FIXME: A header-name could be formed starting or ending with an
  868. // alternative token. It's not clear whether that's ill-formed in all
  869. // cases.
  870. while (FilenameTok.isNot(tok::greater)) {
  871. Lex(FilenameTok);
  872. if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
  873. Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
  874. Diag(Start, diag::note_matching) << tok::less;
  875. return true;
  876. }
  877. End = FilenameTok.getLocation();
  878. // FIXME: Provide code completion for #includes.
  879. if (FilenameTok.is(tok::code_completion)) {
  880. setCodeCompletionReached();
  881. Lex(FilenameTok);
  882. continue;
  883. }
  884. // Append the spelling of this token to the buffer. If there was a space
  885. // before it, add it now.
  886. if (FilenameTok.hasLeadingSpace())
  887. FilenameBuffer.push_back(' ');
  888. // Get the spelling of the token, directly into FilenameBuffer if
  889. // possible.
  890. size_t PreAppendSize = FilenameBuffer.size();
  891. FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
  892. const char *BufPtr = &FilenameBuffer[PreAppendSize];
  893. unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
  894. // If the token was spelled somewhere else, copy it into FilenameBuffer.
  895. if (BufPtr != &FilenameBuffer[PreAppendSize])
  896. memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
  897. // Resize FilenameBuffer to the correct size.
  898. if (FilenameTok.getLength() != ActualLen)
  899. FilenameBuffer.resize(PreAppendSize + ActualLen);
  900. }
  901. FilenameTok.startToken();
  902. FilenameTok.setKind(tok::header_name);
  903. FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
  904. FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
  905. FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
  906. CreateString(FilenameBuffer, FilenameTok, Start, End);
  907. } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
  908. // Convert a string-literal token of the form " h-char-sequence "
  909. // (produced by macro expansion) into a header-name token.
  910. //
  911. // The rules for header-names don't quite match the rules for
  912. // string-literals, but all the places where they differ result in
  913. // undefined behavior, so we can and do treat them the same.
  914. //
  915. // A string-literal with a prefix or suffix is not translated into a
  916. // header-name. This could theoretically be observable via the C++20
  917. // context-sensitive header-name formation rules.
  918. StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
  919. if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
  920. FilenameTok.setKind(tok::header_name);
  921. }
  922. return false;
  923. }
  924. /// Collect the tokens of a C++20 pp-import-suffix.
  925. void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
  926. // FIXME: For error recovery, consider recognizing attribute syntax here
  927. // and terminating / diagnosing a missing semicolon if we find anything
  928. // else? (Can we leave that to the parser?)
  929. unsigned BracketDepth = 0;
  930. while (true) {
  931. Toks.emplace_back();
  932. Lex(Toks.back());
  933. switch (Toks.back().getKind()) {
  934. case tok::l_paren: case tok::l_square: case tok::l_brace:
  935. ++BracketDepth;
  936. break;
  937. case tok::r_paren: case tok::r_square: case tok::r_brace:
  938. if (BracketDepth == 0)
  939. return;
  940. --BracketDepth;
  941. break;
  942. case tok::semi:
  943. if (BracketDepth == 0)
  944. return;
  945. break;
  946. case tok::eof:
  947. return;
  948. default:
  949. break;
  950. }
  951. }
  952. }
  953. /// Lex a token following the 'import' contextual keyword.
  954. ///
  955. /// pp-import: [C++20]
  956. /// import header-name pp-import-suffix[opt] ;
  957. /// import header-name-tokens pp-import-suffix[opt] ;
  958. /// [ObjC] @ import module-name ;
  959. /// [Clang] import module-name ;
  960. ///
  961. /// header-name-tokens:
  962. /// string-literal
  963. /// < [any sequence of preprocessing-tokens other than >] >
  964. ///
  965. /// module-name:
  966. /// module-name-qualifier[opt] identifier
  967. ///
  968. /// module-name-qualifier
  969. /// module-name-qualifier[opt] identifier .
  970. ///
  971. /// We respond to a pp-import by importing macros from the named module.
  972. bool Preprocessor::LexAfterModuleImport(Token &Result) {
  973. // Figure out what kind of lexer we actually have.
  974. recomputeCurLexerKind();
  975. // Lex the next token. The header-name lexing rules are used at the start of
  976. // a pp-import.
  977. //
  978. // For now, we only support header-name imports in C++20 mode.
  979. // FIXME: Should we allow this in all language modes that support an import
  980. // declaration as an extension?
  981. if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
  982. if (LexHeaderName(Result))
  983. return true;
  984. } else {
  985. Lex(Result);
  986. }
  987. // Allocate a holding buffer for a sequence of tokens and introduce it into
  988. // the token stream.
  989. auto EnterTokens = [this](ArrayRef<Token> Toks) {
  990. auto ToksCopy = std::make_unique<Token[]>(Toks.size());
  991. std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
  992. EnterTokenStream(std::move(ToksCopy), Toks.size(),
  993. /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
  994. };
  995. // Check for a header-name.
  996. SmallVector<Token, 32> Suffix;
  997. if (Result.is(tok::header_name)) {
  998. // Enter the header-name token into the token stream; a Lex action cannot
  999. // both return a token and cache tokens (doing so would corrupt the token
  1000. // cache if the call to Lex comes from CachingLex / PeekAhead).
  1001. Suffix.push_back(Result);
  1002. // Consume the pp-import-suffix and expand any macros in it now. We'll add
  1003. // it back into the token stream later.
  1004. CollectPpImportSuffix(Suffix);
  1005. if (Suffix.back().isNot(tok::semi)) {
  1006. // This is not a pp-import after all.
  1007. EnterTokens(Suffix);
  1008. return false;
  1009. }
  1010. // C++2a [cpp.module]p1:
  1011. // The ';' preprocessing-token terminating a pp-import shall not have
  1012. // been produced by macro replacement.
  1013. SourceLocation SemiLoc = Suffix.back().getLocation();
  1014. if (SemiLoc.isMacroID())
  1015. Diag(SemiLoc, diag::err_header_import_semi_in_macro);
  1016. // Reconstitute the import token.
  1017. Token ImportTok;
  1018. ImportTok.startToken();
  1019. ImportTok.setKind(tok::kw_import);
  1020. ImportTok.setLocation(ModuleImportLoc);
  1021. ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
  1022. ImportTok.setLength(6);
  1023. auto Action = HandleHeaderIncludeOrImport(
  1024. /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
  1025. switch (Action.Kind) {
  1026. case ImportAction::None:
  1027. break;
  1028. case ImportAction::ModuleBegin:
  1029. // Let the parser know we're textually entering the module.
  1030. Suffix.emplace_back();
  1031. Suffix.back().startToken();
  1032. Suffix.back().setKind(tok::annot_module_begin);
  1033. Suffix.back().setLocation(SemiLoc);
  1034. Suffix.back().setAnnotationEndLoc(SemiLoc);
  1035. Suffix.back().setAnnotationValue(Action.ModuleForHeader);
  1036. LLVM_FALLTHROUGH;
  1037. case ImportAction::ModuleImport:
  1038. case ImportAction::SkippedModuleImport:
  1039. // We chose to import (or textually enter) the file. Convert the
  1040. // header-name token into a header unit annotation token.
  1041. Suffix[0].setKind(tok::annot_header_unit);
  1042. Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
  1043. Suffix[0].setAnnotationValue(Action.ModuleForHeader);
  1044. // FIXME: Call the moduleImport callback?
  1045. break;
  1046. }
  1047. EnterTokens(Suffix);
  1048. return false;
  1049. }
  1050. // The token sequence
  1051. //
  1052. // import identifier (. identifier)*
  1053. //
  1054. // indicates a module import directive. We already saw the 'import'
  1055. // contextual keyword, so now we're looking for the identifiers.
  1056. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  1057. // We expected to see an identifier here, and we did; continue handling
  1058. // identifiers.
  1059. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  1060. Result.getLocation()));
  1061. ModuleImportExpectsIdentifier = false;
  1062. CurLexerKind = CLK_LexAfterModuleImport;
  1063. return true;
  1064. }
  1065. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  1066. // see the next identifier. (We can also see a '[[' that begins an
  1067. // attribute-specifier-seq here under the C++ Modules TS.)
  1068. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  1069. ModuleImportExpectsIdentifier = true;
  1070. CurLexerKind = CLK_LexAfterModuleImport;
  1071. return true;
  1072. }
  1073. // If we didn't recognize a module name at all, this is not a (valid) import.
  1074. if (ModuleImportPath.empty() || Result.is(tok::eof))
  1075. return true;
  1076. // Consume the pp-import-suffix and expand any macros in it now, if we're not
  1077. // at the semicolon already.
  1078. SourceLocation SemiLoc = Result.getLocation();
  1079. if (Result.isNot(tok::semi)) {
  1080. Suffix.push_back(Result);
  1081. CollectPpImportSuffix(Suffix);
  1082. if (Suffix.back().isNot(tok::semi)) {
  1083. // This is not an import after all.
  1084. EnterTokens(Suffix);
  1085. return false;
  1086. }
  1087. SemiLoc = Suffix.back().getLocation();
  1088. }
  1089. // Under the Modules TS, the dot is just part of the module name, and not
  1090. // a real hierarchy separator. Flatten such module names now.
  1091. //
  1092. // FIXME: Is this the right level to be performing this transformation?
  1093. std::string FlatModuleName;
  1094. if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
  1095. for (auto &Piece : ModuleImportPath) {
  1096. if (!FlatModuleName.empty())
  1097. FlatModuleName += ".";
  1098. FlatModuleName += Piece.first->getName();
  1099. }
  1100. SourceLocation FirstPathLoc = ModuleImportPath[0].second;
  1101. ModuleImportPath.clear();
  1102. ModuleImportPath.push_back(
  1103. std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
  1104. }
  1105. Module *Imported = nullptr;
  1106. if (getLangOpts().Modules) {
  1107. Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  1108. ModuleImportPath,
  1109. Module::Hidden,
  1110. /*IsInclusionDirective=*/false);
  1111. if (Imported)
  1112. makeModuleVisible(Imported, SemiLoc);
  1113. }
  1114. if (Callbacks)
  1115. Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
  1116. if (!Suffix.empty()) {
  1117. EnterTokens(Suffix);
  1118. return false;
  1119. }
  1120. return true;
  1121. }
  1122. void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
  1123. CurSubmoduleState->VisibleModules.setVisible(
  1124. M, Loc, [](Module *) {},
  1125. [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
  1126. // FIXME: Include the path in the diagnostic.
  1127. // FIXME: Include the import location for the conflicting module.
  1128. Diag(ModuleImportLoc, diag::warn_module_conflict)
  1129. << Path[0]->getFullModuleName()
  1130. << Conflict->getFullModuleName()
  1131. << Message;
  1132. });
  1133. // Add this module to the imports list of the currently-built submodule.
  1134. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
  1135. BuildingSubmoduleStack.back().M->Imports.insert(M);
  1136. }
  1137. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  1138. const char *DiagnosticTag,
  1139. bool AllowMacroExpansion) {
  1140. // We need at least one string literal.
  1141. if (Result.isNot(tok::string_literal)) {
  1142. Diag(Result, diag::err_expected_string_literal)
  1143. << /*Source='in...'*/0 << DiagnosticTag;
  1144. return false;
  1145. }
  1146. // Lex string literal tokens, optionally with macro expansion.
  1147. SmallVector<Token, 4> StrToks;
  1148. do {
  1149. StrToks.push_back(Result);
  1150. if (Result.hasUDSuffix())
  1151. Diag(Result, diag::err_invalid_string_udl);
  1152. if (AllowMacroExpansion)
  1153. Lex(Result);
  1154. else
  1155. LexUnexpandedToken(Result);
  1156. } while (Result.is(tok::string_literal));
  1157. // Concatenate and parse the strings.
  1158. StringLiteralParser Literal(StrToks, *this);
  1159. assert(Literal.isAscii() && "Didn't allow wide strings in");
  1160. if (Literal.hadError)
  1161. return false;
  1162. if (Literal.Pascal) {
  1163. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  1164. << /*Source='in...'*/0 << DiagnosticTag;
  1165. return false;
  1166. }
  1167. String = Literal.GetString();
  1168. return true;
  1169. }
  1170. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  1171. assert(Tok.is(tok::numeric_constant));
  1172. SmallString<8> IntegerBuffer;
  1173. bool NumberInvalid = false;
  1174. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  1175. if (NumberInvalid)
  1176. return false;
  1177. NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
  1178. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  1179. return false;
  1180. llvm::APInt APVal(64, 0);
  1181. if (Literal.GetIntegerValue(APVal))
  1182. return false;
  1183. Lex(Tok);
  1184. Value = APVal.getLimitedValue();
  1185. return true;
  1186. }
  1187. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  1188. assert(Handler && "NULL comment handler");
  1189. assert(llvm::find(CommentHandlers, Handler) == CommentHandlers.end() &&
  1190. "Comment handler already registered");
  1191. CommentHandlers.push_back(Handler);
  1192. }
  1193. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  1194. std::vector<CommentHandler *>::iterator Pos =
  1195. llvm::find(CommentHandlers, Handler);
  1196. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  1197. CommentHandlers.erase(Pos);
  1198. }
  1199. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  1200. bool AnyPendingTokens = false;
  1201. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  1202. HEnd = CommentHandlers.end();
  1203. H != HEnd; ++H) {
  1204. if ((*H)->HandleComment(*this, Comment))
  1205. AnyPendingTokens = true;
  1206. }
  1207. if (!AnyPendingTokens || getCommentRetentionState())
  1208. return false;
  1209. Lex(result);
  1210. return true;
  1211. }
  1212. ModuleLoader::~ModuleLoader() = default;
  1213. CommentHandler::~CommentHandler() = default;
  1214. CodeCompletionHandler::~CodeCompletionHandler() = default;
  1215. void Preprocessor::createPreprocessingRecord() {
  1216. if (Record)
  1217. return;
  1218. Record = new PreprocessingRecord(getSourceManager());
  1219. addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
  1220. }