Preprocessor.cpp 54 KB

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