Preprocessor.cpp 51 KB

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