TokenLexer.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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::make_range(ResultToks.begin() + FirstResult,
  413. ResultToks.end())) {
  414. if (Tok.is(tok::hashhash))
  415. Tok.setKind(tok::unknown);
  416. }
  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::makeArrayRef(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. unsigned 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 InstLoc,
  856. Token *&begin_tokens,
  857. Token * end_tokens) {
  858. assert(begin_tokens < end_tokens);
  859. SourceLocation FirstLoc = begin_tokens->getLocation();
  860. SourceLocation CurLoc = FirstLoc;
  861. // Compare the source location offset of tokens and group together tokens that
  862. // are close, even if their locations point to different FileIDs. e.g.
  863. //
  864. // |bar | foo | cake | (3 tokens from 3 consecutive FileIDs)
  865. // ^ ^
  866. // |bar foo cake| (one SLocEntry chunk for all tokens)
  867. //
  868. // we can perform this "merge" since the token's spelling location depends
  869. // on the relative offset.
  870. Token *NextTok = begin_tokens + 1;
  871. for (; NextTok < end_tokens; ++NextTok) {
  872. SourceLocation NextLoc = NextTok->getLocation();
  873. if (CurLoc.isFileID() != NextLoc.isFileID())
  874. break; // Token from different kind of FileID.
  875. int RelOffs;
  876. if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
  877. break; // Token from different local/loaded location.
  878. // Check that token is not before the previous token or more than 50
  879. // "characters" away.
  880. if (RelOffs < 0 || RelOffs > 50)
  881. break;
  882. if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
  883. break; // Token from a different macro.
  884. CurLoc = NextLoc;
  885. }
  886. // For the consecutive tokens, find the length of the SLocEntry to contain
  887. // all of them.
  888. Token &LastConsecutiveTok = *(NextTok-1);
  889. int LastRelOffs = 0;
  890. SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
  891. &LastRelOffs);
  892. unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength();
  893. // Create a macro expansion SLocEntry that will "contain" all of the tokens.
  894. SourceLocation Expansion =
  895. SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
  896. // Change the location of the tokens from the spelling location to the new
  897. // expanded location.
  898. for (; begin_tokens < NextTok; ++begin_tokens) {
  899. Token &Tok = *begin_tokens;
  900. int RelOffs = 0;
  901. SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
  902. Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
  903. }
  904. }
  905. /// Creates SLocEntries and updates the locations of macro argument
  906. /// tokens to their new expanded locations.
  907. ///
  908. /// \param ArgIdSpellLoc the location of the macro argument id inside the macro
  909. /// definition.
  910. void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
  911. Token *begin_tokens,
  912. Token *end_tokens) {
  913. SourceManager &SM = PP.getSourceManager();
  914. SourceLocation InstLoc =
  915. getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
  916. while (begin_tokens < end_tokens) {
  917. // If there's only one token just create a SLocEntry for it.
  918. if (end_tokens - begin_tokens == 1) {
  919. Token &Tok = *begin_tokens;
  920. Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
  921. InstLoc,
  922. Tok.getLength()));
  923. return;
  924. }
  925. updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
  926. }
  927. }
  928. void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
  929. AtStartOfLine = Result.isAtStartOfLine();
  930. HasLeadingSpace = Result.hasLeadingSpace();
  931. }