Preprocessor.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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/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 <optional>
  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. MaxTokens = LangOpts.MaxTokens;
  145. }
  146. Preprocessor::~Preprocessor() {
  147. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  148. IncludeMacroStack.clear();
  149. // Free any cached macro expanders.
  150. // This populates MacroArgCache, so all TokenLexers need to be destroyed
  151. // before the code below that frees up the MacroArgCache list.
  152. std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
  153. CurTokenLexer.reset();
  154. // Free any cached MacroArgs.
  155. for (MacroArgs *ArgList = MacroArgCache; ArgList;)
  156. ArgList = ArgList->deallocate();
  157. // Delete the header search info, if we own it.
  158. if (OwnsHeaderSearch)
  159. delete &HeaderInfo;
  160. }
  161. void Preprocessor::Initialize(const TargetInfo &Target,
  162. const TargetInfo *AuxTarget) {
  163. assert((!this->Target || this->Target == &Target) &&
  164. "Invalid override of target information");
  165. this->Target = &Target;
  166. assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
  167. "Invalid override of aux target information.");
  168. this->AuxTarget = AuxTarget;
  169. // Initialize information about built-ins.
  170. BuiltinInfo->InitializeTarget(Target, AuxTarget);
  171. HeaderInfo.setTarget(Target);
  172. // Populate the identifier table with info about keywords for the current language.
  173. Identifiers.AddKeywords(LangOpts);
  174. // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
  175. setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
  176. if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
  177. // Use setting from TargetInfo.
  178. setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
  179. else
  180. // Set initial value of __FLT_EVAL_METHOD__ from the command line.
  181. setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
  182. }
  183. void Preprocessor::InitializeForModelFile() {
  184. NumEnteredSourceFiles = 0;
  185. // Reset pragmas
  186. PragmaHandlersBackup = std::move(PragmaHandlers);
  187. PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
  188. RegisterBuiltinPragmas();
  189. // Reset PredefinesFileID
  190. PredefinesFileID = FileID();
  191. }
  192. void Preprocessor::FinalizeForModelFile() {
  193. NumEnteredSourceFiles = 1;
  194. PragmaHandlers = std::move(PragmaHandlersBackup);
  195. }
  196. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  197. llvm::errs() << tok::getTokenName(Tok.getKind());
  198. if (!Tok.isAnnotation())
  199. llvm::errs() << " '" << 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 = CurLexer->isDependencyDirectivesLexer()
  329. ? CLK_DependencyDirectivesLexer
  330. : CLK_Lexer;
  331. else if (CurTokenLexer)
  332. CurLexerKind = CLK_TokenLexer;
  333. else
  334. CurLexerKind = CLK_CachingLexer;
  335. }
  336. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  337. unsigned CompleteLine,
  338. unsigned CompleteColumn) {
  339. assert(File);
  340. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  341. assert(!CodeCompletionFile && "Already set");
  342. // Load the actual file's contents.
  343. std::optional<llvm::MemoryBufferRef> Buffer =
  344. SourceMgr.getMemoryBufferForFileOrNone(File);
  345. if (!Buffer)
  346. return true;
  347. // Find the byte position of the truncation point.
  348. const char *Position = Buffer->getBufferStart();
  349. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  350. for (; *Position; ++Position) {
  351. if (*Position != '\r' && *Position != '\n')
  352. continue;
  353. // Eat \r\n or \n\r as a single line.
  354. if ((Position[1] == '\r' || Position[1] == '\n') &&
  355. Position[0] != Position[1])
  356. ++Position;
  357. ++Position;
  358. break;
  359. }
  360. }
  361. Position += CompleteColumn - 1;
  362. // If pointing inside the preamble, adjust the position at the beginning of
  363. // the file after the preamble.
  364. if (SkipMainFilePreamble.first &&
  365. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
  366. if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
  367. Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
  368. }
  369. if (Position > Buffer->getBufferEnd())
  370. Position = Buffer->getBufferEnd();
  371. CodeCompletionFile = File;
  372. CodeCompletionOffset = Position - Buffer->getBufferStart();
  373. auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
  374. Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
  375. char *NewBuf = NewBuffer->getBufferStart();
  376. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  377. *NewPos = '\0';
  378. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  379. SourceMgr.overrideFileContents(File, std::move(NewBuffer));
  380. return false;
  381. }
  382. void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
  383. bool IsAngled) {
  384. setCodeCompletionReached();
  385. if (CodeComplete)
  386. CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
  387. }
  388. void Preprocessor::CodeCompleteNaturalLanguage() {
  389. setCodeCompletionReached();
  390. if (CodeComplete)
  391. CodeComplete->CodeCompleteNaturalLanguage();
  392. }
  393. /// getSpelling - This method is used to get the spelling of a token into a
  394. /// SmallVector. Note that the returned StringRef may not point to the
  395. /// supplied buffer if a copy can be avoided.
  396. StringRef Preprocessor::getSpelling(const Token &Tok,
  397. SmallVectorImpl<char> &Buffer,
  398. bool *Invalid) const {
  399. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  400. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
  401. // Try the fast path.
  402. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  403. return II->getName();
  404. }
  405. // Resize the buffer if we need to copy into it.
  406. if (Tok.needsCleaning())
  407. Buffer.resize(Tok.getLength());
  408. const char *Ptr = Buffer.data();
  409. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  410. return StringRef(Ptr, Len);
  411. }
  412. /// CreateString - Plop the specified string into a scratch buffer and return a
  413. /// location for it. If specified, the source location provides a source
  414. /// location for the token.
  415. void Preprocessor::CreateString(StringRef Str, Token &Tok,
  416. SourceLocation ExpansionLocStart,
  417. SourceLocation ExpansionLocEnd) {
  418. Tok.setLength(Str.size());
  419. const char *DestPtr;
  420. SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
  421. if (ExpansionLocStart.isValid())
  422. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  423. ExpansionLocEnd, Str.size());
  424. Tok.setLocation(Loc);
  425. // If this is a raw identifier or a literal token, set the pointer data.
  426. if (Tok.is(tok::raw_identifier))
  427. Tok.setRawIdentifierData(DestPtr);
  428. else if (Tok.isLiteral())
  429. Tok.setLiteralData(DestPtr);
  430. }
  431. SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
  432. auto &SM = getSourceManager();
  433. SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
  434. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
  435. bool Invalid = false;
  436. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  437. if (Invalid)
  438. return SourceLocation();
  439. // FIXME: We could consider re-using spelling for tokens we see repeatedly.
  440. const char *DestPtr;
  441. SourceLocation Spelling =
  442. ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
  443. return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
  444. }
  445. Module *Preprocessor::getCurrentModule() {
  446. if (!getLangOpts().isCompilingModule())
  447. return nullptr;
  448. return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
  449. }
  450. Module *Preprocessor::getCurrentModuleImplementation() {
  451. if (!getLangOpts().isCompilingModuleImplementation())
  452. return nullptr;
  453. return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
  454. }
  455. //===----------------------------------------------------------------------===//
  456. // Preprocessor Initialization Methods
  457. //===----------------------------------------------------------------------===//
  458. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  459. /// which implicitly adds the builtin defines etc.
  460. void Preprocessor::EnterMainSourceFile() {
  461. // We do not allow the preprocessor to reenter the main file. Doing so will
  462. // cause FileID's to accumulate information from both runs (e.g. #line
  463. // information) and predefined macros aren't guaranteed to be set properly.
  464. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  465. FileID MainFileID = SourceMgr.getMainFileID();
  466. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  467. // a main file.
  468. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  469. // Enter the main file source buffer.
  470. EnterSourceFile(MainFileID, nullptr, SourceLocation());
  471. // If we've been asked to skip bytes in the main file (e.g., as part of a
  472. // precompiled preamble), do so now.
  473. if (SkipMainFilePreamble.first > 0)
  474. CurLexer->SetByteOffset(SkipMainFilePreamble.first,
  475. SkipMainFilePreamble.second);
  476. // Tell the header info that the main file was entered. If the file is later
  477. // #imported, it won't be re-entered.
  478. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  479. markIncluded(FE);
  480. }
  481. // Preprocess Predefines to populate the initial preprocessor state.
  482. std::unique_ptr<llvm::MemoryBuffer> SB =
  483. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  484. assert(SB && "Cannot create predefined source buffer");
  485. FileID FID = SourceMgr.createFileID(std::move(SB));
  486. assert(FID.isValid() && "Could not create FileID for predefines?");
  487. setPredefinesFileID(FID);
  488. // Start parsing the predefines.
  489. EnterSourceFile(FID, nullptr, SourceLocation());
  490. if (!PPOpts->PCHThroughHeader.empty()) {
  491. // Lookup and save the FileID for the through header. If it isn't found
  492. // in the search path, it's a fatal error.
  493. OptionalFileEntryRef File = LookupFile(
  494. SourceLocation(), PPOpts->PCHThroughHeader,
  495. /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
  496. /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
  497. /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
  498. /*IsFrameworkFound=*/nullptr);
  499. if (!File) {
  500. Diag(SourceLocation(), diag::err_pp_through_header_not_found)
  501. << PPOpts->PCHThroughHeader;
  502. return;
  503. }
  504. setPCHThroughHeaderFileID(
  505. SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
  506. }
  507. // Skip tokens from the Predefines and if needed the main file.
  508. if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
  509. (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
  510. SkipTokensWhileUsingPCH();
  511. }
  512. void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
  513. assert(PCHThroughHeaderFileID.isInvalid() &&
  514. "PCHThroughHeaderFileID already set!");
  515. PCHThroughHeaderFileID = FID;
  516. }
  517. bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
  518. assert(PCHThroughHeaderFileID.isValid() &&
  519. "Invalid PCH through header FileID");
  520. return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
  521. }
  522. bool Preprocessor::creatingPCHWithThroughHeader() {
  523. return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  524. PCHThroughHeaderFileID.isValid();
  525. }
  526. bool Preprocessor::usingPCHWithThroughHeader() {
  527. return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
  528. PCHThroughHeaderFileID.isValid();
  529. }
  530. bool Preprocessor::creatingPCHWithPragmaHdrStop() {
  531. return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
  532. }
  533. bool Preprocessor::usingPCHWithPragmaHdrStop() {
  534. return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
  535. }
  536. /// Skip tokens until after the #include of the through header or
  537. /// until after a #pragma hdrstop is seen. Tokens in the predefines file
  538. /// and the main file may be skipped. If the end of the predefines file
  539. /// is reached, skipping continues into the main file. If the end of the
  540. /// main file is reached, it's a fatal error.
  541. void Preprocessor::SkipTokensWhileUsingPCH() {
  542. bool ReachedMainFileEOF = false;
  543. bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
  544. bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
  545. Token Tok;
  546. while (true) {
  547. bool InPredefines =
  548. (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
  549. switch (CurLexerKind) {
  550. case CLK_Lexer:
  551. CurLexer->Lex(Tok);
  552. break;
  553. case CLK_TokenLexer:
  554. CurTokenLexer->Lex(Tok);
  555. break;
  556. case CLK_CachingLexer:
  557. CachingLex(Tok);
  558. break;
  559. case CLK_DependencyDirectivesLexer:
  560. CurLexer->LexDependencyDirectiveToken(Tok);
  561. break;
  562. case CLK_LexAfterModuleImport:
  563. LexAfterModuleImport(Tok);
  564. break;
  565. }
  566. if (Tok.is(tok::eof) && !InPredefines) {
  567. ReachedMainFileEOF = true;
  568. break;
  569. }
  570. if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
  571. break;
  572. if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
  573. break;
  574. }
  575. if (ReachedMainFileEOF) {
  576. if (UsingPCHThroughHeader)
  577. Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
  578. << PPOpts->PCHThroughHeader << 1;
  579. else if (!PPOpts->PCHWithHdrStopCreate)
  580. Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
  581. }
  582. }
  583. void Preprocessor::replayPreambleConditionalStack() {
  584. // Restore the conditional stack from the preamble, if there is one.
  585. if (PreambleConditionalStack.isReplaying()) {
  586. assert(CurPPLexer &&
  587. "CurPPLexer is null when calling replayPreambleConditionalStack.");
  588. CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
  589. PreambleConditionalStack.doneReplaying();
  590. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  591. SkipExcludedConditionalBlock(
  592. PreambleConditionalStack.SkipInfo->HashTokenLoc,
  593. PreambleConditionalStack.SkipInfo->IfTokenLoc,
  594. PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
  595. PreambleConditionalStack.SkipInfo->FoundElse,
  596. PreambleConditionalStack.SkipInfo->ElseLoc);
  597. }
  598. }
  599. void Preprocessor::EndSourceFile() {
  600. // Notify the client that we reached the end of the source file.
  601. if (Callbacks)
  602. Callbacks->EndOfMainFile();
  603. }
  604. //===----------------------------------------------------------------------===//
  605. // Lexer Event Handling.
  606. //===----------------------------------------------------------------------===//
  607. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  608. /// identifier information for the token and install it into the token,
  609. /// updating the token kind accordingly.
  610. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  611. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  612. // Look up this token, see if it is a macro, or if it is a language keyword.
  613. IdentifierInfo *II;
  614. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  615. // No cleaning needed, just use the characters from the lexed buffer.
  616. II = getIdentifierInfo(Identifier.getRawIdentifier());
  617. } else {
  618. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  619. SmallString<64> IdentifierBuffer;
  620. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  621. if (Identifier.hasUCN()) {
  622. SmallString<64> UCNIdentifierBuffer;
  623. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  624. II = getIdentifierInfo(UCNIdentifierBuffer);
  625. } else {
  626. II = getIdentifierInfo(CleanedStr);
  627. }
  628. }
  629. // Update the token info (identifier info and appropriate token kind).
  630. // FIXME: the raw_identifier may contain leading whitespace which is removed
  631. // from the cleaned identifier token. The SourceLocation should be updated to
  632. // refer to the non-whitespace character. For instance, the text "\\\nB" (a
  633. // line continuation before 'B') is parsed as a single tok::raw_identifier and
  634. // is cleaned to tok::identifier "B". After cleaning the token's length is
  635. // still 3 and the SourceLocation refers to the location of the backslash.
  636. Identifier.setIdentifierInfo(II);
  637. Identifier.setKind(II->getTokenID());
  638. return II;
  639. }
  640. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  641. PoisonReasons[II] = DiagID;
  642. }
  643. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  644. assert(Ident__exception_code && Ident__exception_info);
  645. assert(Ident___exception_code && Ident___exception_info);
  646. Ident__exception_code->setIsPoisoned(Poison);
  647. Ident___exception_code->setIsPoisoned(Poison);
  648. Ident_GetExceptionCode->setIsPoisoned(Poison);
  649. Ident__exception_info->setIsPoisoned(Poison);
  650. Ident___exception_info->setIsPoisoned(Poison);
  651. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  652. Ident__abnormal_termination->setIsPoisoned(Poison);
  653. Ident___abnormal_termination->setIsPoisoned(Poison);
  654. Ident_AbnormalTermination->setIsPoisoned(Poison);
  655. }
  656. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  657. assert(Identifier.getIdentifierInfo() &&
  658. "Can't handle identifiers without identifier info!");
  659. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  660. PoisonReasons.find(Identifier.getIdentifierInfo());
  661. if(it == PoisonReasons.end())
  662. Diag(Identifier, diag::err_pp_used_poisoned_id);
  663. else
  664. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  665. }
  666. void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
  667. assert(II.isOutOfDate() && "not out of date");
  668. getExternalSource()->updateOutOfDateIdentifier(II);
  669. }
  670. /// HandleIdentifier - This callback is invoked when the lexer reads an
  671. /// identifier. This callback looks up the identifier in the map and/or
  672. /// potentially macro expands it or turns it into a named token (like 'for').
  673. ///
  674. /// Note that callers of this method are guarded by checking the
  675. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  676. /// IdentifierInfo methods that compute these properties will need to change to
  677. /// match.
  678. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  679. assert(Identifier.getIdentifierInfo() &&
  680. "Can't handle identifiers without identifier info!");
  681. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  682. // If the information about this identifier is out of date, update it from
  683. // the external source.
  684. // We have to treat __VA_ARGS__ in a special way, since it gets
  685. // serialized with isPoisoned = true, but our preprocessor may have
  686. // unpoisoned it if we're defining a C99 macro.
  687. if (II.isOutOfDate()) {
  688. bool CurrentIsPoisoned = false;
  689. const bool IsSpecialVariadicMacro =
  690. &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
  691. if (IsSpecialVariadicMacro)
  692. CurrentIsPoisoned = II.isPoisoned();
  693. updateOutOfDateIdentifier(II);
  694. Identifier.setKind(II.getTokenID());
  695. if (IsSpecialVariadicMacro)
  696. II.setIsPoisoned(CurrentIsPoisoned);
  697. }
  698. // If this identifier was poisoned, and if it was not produced from a macro
  699. // expansion, emit an error.
  700. if (II.isPoisoned() && CurPPLexer) {
  701. HandlePoisonedIdentifier(Identifier);
  702. }
  703. // If this is a macro to be expanded, do it.
  704. if (MacroDefinition MD = getMacroDefinition(&II)) {
  705. auto *MI = MD.getMacroInfo();
  706. assert(MI && "macro definition with no macro info?");
  707. if (!DisableMacroExpansion) {
  708. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  709. // C99 6.10.3p10: If the preprocessing token immediately after the
  710. // macro name isn't a '(', this macro should not be expanded.
  711. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  712. return HandleMacroExpandedIdentifier(Identifier, MD);
  713. } else {
  714. // C99 6.10.3.4p2 says that a disabled macro may never again be
  715. // expanded, even if it's in a context where it could be expanded in the
  716. // future.
  717. Identifier.setFlag(Token::DisableExpand);
  718. if (MI->isObjectLike() || isNextPPTokenLParen())
  719. Diag(Identifier, diag::pp_disabled_macro_expansion);
  720. }
  721. }
  722. }
  723. // If this identifier is a keyword in a newer Standard or proposed Standard,
  724. // produce a warning. Don't warn if we're not considering macro expansion,
  725. // since this identifier might be the name of a macro.
  726. // FIXME: This warning is disabled in cases where it shouldn't be, like
  727. // "#define constexpr constexpr", "int constexpr;"
  728. if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
  729. Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
  730. << II.getName();
  731. // Don't diagnose this keyword again in this translation unit.
  732. II.setIsFutureCompatKeyword(false);
  733. }
  734. // If this is an extension token, diagnose its use.
  735. // We avoid diagnosing tokens that originate from macro definitions.
  736. // FIXME: This warning is disabled in cases where it shouldn't be,
  737. // like "#define TY typeof", "TY(1) x".
  738. if (II.isExtensionToken() && !DisableMacroExpansion)
  739. Diag(Identifier, diag::ext_token_used);
  740. // If this is the 'import' contextual keyword following an '@', note
  741. // that the next token indicates a module name.
  742. //
  743. // Note that we do not treat 'import' as a contextual
  744. // keyword when we're in a caching lexer, because caching lexers only get
  745. // used in contexts where import declarations are disallowed.
  746. //
  747. // Likewise if this is the C++ Modules TS import keyword.
  748. if (((LastTokenWasAt && II.isModulesImport()) ||
  749. Identifier.is(tok::kw_import)) &&
  750. !InMacroArgs && !DisableMacroExpansion &&
  751. (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
  752. CurLexerKind != CLK_CachingLexer) {
  753. ModuleImportLoc = Identifier.getLocation();
  754. NamedModuleImportPath.clear();
  755. IsAtImport = true;
  756. ModuleImportExpectsIdentifier = true;
  757. CurLexerKind = CLK_LexAfterModuleImport;
  758. }
  759. return true;
  760. }
  761. void Preprocessor::Lex(Token &Result) {
  762. ++LexLevel;
  763. // We loop here until a lex function returns a token; this avoids recursion.
  764. bool ReturnedToken;
  765. do {
  766. switch (CurLexerKind) {
  767. case CLK_Lexer:
  768. ReturnedToken = CurLexer->Lex(Result);
  769. break;
  770. case CLK_TokenLexer:
  771. ReturnedToken = CurTokenLexer->Lex(Result);
  772. break;
  773. case CLK_CachingLexer:
  774. CachingLex(Result);
  775. ReturnedToken = true;
  776. break;
  777. case CLK_DependencyDirectivesLexer:
  778. ReturnedToken = CurLexer->LexDependencyDirectiveToken(Result);
  779. break;
  780. case CLK_LexAfterModuleImport:
  781. ReturnedToken = LexAfterModuleImport(Result);
  782. break;
  783. }
  784. } while (!ReturnedToken);
  785. if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
  786. return;
  787. if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
  788. // Remember the identifier before code completion token.
  789. setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
  790. setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
  791. // Set IdenfitierInfo to null to avoid confusing code that handles both
  792. // identifiers and completion tokens.
  793. Result.setIdentifierInfo(nullptr);
  794. }
  795. // Update StdCXXImportSeqState to track our position within a C++20 import-seq
  796. // if this token is being produced as a result of phase 4 of translation.
  797. // Update TrackGMFState to decide if we are currently in a Global Module
  798. // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
  799. // depends on the prevailing StdCXXImportSeq state in two cases.
  800. if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
  801. !Result.getFlag(Token::IsReinjected)) {
  802. switch (Result.getKind()) {
  803. case tok::l_paren: case tok::l_square: case tok::l_brace:
  804. StdCXXImportSeqState.handleOpenBracket();
  805. break;
  806. case tok::r_paren: case tok::r_square:
  807. StdCXXImportSeqState.handleCloseBracket();
  808. break;
  809. case tok::r_brace:
  810. StdCXXImportSeqState.handleCloseBrace();
  811. break;
  812. // This token is injected to represent the translation of '#include "a.h"'
  813. // into "import a.h;". Mimic the notional ';'.
  814. case tok::annot_module_include:
  815. case tok::semi:
  816. TrackGMFState.handleSemi();
  817. StdCXXImportSeqState.handleSemi();
  818. ModuleDeclState.handleSemi();
  819. break;
  820. case tok::header_name:
  821. case tok::annot_header_unit:
  822. StdCXXImportSeqState.handleHeaderName();
  823. break;
  824. case tok::kw_export:
  825. TrackGMFState.handleExport();
  826. StdCXXImportSeqState.handleExport();
  827. ModuleDeclState.handleExport();
  828. break;
  829. case tok::colon:
  830. ModuleDeclState.handleColon();
  831. break;
  832. case tok::period:
  833. ModuleDeclState.handlePeriod();
  834. break;
  835. case tok::identifier:
  836. if (Result.getIdentifierInfo()->isModulesImport()) {
  837. TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
  838. StdCXXImportSeqState.handleImport();
  839. if (StdCXXImportSeqState.afterImportSeq()) {
  840. ModuleImportLoc = Result.getLocation();
  841. NamedModuleImportPath.clear();
  842. IsAtImport = false;
  843. ModuleImportExpectsIdentifier = true;
  844. CurLexerKind = CLK_LexAfterModuleImport;
  845. }
  846. break;
  847. } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
  848. TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
  849. ModuleDeclState.handleModule();
  850. break;
  851. } else {
  852. ModuleDeclState.handleIdentifier(Result.getIdentifierInfo());
  853. if (ModuleDeclState.isModuleCandidate())
  854. break;
  855. }
  856. [[fallthrough]];
  857. default:
  858. TrackGMFState.handleMisc();
  859. StdCXXImportSeqState.handleMisc();
  860. ModuleDeclState.handleMisc();
  861. break;
  862. }
  863. }
  864. LastTokenWasAt = Result.is(tok::at);
  865. --LexLevel;
  866. if ((LexLevel == 0 || PreprocessToken) &&
  867. !Result.getFlag(Token::IsReinjected)) {
  868. if (LexLevel == 0)
  869. ++TokenCount;
  870. if (OnToken)
  871. OnToken(Result);
  872. }
  873. }
  874. /// Lex a header-name token (including one formed from header-name-tokens if
  875. /// \p AllowConcatenation is \c true).
  876. ///
  877. /// \param FilenameTok Filled in with the next token. On success, this will
  878. /// be either a header_name token. On failure, it will be whatever other
  879. /// token was found instead.
  880. /// \param AllowMacroExpansion If \c true, allow the header name to be formed
  881. /// by macro expansion (concatenating tokens as necessary if the first
  882. /// token is a '<').
  883. /// \return \c true if we reached EOD or EOF while looking for a > token in
  884. /// a concatenated header name and diagnosed it. \c false otherwise.
  885. bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
  886. // Lex using header-name tokenization rules if tokens are being lexed from
  887. // a file. Just grab a token normally if we're in a macro expansion.
  888. if (CurPPLexer)
  889. CurPPLexer->LexIncludeFilename(FilenameTok);
  890. else
  891. Lex(FilenameTok);
  892. // This could be a <foo/bar.h> file coming from a macro expansion. In this
  893. // case, glue the tokens together into an angle_string_literal token.
  894. SmallString<128> FilenameBuffer;
  895. if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
  896. bool StartOfLine = FilenameTok.isAtStartOfLine();
  897. bool LeadingSpace = FilenameTok.hasLeadingSpace();
  898. bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
  899. SourceLocation Start = FilenameTok.getLocation();
  900. SourceLocation End;
  901. FilenameBuffer.push_back('<');
  902. // Consume tokens until we find a '>'.
  903. // FIXME: A header-name could be formed starting or ending with an
  904. // alternative token. It's not clear whether that's ill-formed in all
  905. // cases.
  906. while (FilenameTok.isNot(tok::greater)) {
  907. Lex(FilenameTok);
  908. if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
  909. Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
  910. Diag(Start, diag::note_matching) << tok::less;
  911. return true;
  912. }
  913. End = FilenameTok.getLocation();
  914. // FIXME: Provide code completion for #includes.
  915. if (FilenameTok.is(tok::code_completion)) {
  916. setCodeCompletionReached();
  917. Lex(FilenameTok);
  918. continue;
  919. }
  920. // Append the spelling of this token to the buffer. If there was a space
  921. // before it, add it now.
  922. if (FilenameTok.hasLeadingSpace())
  923. FilenameBuffer.push_back(' ');
  924. // Get the spelling of the token, directly into FilenameBuffer if
  925. // possible.
  926. size_t PreAppendSize = FilenameBuffer.size();
  927. FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
  928. const char *BufPtr = &FilenameBuffer[PreAppendSize];
  929. unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
  930. // If the token was spelled somewhere else, copy it into FilenameBuffer.
  931. if (BufPtr != &FilenameBuffer[PreAppendSize])
  932. memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
  933. // Resize FilenameBuffer to the correct size.
  934. if (FilenameTok.getLength() != ActualLen)
  935. FilenameBuffer.resize(PreAppendSize + ActualLen);
  936. }
  937. FilenameTok.startToken();
  938. FilenameTok.setKind(tok::header_name);
  939. FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
  940. FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
  941. FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
  942. CreateString(FilenameBuffer, FilenameTok, Start, End);
  943. } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
  944. // Convert a string-literal token of the form " h-char-sequence "
  945. // (produced by macro expansion) into a header-name token.
  946. //
  947. // The rules for header-names don't quite match the rules for
  948. // string-literals, but all the places where they differ result in
  949. // undefined behavior, so we can and do treat them the same.
  950. //
  951. // A string-literal with a prefix or suffix is not translated into a
  952. // header-name. This could theoretically be observable via the C++20
  953. // context-sensitive header-name formation rules.
  954. StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
  955. if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
  956. FilenameTok.setKind(tok::header_name);
  957. }
  958. return false;
  959. }
  960. /// Collect the tokens of a C++20 pp-import-suffix.
  961. void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
  962. // FIXME: For error recovery, consider recognizing attribute syntax here
  963. // and terminating / diagnosing a missing semicolon if we find anything
  964. // else? (Can we leave that to the parser?)
  965. unsigned BracketDepth = 0;
  966. while (true) {
  967. Toks.emplace_back();
  968. Lex(Toks.back());
  969. switch (Toks.back().getKind()) {
  970. case tok::l_paren: case tok::l_square: case tok::l_brace:
  971. ++BracketDepth;
  972. break;
  973. case tok::r_paren: case tok::r_square: case tok::r_brace:
  974. if (BracketDepth == 0)
  975. return;
  976. --BracketDepth;
  977. break;
  978. case tok::semi:
  979. if (BracketDepth == 0)
  980. return;
  981. break;
  982. case tok::eof:
  983. return;
  984. default:
  985. break;
  986. }
  987. }
  988. }
  989. /// Lex a token following the 'import' contextual keyword.
  990. ///
  991. /// pp-import: [C++20]
  992. /// import header-name pp-import-suffix[opt] ;
  993. /// import header-name-tokens pp-import-suffix[opt] ;
  994. /// [ObjC] @ import module-name ;
  995. /// [Clang] import module-name ;
  996. ///
  997. /// header-name-tokens:
  998. /// string-literal
  999. /// < [any sequence of preprocessing-tokens other than >] >
  1000. ///
  1001. /// module-name:
  1002. /// module-name-qualifier[opt] identifier
  1003. ///
  1004. /// module-name-qualifier
  1005. /// module-name-qualifier[opt] identifier .
  1006. ///
  1007. /// We respond to a pp-import by importing macros from the named module.
  1008. bool Preprocessor::LexAfterModuleImport(Token &Result) {
  1009. // Figure out what kind of lexer we actually have.
  1010. recomputeCurLexerKind();
  1011. // Lex the next token. The header-name lexing rules are used at the start of
  1012. // a pp-import.
  1013. //
  1014. // For now, we only support header-name imports in C++20 mode.
  1015. // FIXME: Should we allow this in all language modes that support an import
  1016. // declaration as an extension?
  1017. if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
  1018. if (LexHeaderName(Result))
  1019. return true;
  1020. if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) {
  1021. std::string Name = ModuleDeclState.getPrimaryName().str();
  1022. Name += ":";
  1023. NamedModuleImportPath.push_back(
  1024. {getIdentifierInfo(Name), Result.getLocation()});
  1025. CurLexerKind = CLK_LexAfterModuleImport;
  1026. return true;
  1027. }
  1028. } else {
  1029. Lex(Result);
  1030. }
  1031. // Allocate a holding buffer for a sequence of tokens and introduce it into
  1032. // the token stream.
  1033. auto EnterTokens = [this](ArrayRef<Token> Toks) {
  1034. auto ToksCopy = std::make_unique<Token[]>(Toks.size());
  1035. std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
  1036. EnterTokenStream(std::move(ToksCopy), Toks.size(),
  1037. /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
  1038. };
  1039. bool ImportingHeader = Result.is(tok::header_name);
  1040. // Check for a header-name.
  1041. SmallVector<Token, 32> Suffix;
  1042. if (ImportingHeader) {
  1043. // Enter the header-name token into the token stream; a Lex action cannot
  1044. // both return a token and cache tokens (doing so would corrupt the token
  1045. // cache if the call to Lex comes from CachingLex / PeekAhead).
  1046. Suffix.push_back(Result);
  1047. // Consume the pp-import-suffix and expand any macros in it now. We'll add
  1048. // it back into the token stream later.
  1049. CollectPpImportSuffix(Suffix);
  1050. if (Suffix.back().isNot(tok::semi)) {
  1051. // This is not a pp-import after all.
  1052. EnterTokens(Suffix);
  1053. return false;
  1054. }
  1055. // C++2a [cpp.module]p1:
  1056. // The ';' preprocessing-token terminating a pp-import shall not have
  1057. // been produced by macro replacement.
  1058. SourceLocation SemiLoc = Suffix.back().getLocation();
  1059. if (SemiLoc.isMacroID())
  1060. Diag(SemiLoc, diag::err_header_import_semi_in_macro);
  1061. // Reconstitute the import token.
  1062. Token ImportTok;
  1063. ImportTok.startToken();
  1064. ImportTok.setKind(tok::kw_import);
  1065. ImportTok.setLocation(ModuleImportLoc);
  1066. ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
  1067. ImportTok.setLength(6);
  1068. auto Action = HandleHeaderIncludeOrImport(
  1069. /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
  1070. switch (Action.Kind) {
  1071. case ImportAction::None:
  1072. break;
  1073. case ImportAction::ModuleBegin:
  1074. // Let the parser know we're textually entering the module.
  1075. Suffix.emplace_back();
  1076. Suffix.back().startToken();
  1077. Suffix.back().setKind(tok::annot_module_begin);
  1078. Suffix.back().setLocation(SemiLoc);
  1079. Suffix.back().setAnnotationEndLoc(SemiLoc);
  1080. Suffix.back().setAnnotationValue(Action.ModuleForHeader);
  1081. [[fallthrough]];
  1082. case ImportAction::ModuleImport:
  1083. case ImportAction::HeaderUnitImport:
  1084. case ImportAction::SkippedModuleImport:
  1085. // We chose to import (or textually enter) the file. Convert the
  1086. // header-name token into a header unit annotation token.
  1087. Suffix[0].setKind(tok::annot_header_unit);
  1088. Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
  1089. Suffix[0].setAnnotationValue(Action.ModuleForHeader);
  1090. // FIXME: Call the moduleImport callback?
  1091. break;
  1092. case ImportAction::Failure:
  1093. assert(TheModuleLoader.HadFatalFailure &&
  1094. "This should be an early exit only to a fatal error");
  1095. Result.setKind(tok::eof);
  1096. CurLexer->cutOffLexing();
  1097. EnterTokens(Suffix);
  1098. return true;
  1099. }
  1100. EnterTokens(Suffix);
  1101. return false;
  1102. }
  1103. // The token sequence
  1104. //
  1105. // import identifier (. identifier)*
  1106. //
  1107. // indicates a module import directive. We already saw the 'import'
  1108. // contextual keyword, so now we're looking for the identifiers.
  1109. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  1110. // We expected to see an identifier here, and we did; continue handling
  1111. // identifiers.
  1112. NamedModuleImportPath.push_back(
  1113. std::make_pair(Result.getIdentifierInfo(), Result.getLocation()));
  1114. ModuleImportExpectsIdentifier = false;
  1115. CurLexerKind = CLK_LexAfterModuleImport;
  1116. return true;
  1117. }
  1118. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  1119. // see the next identifier. (We can also see a '[[' that begins an
  1120. // attribute-specifier-seq here under the C++ Modules TS.)
  1121. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  1122. ModuleImportExpectsIdentifier = true;
  1123. CurLexerKind = CLK_LexAfterModuleImport;
  1124. return true;
  1125. }
  1126. // If we didn't recognize a module name at all, this is not a (valid) import.
  1127. if (NamedModuleImportPath.empty() || Result.is(tok::eof))
  1128. return true;
  1129. // Consume the pp-import-suffix and expand any macros in it now, if we're not
  1130. // at the semicolon already.
  1131. SourceLocation SemiLoc = Result.getLocation();
  1132. if (Result.isNot(tok::semi)) {
  1133. Suffix.push_back(Result);
  1134. CollectPpImportSuffix(Suffix);
  1135. if (Suffix.back().isNot(tok::semi)) {
  1136. // This is not an import after all.
  1137. EnterTokens(Suffix);
  1138. return false;
  1139. }
  1140. SemiLoc = Suffix.back().getLocation();
  1141. }
  1142. // Under the Modules TS, the dot is just part of the module name, and not
  1143. // a real hierarchy separator. Flatten such module names now.
  1144. //
  1145. // FIXME: Is this the right level to be performing this transformation?
  1146. std::string FlatModuleName;
  1147. if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
  1148. for (auto &Piece : NamedModuleImportPath) {
  1149. // If the FlatModuleName ends with colon, it implies it is a partition.
  1150. if (!FlatModuleName.empty() && FlatModuleName.back() != ':')
  1151. FlatModuleName += ".";
  1152. FlatModuleName += Piece.first->getName();
  1153. }
  1154. SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;
  1155. NamedModuleImportPath.clear();
  1156. NamedModuleImportPath.push_back(
  1157. std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
  1158. }
  1159. Module *Imported = nullptr;
  1160. // We don't/shouldn't load the standard c++20 modules when preprocessing.
  1161. if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {
  1162. Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  1163. NamedModuleImportPath,
  1164. Module::Hidden,
  1165. /*IsInclusionDirective=*/false);
  1166. if (Imported)
  1167. makeModuleVisible(Imported, SemiLoc);
  1168. }
  1169. if (Callbacks)
  1170. Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
  1171. if (!Suffix.empty()) {
  1172. EnterTokens(Suffix);
  1173. return false;
  1174. }
  1175. return true;
  1176. }
  1177. void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
  1178. CurSubmoduleState->VisibleModules.setVisible(
  1179. M, Loc, [](Module *) {},
  1180. [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
  1181. // FIXME: Include the path in the diagnostic.
  1182. // FIXME: Include the import location for the conflicting module.
  1183. Diag(ModuleImportLoc, diag::warn_module_conflict)
  1184. << Path[0]->getFullModuleName()
  1185. << Conflict->getFullModuleName()
  1186. << Message;
  1187. });
  1188. // Add this module to the imports list of the currently-built submodule.
  1189. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
  1190. BuildingSubmoduleStack.back().M->Imports.insert(M);
  1191. }
  1192. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  1193. const char *DiagnosticTag,
  1194. bool AllowMacroExpansion) {
  1195. // We need at least one string literal.
  1196. if (Result.isNot(tok::string_literal)) {
  1197. Diag(Result, diag::err_expected_string_literal)
  1198. << /*Source='in...'*/0 << DiagnosticTag;
  1199. return false;
  1200. }
  1201. // Lex string literal tokens, optionally with macro expansion.
  1202. SmallVector<Token, 4> StrToks;
  1203. do {
  1204. StrToks.push_back(Result);
  1205. if (Result.hasUDSuffix())
  1206. Diag(Result, diag::err_invalid_string_udl);
  1207. if (AllowMacroExpansion)
  1208. Lex(Result);
  1209. else
  1210. LexUnexpandedToken(Result);
  1211. } while (Result.is(tok::string_literal));
  1212. // Concatenate and parse the strings.
  1213. StringLiteralParser Literal(StrToks, *this);
  1214. assert(Literal.isOrdinary() && "Didn't allow wide strings in");
  1215. if (Literal.hadError)
  1216. return false;
  1217. if (Literal.Pascal) {
  1218. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  1219. << /*Source='in...'*/0 << DiagnosticTag;
  1220. return false;
  1221. }
  1222. String = std::string(Literal.GetString());
  1223. return true;
  1224. }
  1225. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  1226. assert(Tok.is(tok::numeric_constant));
  1227. SmallString<8> IntegerBuffer;
  1228. bool NumberInvalid = false;
  1229. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  1230. if (NumberInvalid)
  1231. return false;
  1232. NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
  1233. getLangOpts(), getTargetInfo(),
  1234. getDiagnostics());
  1235. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  1236. return false;
  1237. llvm::APInt APVal(64, 0);
  1238. if (Literal.GetIntegerValue(APVal))
  1239. return false;
  1240. Lex(Tok);
  1241. Value = APVal.getLimitedValue();
  1242. return true;
  1243. }
  1244. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  1245. assert(Handler && "NULL comment handler");
  1246. assert(!llvm::is_contained(CommentHandlers, Handler) &&
  1247. "Comment handler already registered");
  1248. CommentHandlers.push_back(Handler);
  1249. }
  1250. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  1251. std::vector<CommentHandler *>::iterator Pos =
  1252. llvm::find(CommentHandlers, Handler);
  1253. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  1254. CommentHandlers.erase(Pos);
  1255. }
  1256. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  1257. bool AnyPendingTokens = false;
  1258. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  1259. HEnd = CommentHandlers.end();
  1260. H != HEnd; ++H) {
  1261. if ((*H)->HandleComment(*this, Comment))
  1262. AnyPendingTokens = true;
  1263. }
  1264. if (!AnyPendingTokens || getCommentRetentionState())
  1265. return false;
  1266. Lex(result);
  1267. return true;
  1268. }
  1269. void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
  1270. const MacroAnnotations &A =
  1271. getMacroAnnotations(Identifier.getIdentifierInfo());
  1272. assert(A.DeprecationInfo &&
  1273. "Macro deprecation warning without recorded annotation!");
  1274. const MacroAnnotationInfo &Info = *A.DeprecationInfo;
  1275. if (Info.Message.empty())
  1276. Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
  1277. << Identifier.getIdentifierInfo() << 0;
  1278. else
  1279. Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
  1280. << Identifier.getIdentifierInfo() << 1 << Info.Message;
  1281. Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
  1282. }
  1283. void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
  1284. const MacroAnnotations &A =
  1285. getMacroAnnotations(Identifier.getIdentifierInfo());
  1286. assert(A.RestrictExpansionInfo &&
  1287. "Macro restricted expansion warning without recorded annotation!");
  1288. const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
  1289. if (Info.Message.empty())
  1290. Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
  1291. << Identifier.getIdentifierInfo() << 0;
  1292. else
  1293. Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
  1294. << Identifier.getIdentifierInfo() << 1 << Info.Message;
  1295. Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
  1296. }
  1297. void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
  1298. bool IsUndef) const {
  1299. const MacroAnnotations &A =
  1300. getMacroAnnotations(Identifier.getIdentifierInfo());
  1301. assert(A.FinalAnnotationLoc &&
  1302. "Final macro warning without recorded annotation!");
  1303. Diag(Identifier, diag::warn_pragma_final_macro)
  1304. << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
  1305. Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
  1306. }
  1307. ModuleLoader::~ModuleLoader() = default;
  1308. CommentHandler::~CommentHandler() = default;
  1309. EmptylineHandler::~EmptylineHandler() = default;
  1310. CodeCompletionHandler::~CodeCompletionHandler() = default;
  1311. void Preprocessor::createPreprocessingRecord() {
  1312. if (Record)
  1313. return;
  1314. Record = new PreprocessingRecord(getSourceManager());
  1315. addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
  1316. }