Preprocessor.cpp 50 KB

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