TokenLexer.cpp 43 KB

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