TokenLexer.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. //===- TokenLexer.cpp - Lex from a token stream ---------------------------===//
  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 TokenLexer interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Lex/TokenLexer.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/IdentifierTable.h"
  15. #include "clang/Basic/LangOptions.h"
  16. #include "clang/Basic/SourceLocation.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Basic/TokenKinds.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/Lexer.h"
  21. #include "clang/Lex/MacroArgs.h"
  22. #include "clang/Lex/MacroInfo.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "clang/Lex/Token.h"
  25. #include "clang/Lex/VariadicMacroSupport.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SmallString.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/iterator_range.h"
  31. #include <cassert>
  32. #include <cstring>
  33. #include <optional>
  34. using namespace clang;
  35. /// Create a TokenLexer for the specified macro with the specified actual
  36. /// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
  37. void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
  38. MacroArgs *Actuals) {
  39. // If the client is reusing a TokenLexer, make sure to free any memory
  40. // associated with it.
  41. destroy();
  42. Macro = MI;
  43. ActualArgs = Actuals;
  44. CurTokenIdx = 0;
  45. ExpandLocStart = Tok.getLocation();
  46. ExpandLocEnd = ELEnd;
  47. AtStartOfLine = Tok.isAtStartOfLine();
  48. HasLeadingSpace = Tok.hasLeadingSpace();
  49. NextTokGetsSpace = false;
  50. Tokens = &*Macro->tokens_begin();
  51. OwnsTokens = false;
  52. DisableMacroExpansion = false;
  53. IsReinject = false;
  54. NumTokens = Macro->tokens_end()-Macro->tokens_begin();
  55. MacroExpansionStart = SourceLocation();
  56. SourceManager &SM = PP.getSourceManager();
  57. MacroStartSLocOffset = SM.getNextLocalOffset();
  58. if (NumTokens > 0) {
  59. assert(Tokens[0].getLocation().isValid());
  60. assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
  61. "Macro defined in macro?");
  62. assert(ExpandLocStart.isValid());
  63. // Reserve a source location entry chunk for the length of the macro
  64. // definition. Tokens that get lexed directly from the definition will
  65. // have their locations pointing inside this chunk. This is to avoid
  66. // creating separate source location entries for each token.
  67. MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
  68. MacroDefLength = Macro->getDefinitionLength(SM);
  69. MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
  70. ExpandLocStart,
  71. ExpandLocEnd,
  72. MacroDefLength);
  73. }
  74. // If this is a function-like macro, expand the arguments and change
  75. // Tokens to point to the expanded tokens.
  76. if (Macro->isFunctionLike() && Macro->getNumParams())
  77. ExpandFunctionArguments();
  78. // Mark the macro as currently disabled, so that it is not recursively
  79. // expanded. The macro must be disabled only after argument pre-expansion of
  80. // function-like macro arguments occurs.
  81. Macro->DisableMacro();
  82. }
  83. /// Create a TokenLexer for the specified token stream. This does not
  84. /// take ownership of the specified token vector.
  85. void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
  86. bool disableMacroExpansion, bool ownsTokens,
  87. bool isReinject) {
  88. assert(!isReinject || disableMacroExpansion);
  89. // If the client is reusing a TokenLexer, make sure to free any memory
  90. // associated with it.
  91. destroy();
  92. Macro = nullptr;
  93. ActualArgs = nullptr;
  94. Tokens = TokArray;
  95. OwnsTokens = ownsTokens;
  96. DisableMacroExpansion = disableMacroExpansion;
  97. IsReinject = isReinject;
  98. NumTokens = NumToks;
  99. CurTokenIdx = 0;
  100. ExpandLocStart = ExpandLocEnd = SourceLocation();
  101. AtStartOfLine = false;
  102. HasLeadingSpace = false;
  103. NextTokGetsSpace = false;
  104. MacroExpansionStart = SourceLocation();
  105. // Set HasLeadingSpace/AtStartOfLine so that the first token will be
  106. // returned unmodified.
  107. if (NumToks != 0) {
  108. AtStartOfLine = TokArray[0].isAtStartOfLine();
  109. HasLeadingSpace = TokArray[0].hasLeadingSpace();
  110. }
  111. }
  112. void TokenLexer::destroy() {
  113. // If this was a function-like macro that actually uses its arguments, delete
  114. // the expanded tokens.
  115. if (OwnsTokens) {
  116. delete [] Tokens;
  117. Tokens = nullptr;
  118. OwnsTokens = false;
  119. }
  120. // TokenLexer owns its formal arguments.
  121. if (ActualArgs) ActualArgs->destroy(PP);
  122. }
  123. bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
  124. SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
  125. unsigned MacroArgNo, Preprocessor &PP) {
  126. // Is the macro argument __VA_ARGS__?
  127. if (!Macro->isVariadic() || MacroArgNo != Macro->getNumParams()-1)
  128. return false;
  129. // In Microsoft-compatibility mode, a comma is removed in the expansion
  130. // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty. This extension is
  131. // not supported by gcc.
  132. if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
  133. return false;
  134. // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
  135. // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
  136. // named arguments, where it remains. In all other modes, including C99
  137. // with GNU extensions, it is removed regardless of named arguments.
  138. // Microsoft also appears to support this extension, unofficially.
  139. if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode
  140. && Macro->getNumParams() < 2)
  141. return false;
  142. // Is a comma available to be removed?
  143. if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
  144. return false;
  145. // Issue an extension diagnostic for the paste operator.
  146. if (HasPasteOperator)
  147. PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
  148. // Remove the comma.
  149. ResultToks.pop_back();
  150. if (!ResultToks.empty()) {
  151. // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
  152. // then removal of the comma should produce a placemarker token (in C99
  153. // terms) which we model by popping off the previous ##, giving us a plain
  154. // "X" when __VA_ARGS__ is empty.
  155. if (ResultToks.back().is(tok::hashhash))
  156. ResultToks.pop_back();
  157. // Remember that this comma was elided.
  158. ResultToks.back().setFlag(Token::CommaAfterElided);
  159. }
  160. // Never add a space, even if the comma, ##, or arg had a space.
  161. NextTokGetsSpace = false;
  162. return true;
  163. }
  164. void TokenLexer::stringifyVAOPTContents(
  165. SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,
  166. const SourceLocation VAOPTClosingParenLoc) {
  167. const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();
  168. const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;
  169. Token *const VAOPTTokens =
  170. NumVAOptTokens ? &ResultToks[NumToksPriorToVAOpt] : nullptr;
  171. SmallVector<Token, 64> ConcatenatedVAOPTResultToks;
  172. // FIXME: Should we keep track within VCtx that we did or didnot
  173. // encounter pasting - and only then perform this loop.
  174. // Perform token pasting (concatenation) prior to stringization.
  175. for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;
  176. ++CurTokenIdx) {
  177. if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {
  178. assert(CurTokenIdx != 0 &&
  179. "Can not have __VAOPT__ contents begin with a ##");
  180. Token &LHS = VAOPTTokens[CurTokenIdx - 1];
  181. pasteTokens(LHS, llvm::ArrayRef(VAOPTTokens, NumVAOptTokens),
  182. CurTokenIdx);
  183. // Replace the token prior to the first ## in this iteration.
  184. ConcatenatedVAOPTResultToks.back() = LHS;
  185. if (CurTokenIdx == NumVAOptTokens)
  186. break;
  187. }
  188. ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);
  189. }
  190. ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());
  191. // Get the SourceLocation that represents the start location within
  192. // the macro definition that marks where this string is substituted
  193. // into: i.e. the __VA_OPT__ and the ')' within the spelling of the
  194. // macro definition, and use it to indicate that the stringified token
  195. // was generated from that location.
  196. const SourceLocation ExpansionLocStartWithinMacro =
  197. getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());
  198. const SourceLocation ExpansionLocEndWithinMacro =
  199. getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);
  200. Token StringifiedVAOPT = MacroArgs::StringifyArgument(
  201. &ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,
  202. ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);
  203. if (VCtx.getLeadingSpaceForStringifiedToken())
  204. StringifiedVAOPT.setFlag(Token::LeadingSpace);
  205. StringifiedVAOPT.setFlag(Token::StringifiedInMacro);
  206. // Resize (shrink) the token stream to just capture this stringified token.
  207. ResultToks.resize(NumToksPriorToVAOpt + 1);
  208. ResultToks.back() = StringifiedVAOPT;
  209. }
  210. /// Expand the arguments of a function-like macro so that we can quickly
  211. /// return preexpanded tokens from Tokens.
  212. void TokenLexer::ExpandFunctionArguments() {
  213. SmallVector<Token, 128> ResultToks;
  214. // Loop through 'Tokens', expanding them into ResultToks. Keep
  215. // track of whether we change anything. If not, no need to keep them. If so,
  216. // we install the newly expanded sequence as the new 'Tokens' list.
  217. bool MadeChange = false;
  218. std::optional<bool> CalledWithVariadicArguments;
  219. VAOptExpansionContext VCtx(PP);
  220. for (unsigned I = 0, E = NumTokens; I != E; ++I) {
  221. const Token &CurTok = Tokens[I];
  222. // We don't want a space for the next token after a paste
  223. // operator. In valid code, the token will get smooshed onto the
  224. // preceding one anyway. In assembler-with-cpp mode, invalid
  225. // pastes are allowed through: in this case, we do not want the
  226. // extra whitespace to be added. For example, we want ". ## foo"
  227. // -> ".foo" not ". foo".
  228. if (I != 0 && !Tokens[I-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
  229. NextTokGetsSpace = true;
  230. if (VCtx.isVAOptToken(CurTok)) {
  231. MadeChange = true;
  232. assert(Tokens[I + 1].is(tok::l_paren) &&
  233. "__VA_OPT__ must be followed by '('");
  234. ++I; // Skip the l_paren
  235. VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),
  236. ResultToks.size());
  237. continue;
  238. }
  239. // We have entered into the __VA_OPT__ context, so handle tokens
  240. // appropriately.
  241. if (VCtx.isInVAOpt()) {
  242. // If we are about to process a token that is either an argument to
  243. // __VA_OPT__ or its closing rparen, then:
  244. // 1) If the token is the closing rparen that exits us out of __VA_OPT__,
  245. // perform any necessary stringification or placemarker processing,
  246. // and/or skip to the next token.
  247. // 2) else if macro was invoked without variadic arguments skip this
  248. // token.
  249. // 3) else (macro was invoked with variadic arguments) process the token
  250. // normally.
  251. if (Tokens[I].is(tok::l_paren))
  252. VCtx.sawOpeningParen(Tokens[I].getLocation());
  253. // Continue skipping tokens within __VA_OPT__ if the macro was not
  254. // called with variadic arguments, else let the rest of the loop handle
  255. // this token. Note sawClosingParen() returns true only if the r_paren matches
  256. // the closing r_paren of the __VA_OPT__.
  257. if (!Tokens[I].is(tok::r_paren) || !VCtx.sawClosingParen()) {
  258. // Lazily expand __VA_ARGS__ when we see the first __VA_OPT__.
  259. if (!CalledWithVariadicArguments) {
  260. CalledWithVariadicArguments =
  261. ActualArgs->invokedWithVariadicArgument(Macro, PP);
  262. }
  263. if (!*CalledWithVariadicArguments) {
  264. // Skip this token.
  265. continue;
  266. }
  267. // ... else the macro was called with variadic arguments, and we do not
  268. // have a closing rparen - so process this token normally.
  269. } else {
  270. // Current token is the closing r_paren which marks the end of the
  271. // __VA_OPT__ invocation, so handle any place-marker pasting (if
  272. // empty) by removing hashhash either before (if exists) or after. And
  273. // also stringify the entire contents if VAOPT was preceded by a hash,
  274. // but do so only after any token concatenation that needs to occur
  275. // within the contents of VAOPT.
  276. if (VCtx.hasStringifyOrCharifyBefore()) {
  277. // Replace all the tokens just added from within VAOPT into a single
  278. // stringified token. This requires token-pasting to eagerly occur
  279. // within these tokens. If either the contents of VAOPT were empty
  280. // or the macro wasn't called with any variadic arguments, the result
  281. // is a token that represents an empty string.
  282. stringifyVAOPTContents(ResultToks, VCtx,
  283. /*ClosingParenLoc*/ Tokens[I].getLocation());
  284. } else if (/*No tokens within VAOPT*/
  285. ResultToks.size() == VCtx.getNumberOfTokensPriorToVAOpt()) {
  286. // Treat VAOPT as a placemarker token. Eat either the '##' before the
  287. // RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that
  288. // hashhash was not a placemarker) or the '##'
  289. // after VAOPT, but not both.
  290. if (ResultToks.size() && ResultToks.back().is(tok::hashhash)) {
  291. ResultToks.pop_back();
  292. } else if ((I + 1 != E) && Tokens[I + 1].is(tok::hashhash)) {
  293. ++I; // Skip the following hashhash.
  294. }
  295. } else {
  296. // If there's a ## before the __VA_OPT__, we might have discovered
  297. // that the __VA_OPT__ begins with a placeholder. We delay action on
  298. // that to now to avoid messing up our stashed count of tokens before
  299. // __VA_OPT__.
  300. if (VCtx.beginsWithPlaceholder()) {
  301. assert(VCtx.getNumberOfTokensPriorToVAOpt() > 0 &&
  302. ResultToks.size() >= VCtx.getNumberOfTokensPriorToVAOpt() &&
  303. ResultToks[VCtx.getNumberOfTokensPriorToVAOpt() - 1].is(
  304. tok::hashhash) &&
  305. "no token paste before __VA_OPT__");
  306. ResultToks.erase(ResultToks.begin() +
  307. VCtx.getNumberOfTokensPriorToVAOpt() - 1);
  308. }
  309. // If the expansion of __VA_OPT__ ends with a placeholder, eat any
  310. // following '##' token.
  311. if (VCtx.endsWithPlaceholder() && I + 1 != E &&
  312. Tokens[I + 1].is(tok::hashhash)) {
  313. ++I;
  314. }
  315. }
  316. VCtx.reset();
  317. // We processed __VA_OPT__'s closing paren (and the exit out of
  318. // __VA_OPT__), so skip to the next token.
  319. continue;
  320. }
  321. }
  322. // If we found the stringify operator, get the argument stringified. The
  323. // preprocessor already verified that the following token is a macro
  324. // parameter or __VA_OPT__ when the #define was lexed.
  325. if (CurTok.isOneOf(tok::hash, tok::hashat)) {
  326. int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());
  327. assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&
  328. "Token following # is not an argument or __VA_OPT__!");
  329. if (ArgNo == -1) {
  330. // Handle the __VA_OPT__ case.
  331. VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,
  332. CurTok.is(tok::hashat));
  333. continue;
  334. }
  335. // Else handle the simple argument case.
  336. SourceLocation ExpansionLocStart =
  337. getExpansionLocForMacroDefLoc(CurTok.getLocation());
  338. SourceLocation ExpansionLocEnd =
  339. getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());
  340. bool Charify = CurTok.is(tok::hashat);
  341. const Token *UnexpArg = ActualArgs->getUnexpArgument(ArgNo);
  342. Token Res = MacroArgs::StringifyArgument(
  343. UnexpArg, PP, Charify, ExpansionLocStart, ExpansionLocEnd);
  344. Res.setFlag(Token::StringifiedInMacro);
  345. // The stringified/charified string leading space flag gets set to match
  346. // the #/#@ operator.
  347. if (NextTokGetsSpace)
  348. Res.setFlag(Token::LeadingSpace);
  349. ResultToks.push_back(Res);
  350. MadeChange = true;
  351. ++I; // Skip arg name.
  352. NextTokGetsSpace = false;
  353. continue;
  354. }
  355. // Find out if there is a paste (##) operator before or after the token.
  356. bool NonEmptyPasteBefore =
  357. !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
  358. bool PasteBefore = I != 0 && Tokens[I-1].is(tok::hashhash);
  359. bool PasteAfter = I+1 != E && Tokens[I+1].is(tok::hashhash);
  360. bool RParenAfter = I+1 != E && Tokens[I+1].is(tok::r_paren);
  361. assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&
  362. "unexpected ## in ResultToks");
  363. // Otherwise, if this is not an argument token, just add the token to the
  364. // output buffer.
  365. IdentifierInfo *II = CurTok.getIdentifierInfo();
  366. int ArgNo = II ? Macro->getParameterNum(II) : -1;
  367. if (ArgNo == -1) {
  368. // This isn't an argument, just add it.
  369. ResultToks.push_back(CurTok);
  370. if (NextTokGetsSpace) {
  371. ResultToks.back().setFlag(Token::LeadingSpace);
  372. NextTokGetsSpace = false;
  373. } else if (PasteBefore && !NonEmptyPasteBefore)
  374. ResultToks.back().clearFlag(Token::LeadingSpace);
  375. continue;
  376. }
  377. // An argument is expanded somehow, the result is different than the
  378. // input.
  379. MadeChange = true;
  380. // Otherwise, this is a use of the argument.
  381. // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
  382. // are no trailing commas if __VA_ARGS__ is empty.
  383. if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
  384. MaybeRemoveCommaBeforeVaArgs(ResultToks,
  385. /*HasPasteOperator=*/false,
  386. Macro, ArgNo, PP))
  387. continue;
  388. // If it is not the LHS/RHS of a ## operator, we must pre-expand the
  389. // argument and substitute the expanded tokens into the result. This is
  390. // C99 6.10.3.1p1.
  391. if (!PasteBefore && !PasteAfter) {
  392. const Token *ResultArgToks;
  393. // Only preexpand the argument if it could possibly need it. This
  394. // avoids some work in common cases.
  395. const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
  396. if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
  397. ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
  398. else
  399. ResultArgToks = ArgTok; // Use non-preexpanded tokens.
  400. // If the arg token expanded into anything, append it.
  401. if (ResultArgToks->isNot(tok::eof)) {
  402. size_t FirstResult = ResultToks.size();
  403. unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
  404. ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
  405. // In Microsoft-compatibility mode, we follow MSVC's preprocessing
  406. // behavior by not considering single commas from nested macro
  407. // expansions as argument separators. Set a flag on the token so we can
  408. // test for this later when the macro expansion is processed.
  409. if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
  410. ResultToks.back().is(tok::comma))
  411. ResultToks.back().setFlag(Token::IgnoredComma);
  412. // If the '##' came from expanding an argument, turn it into 'unknown'
  413. // to avoid pasting.
  414. for (Token &Tok : llvm::drop_begin(ResultToks, FirstResult))
  415. if (Tok.is(tok::hashhash))
  416. Tok.setKind(tok::unknown);
  417. if(ExpandLocStart.isValid()) {
  418. updateLocForMacroArgTokens(CurTok.getLocation(),
  419. ResultToks.begin()+FirstResult,
  420. ResultToks.end());
  421. }
  422. // If any tokens were substituted from the argument, the whitespace
  423. // before the first token should match the whitespace of the arg
  424. // identifier.
  425. ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
  426. NextTokGetsSpace);
  427. ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
  428. NextTokGetsSpace = false;
  429. } else {
  430. // We're creating a placeholder token. Usually this doesn't matter,
  431. // but it can affect paste behavior when at the start or end of a
  432. // __VA_OPT__.
  433. if (NonEmptyPasteBefore) {
  434. // We're imagining a placeholder token is inserted here. If this is
  435. // the first token in a __VA_OPT__ after a ##, delete the ##.
  436. assert(VCtx.isInVAOpt() && "should only happen inside a __VA_OPT__");
  437. VCtx.hasPlaceholderAfterHashhashAtStart();
  438. }
  439. if (RParenAfter)
  440. VCtx.hasPlaceholderBeforeRParen();
  441. }
  442. continue;
  443. }
  444. // Okay, we have a token that is either the LHS or RHS of a paste (##)
  445. // argument. It gets substituted as its non-pre-expanded tokens.
  446. const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
  447. unsigned NumToks = MacroArgs::getArgLength(ArgToks);
  448. if (NumToks) { // Not an empty argument?
  449. bool VaArgsPseudoPaste = false;
  450. // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
  451. // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
  452. // the expander tries to paste ',' with the first token of the __VA_ARGS__
  453. // expansion.
  454. if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
  455. ResultToks[ResultToks.size()-2].is(tok::comma) &&
  456. (unsigned)ArgNo == Macro->getNumParams()-1 &&
  457. Macro->isVariadic()) {
  458. VaArgsPseudoPaste = true;
  459. // Remove the paste operator, report use of the extension.
  460. PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
  461. }
  462. ResultToks.append(ArgToks, ArgToks+NumToks);
  463. // If the '##' came from expanding an argument, turn it into 'unknown'
  464. // to avoid pasting.
  465. for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,
  466. ResultToks.end())) {
  467. if (Tok.is(tok::hashhash))
  468. Tok.setKind(tok::unknown);
  469. }
  470. if (ExpandLocStart.isValid()) {
  471. updateLocForMacroArgTokens(CurTok.getLocation(),
  472. ResultToks.end()-NumToks, ResultToks.end());
  473. }
  474. // Transfer the leading whitespace information from the token
  475. // (the macro argument) onto the first token of the
  476. // expansion. Note that we don't do this for the GNU
  477. // pseudo-paste extension ", ## __VA_ARGS__".
  478. if (!VaArgsPseudoPaste) {
  479. ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,
  480. false);
  481. ResultToks[ResultToks.size() - NumToks].setFlagValue(
  482. Token::LeadingSpace, NextTokGetsSpace);
  483. }
  484. NextTokGetsSpace = false;
  485. continue;
  486. }
  487. // If an empty argument is on the LHS or RHS of a paste, the standard (C99
  488. // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
  489. // implement this by eating ## operators when a LHS or RHS expands to
  490. // empty.
  491. if (PasteAfter) {
  492. // Discard the argument token and skip (don't copy to the expansion
  493. // buffer) the paste operator after it.
  494. ++I;
  495. continue;
  496. }
  497. if (RParenAfter)
  498. VCtx.hasPlaceholderBeforeRParen();
  499. // If this is on the RHS of a paste operator, we've already copied the
  500. // paste operator to the ResultToks list, unless the LHS was empty too.
  501. // Remove it.
  502. assert(PasteBefore);
  503. if (NonEmptyPasteBefore) {
  504. assert(ResultToks.back().is(tok::hashhash));
  505. // Do not remove the paste operator if it is the one before __VA_OPT__
  506. // (and we are still processing tokens within VA_OPT). We handle the case
  507. // of removing the paste operator if __VA_OPT__ reduces to the notional
  508. // placemarker above when we encounter the closing paren of VA_OPT.
  509. if (!VCtx.isInVAOpt() ||
  510. ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt())
  511. ResultToks.pop_back();
  512. else
  513. VCtx.hasPlaceholderAfterHashhashAtStart();
  514. }
  515. // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
  516. // and if the macro had at least one real argument, and if the token before
  517. // the ## was a comma, remove the comma. This is a GCC extension which is
  518. // disabled when using -std=c99.
  519. if (ActualArgs->isVarargsElidedUse())
  520. MaybeRemoveCommaBeforeVaArgs(ResultToks,
  521. /*HasPasteOperator=*/true,
  522. Macro, ArgNo, PP);
  523. }
  524. // If anything changed, install this as the new Tokens list.
  525. if (MadeChange) {
  526. assert(!OwnsTokens && "This would leak if we already own the token list");
  527. // This is deleted in the dtor.
  528. NumTokens = ResultToks.size();
  529. // The tokens will be added to Preprocessor's cache and will be removed
  530. // when this TokenLexer finishes lexing them.
  531. Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
  532. // The preprocessor cache of macro expanded tokens owns these tokens,not us.
  533. OwnsTokens = false;
  534. }
  535. }
  536. /// Checks if two tokens form wide string literal.
  537. static bool isWideStringLiteralFromMacro(const Token &FirstTok,
  538. const Token &SecondTok) {
  539. return FirstTok.is(tok::identifier) &&
  540. FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
  541. SecondTok.stringifiedInMacro();
  542. }
  543. /// Lex - Lex and return a token from this macro stream.
  544. bool TokenLexer::Lex(Token &Tok) {
  545. // Lexing off the end of the macro, pop this macro off the expansion stack.
  546. if (isAtEnd()) {
  547. // If this is a macro (not a token stream), mark the macro enabled now
  548. // that it is no longer being expanded.
  549. if (Macro) Macro->EnableMacro();
  550. Tok.startToken();
  551. Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
  552. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
  553. if (CurTokenIdx == 0)
  554. Tok.setFlag(Token::LeadingEmptyMacro);
  555. return PP.HandleEndOfTokenLexer(Tok);
  556. }
  557. SourceManager &SM = PP.getSourceManager();
  558. // If this is the first token of the expanded result, we inherit spacing
  559. // properties later.
  560. bool isFirstToken = CurTokenIdx == 0;
  561. // Get the next token to return.
  562. Tok = Tokens[CurTokenIdx++];
  563. if (IsReinject)
  564. Tok.setFlag(Token::IsReinjected);
  565. bool TokenIsFromPaste = false;
  566. // If this token is followed by a token paste (##) operator, paste the tokens!
  567. // Note that ## is a normal token when not expanding a macro.
  568. if (!isAtEnd() && Macro &&
  569. (Tokens[CurTokenIdx].is(tok::hashhash) ||
  570. // Special processing of L#x macros in -fms-compatibility mode.
  571. // Microsoft compiler is able to form a wide string literal from
  572. // 'L#macro_arg' construct in a function-like macro.
  573. (PP.getLangOpts().MSVCCompat &&
  574. isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])))) {
  575. // When handling the microsoft /##/ extension, the final token is
  576. // returned by pasteTokens, not the pasted token.
  577. if (pasteTokens(Tok))
  578. return true;
  579. TokenIsFromPaste = true;
  580. }
  581. // The token's current location indicate where the token was lexed from. We
  582. // need this information to compute the spelling of the token, but any
  583. // diagnostics for the expanded token should appear as if they came from
  584. // ExpansionLoc. Pull this information together into a new SourceLocation
  585. // that captures all of this.
  586. if (ExpandLocStart.isValid() && // Don't do this for token streams.
  587. // Check that the token's location was not already set properly.
  588. SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
  589. SourceLocation instLoc;
  590. if (Tok.is(tok::comment)) {
  591. instLoc = SM.createExpansionLoc(Tok.getLocation(),
  592. ExpandLocStart,
  593. ExpandLocEnd,
  594. Tok.getLength());
  595. } else {
  596. instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
  597. }
  598. Tok.setLocation(instLoc);
  599. }
  600. // If this is the first token, set the lexical properties of the token to
  601. // match the lexical properties of the macro identifier.
  602. if (isFirstToken) {
  603. Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
  604. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
  605. } else {
  606. // If this is not the first token, we may still need to pass through
  607. // leading whitespace if we've expanded a macro.
  608. if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
  609. if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
  610. }
  611. AtStartOfLine = false;
  612. HasLeadingSpace = false;
  613. // Handle recursive expansion!
  614. if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
  615. // Change the kind of this identifier to the appropriate token kind, e.g.
  616. // turning "for" into a keyword.
  617. IdentifierInfo *II = Tok.getIdentifierInfo();
  618. Tok.setKind(II->getTokenID());
  619. // If this identifier was poisoned and from a paste, emit an error. This
  620. // won't be handled by Preprocessor::HandleIdentifier because this is coming
  621. // from a macro expansion.
  622. if (II->isPoisoned() && TokenIsFromPaste) {
  623. PP.HandlePoisonedIdentifier(Tok);
  624. }
  625. if (!DisableMacroExpansion && II->isHandleIdentifierCase())
  626. return PP.HandleIdentifier(Tok);
  627. }
  628. // Otherwise, return a normal token.
  629. return true;
  630. }
  631. bool TokenLexer::pasteTokens(Token &Tok) {
  632. return pasteTokens(Tok, llvm::ArrayRef(Tokens, NumTokens), CurTokenIdx);
  633. }
  634. /// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##
  635. /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
  636. /// are more ## after it, chomp them iteratively. Return the result as LHSTok.
  637. /// If this returns true, the caller should immediately return the token.
  638. bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
  639. unsigned int &CurIdx) {
  640. assert(CurIdx > 0 && "## can not be the first token within tokens");
  641. assert((TokenStream[CurIdx].is(tok::hashhash) ||
  642. (PP.getLangOpts().MSVCCompat &&
  643. isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&
  644. "Token at this Index must be ## or part of the MSVC 'L "
  645. "#macro-arg' pasting pair");
  646. // MSVC: If previous token was pasted, this must be a recovery from an invalid
  647. // paste operation. Ignore spaces before this token to mimic MSVC output.
  648. // Required for generating valid UUID strings in some MS headers.
  649. if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) &&
  650. TokenStream[CurIdx - 2].is(tok::hashhash))
  651. LHSTok.clearFlag(Token::LeadingSpace);
  652. SmallString<128> Buffer;
  653. const char *ResultTokStrPtr = nullptr;
  654. SourceLocation StartLoc = LHSTok.getLocation();
  655. SourceLocation PasteOpLoc;
  656. auto IsAtEnd = [&TokenStream, &CurIdx] {
  657. return TokenStream.size() == CurIdx;
  658. };
  659. do {
  660. // Consume the ## operator if any.
  661. PasteOpLoc = TokenStream[CurIdx].getLocation();
  662. if (TokenStream[CurIdx].is(tok::hashhash))
  663. ++CurIdx;
  664. assert(!IsAtEnd() && "No token on the RHS of a paste operator!");
  665. // Get the RHS token.
  666. const Token &RHS = TokenStream[CurIdx];
  667. // Allocate space for the result token. This is guaranteed to be enough for
  668. // the two tokens.
  669. Buffer.resize(LHSTok.getLength() + RHS.getLength());
  670. // Get the spelling of the LHS token in Buffer.
  671. const char *BufPtr = &Buffer[0];
  672. bool Invalid = false;
  673. unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);
  674. if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
  675. memcpy(&Buffer[0], BufPtr, LHSLen);
  676. if (Invalid)
  677. return true;
  678. BufPtr = Buffer.data() + LHSLen;
  679. unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
  680. if (Invalid)
  681. return true;
  682. if (RHSLen && BufPtr != &Buffer[LHSLen])
  683. // Really, we want the chars in Buffer!
  684. memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
  685. // Trim excess space.
  686. Buffer.resize(LHSLen+RHSLen);
  687. // Plop the pasted result (including the trailing newline and null) into a
  688. // scratch buffer where we can lex it.
  689. Token ResultTokTmp;
  690. ResultTokTmp.startToken();
  691. // Claim that the tmp token is a string_literal so that we can get the
  692. // character pointer back from CreateString in getLiteralData().
  693. ResultTokTmp.setKind(tok::string_literal);
  694. PP.CreateString(Buffer, ResultTokTmp);
  695. SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
  696. ResultTokStrPtr = ResultTokTmp.getLiteralData();
  697. // Lex the resultant pasted token into Result.
  698. Token Result;
  699. if (LHSTok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
  700. // Common paste case: identifier+identifier = identifier. Avoid creating
  701. // a lexer and other overhead.
  702. PP.IncrementPasteCounter(true);
  703. Result.startToken();
  704. Result.setKind(tok::raw_identifier);
  705. Result.setRawIdentifierData(ResultTokStrPtr);
  706. Result.setLocation(ResultTokLoc);
  707. Result.setLength(LHSLen+RHSLen);
  708. } else {
  709. PP.IncrementPasteCounter(false);
  710. assert(ResultTokLoc.isFileID() &&
  711. "Should be a raw location into scratch buffer");
  712. SourceManager &SourceMgr = PP.getSourceManager();
  713. FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
  714. bool Invalid = false;
  715. const char *ScratchBufStart
  716. = SourceMgr.getBufferData(LocFileID, &Invalid).data();
  717. if (Invalid)
  718. return false;
  719. // Make a lexer to lex this string from. Lex just this one token.
  720. // Make a lexer object so that we lex and expand the paste result.
  721. Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
  722. PP.getLangOpts(), ScratchBufStart,
  723. ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
  724. // Lex a token in raw mode. This way it won't look up identifiers
  725. // automatically, lexing off the end will return an eof token, and
  726. // warnings are disabled. This returns true if the result token is the
  727. // entire buffer.
  728. bool isInvalid = !TL.LexFromRawLexer(Result);
  729. // If we got an EOF token, we didn't form even ONE token. For example, we
  730. // did "/ ## /" to get "//".
  731. isInvalid |= Result.is(tok::eof);
  732. // If pasting the two tokens didn't form a full new token, this is an
  733. // error. This occurs with "x ## +" and other stuff. Return with LHSTok
  734. // unmodified and with RHS as the next token to lex.
  735. if (isInvalid) {
  736. // Explicitly convert the token location to have proper expansion
  737. // information so that the user knows where it came from.
  738. SourceManager &SM = PP.getSourceManager();
  739. SourceLocation Loc =
  740. SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
  741. // Test for the Microsoft extension of /##/ turning into // here on the
  742. // error path.
  743. if (PP.getLangOpts().MicrosoftExt && LHSTok.is(tok::slash) &&
  744. RHS.is(tok::slash)) {
  745. HandleMicrosoftCommentPaste(LHSTok, Loc);
  746. return true;
  747. }
  748. // Do not emit the error when preprocessing assembler code.
  749. if (!PP.getLangOpts().AsmPreprocessor) {
  750. // If we're in microsoft extensions mode, downgrade this from a hard
  751. // error to an extension that defaults to an error. This allows
  752. // disabling it.
  753. PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
  754. : diag::err_pp_bad_paste)
  755. << Buffer;
  756. }
  757. // An error has occurred so exit loop.
  758. break;
  759. }
  760. // Turn ## into 'unknown' to avoid # ## # from looking like a paste
  761. // operator.
  762. if (Result.is(tok::hashhash))
  763. Result.setKind(tok::unknown);
  764. }
  765. // Transfer properties of the LHS over the Result.
  766. Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());
  767. Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());
  768. // Finally, replace LHS with the result, consume the RHS, and iterate.
  769. ++CurIdx;
  770. LHSTok = Result;
  771. } while (!IsAtEnd() && TokenStream[CurIdx].is(tok::hashhash));
  772. SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();
  773. // The token's current location indicate where the token was lexed from. We
  774. // need this information to compute the spelling of the token, but any
  775. // diagnostics for the expanded token should appear as if the token was
  776. // expanded from the full ## expression. Pull this information together into
  777. // a new SourceLocation that captures all of this.
  778. SourceManager &SM = PP.getSourceManager();
  779. if (StartLoc.isFileID())
  780. StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
  781. if (EndLoc.isFileID())
  782. EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
  783. FileID MacroFID = SM.getFileID(MacroExpansionStart);
  784. while (SM.getFileID(StartLoc) != MacroFID)
  785. StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin();
  786. while (SM.getFileID(EndLoc) != MacroFID)
  787. EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
  788. LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,
  789. LHSTok.getLength()));
  790. // Now that we got the result token, it will be subject to expansion. Since
  791. // token pasting re-lexes the result token in raw mode, identifier information
  792. // isn't looked up. As such, if the result is an identifier, look up id info.
  793. if (LHSTok.is(tok::raw_identifier)) {
  794. // Look up the identifier info for the token. We disabled identifier lookup
  795. // by saying we're skipping contents, so we need to do this manually.
  796. PP.LookUpIdentifierInfo(LHSTok);
  797. }
  798. return false;
  799. }
  800. /// isNextTokenLParen - If the next token lexed will pop this macro off the
  801. /// expansion stack, return 2. If the next unexpanded token is a '(', return
  802. /// 1, otherwise return 0.
  803. unsigned TokenLexer::isNextTokenLParen() const {
  804. // Out of tokens?
  805. if (isAtEnd())
  806. return 2;
  807. return Tokens[CurTokenIdx].is(tok::l_paren);
  808. }
  809. /// isParsingPreprocessorDirective - Return true if we are in the middle of a
  810. /// preprocessor directive.
  811. bool TokenLexer::isParsingPreprocessorDirective() const {
  812. return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
  813. }
  814. /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
  815. /// together to form a comment that comments out everything in the current
  816. /// macro, other active macros, and anything left on the current physical
  817. /// source line of the expanded buffer. Handle this by returning the
  818. /// first token on the next line.
  819. void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
  820. PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
  821. // We 'comment out' the rest of this macro by just ignoring the rest of the
  822. // tokens that have not been lexed yet, if any.
  823. // Since this must be a macro, mark the macro enabled now that it is no longer
  824. // being expanded.
  825. assert(Macro && "Token streams can't paste comments");
  826. Macro->EnableMacro();
  827. PP.HandleMicrosoftCommentPaste(Tok);
  828. }
  829. /// If \arg loc is a file ID and points inside the current macro
  830. /// definition, returns the appropriate source location pointing at the
  831. /// macro expansion source location entry, otherwise it returns an invalid
  832. /// SourceLocation.
  833. SourceLocation
  834. TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
  835. assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
  836. "Not appropriate for token streams");
  837. assert(loc.isValid() && loc.isFileID());
  838. SourceManager &SM = PP.getSourceManager();
  839. assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
  840. "Expected loc to come from the macro definition");
  841. SourceLocation::UIntTy relativeOffset = 0;
  842. SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
  843. return MacroExpansionStart.getLocWithOffset(relativeOffset);
  844. }
  845. /// Finds the tokens that are consecutive (from the same FileID)
  846. /// creates a single SLocEntry, and assigns SourceLocations to each token that
  847. /// point to that SLocEntry. e.g for
  848. /// assert(foo == bar);
  849. /// There will be a single SLocEntry for the "foo == bar" chunk and locations
  850. /// for the 'foo', '==', 'bar' tokens will point inside that chunk.
  851. ///
  852. /// \arg begin_tokens will be updated to a position past all the found
  853. /// consecutive tokens.
  854. static void updateConsecutiveMacroArgTokens(SourceManager &SM,
  855. SourceLocation ExpandLoc,
  856. Token *&begin_tokens,
  857. Token * end_tokens) {
  858. assert(begin_tokens + 1 < end_tokens);
  859. SourceLocation BeginLoc = begin_tokens->getLocation();
  860. llvm::MutableArrayRef<Token> All(begin_tokens, end_tokens);
  861. llvm::MutableArrayRef<Token> Partition;
  862. auto NearLast = [&, Last = BeginLoc](SourceLocation Loc) mutable {
  863. // The maximum distance between two consecutive tokens in a partition.
  864. // This is an important trick to avoid using too much SourceLocation address
  865. // space!
  866. static constexpr SourceLocation::IntTy MaxDistance = 50;
  867. auto Distance = Loc.getRawEncoding() - Last.getRawEncoding();
  868. Last = Loc;
  869. return Distance <= MaxDistance;
  870. };
  871. // Partition the tokens by their FileID.
  872. // This is a hot function, and calling getFileID can be expensive, the
  873. // implementation is optimized by reducing the number of getFileID.
  874. if (BeginLoc.isFileID()) {
  875. // Consecutive tokens not written in macros must be from the same file.
  876. // (Neither #include nor eof can occur inside a macro argument.)
  877. Partition = All.take_while([&](const Token &T) {
  878. return T.getLocation().isFileID() && NearLast(T.getLocation());
  879. });
  880. } else {
  881. // Call getFileID once to calculate the bounds, and use the cheaper
  882. // sourcelocation-against-bounds comparison.
  883. FileID BeginFID = SM.getFileID(BeginLoc);
  884. SourceLocation Limit =
  885. SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
  886. Partition = All.take_while([&](const Token &T) {
  887. // NOTE: the Limit is included! The lexer recovery only ever inserts a
  888. // single token past the end of the FileID, specifically the ) when a
  889. // macro-arg containing a comma should be guarded by parentheses.
  890. //
  891. // It is safe to include the Limit here because SourceManager allocates
  892. // FileSize + 1 for each SLocEntry.
  893. //
  894. // See https://github.com/llvm/llvm-project/issues/60722.
  895. return T.getLocation() >= BeginLoc && T.getLocation() <= Limit
  896. && NearLast(T.getLocation());
  897. });
  898. }
  899. assert(!Partition.empty());
  900. // For the consecutive tokens, find the length of the SLocEntry to contain
  901. // all of them.
  902. SourceLocation::UIntTy FullLength =
  903. Partition.back().getEndLoc().getRawEncoding() -
  904. Partition.front().getLocation().getRawEncoding();
  905. // Create a macro expansion SLocEntry that will "contain" all of the tokens.
  906. SourceLocation Expansion =
  907. SM.createMacroArgExpansionLoc(BeginLoc, ExpandLoc, FullLength);
  908. #ifdef EXPENSIVE_CHECKS
  909. assert(llvm::all_of(Partition.drop_front(),
  910. [&SM, ID = SM.getFileID(Partition.front().getLocation())](
  911. const Token &T) {
  912. return ID == SM.getFileID(T.getLocation());
  913. }) &&
  914. "Must have the same FIleID!");
  915. #endif
  916. // Change the location of the tokens from the spelling location to the new
  917. // expanded location.
  918. for (Token& T : Partition) {
  919. SourceLocation::IntTy RelativeOffset =
  920. T.getLocation().getRawEncoding() - BeginLoc.getRawEncoding();
  921. T.setLocation(Expansion.getLocWithOffset(RelativeOffset));
  922. }
  923. begin_tokens = &Partition.back() + 1;
  924. }
  925. /// Creates SLocEntries and updates the locations of macro argument
  926. /// tokens to their new expanded locations.
  927. ///
  928. /// \param ArgIdSpellLoc the location of the macro argument id inside the macro
  929. /// definition.
  930. void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
  931. Token *begin_tokens,
  932. Token *end_tokens) {
  933. SourceManager &SM = PP.getSourceManager();
  934. SourceLocation ExpandLoc =
  935. getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
  936. while (begin_tokens < end_tokens) {
  937. // If there's only one token just create a SLocEntry for it.
  938. if (end_tokens - begin_tokens == 1) {
  939. Token &Tok = *begin_tokens;
  940. Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
  941. ExpandLoc,
  942. Tok.getLength()));
  943. return;
  944. }
  945. updateConsecutiveMacroArgTokens(SM, ExpandLoc, begin_tokens, end_tokens);
  946. }
  947. }
  948. void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
  949. AtStartOfLine = Result.isAtStartOfLine();
  950. HasLeadingSpace = Result.hasLeadingSpace();
  951. }