TokenLexer.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. //===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the TokenLexer interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/TokenLexer.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Lex/LexDiagnostic.h"
  16. #include "clang/Lex/MacroArgs.h"
  17. #include "clang/Lex/MacroInfo.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PreprocessorOptions.h" // HLSL Change
  20. #include "llvm/ADT/SmallString.h"
  21. using namespace clang;
  22. /// Create a TokenLexer for the specified macro with the specified actual
  23. /// arguments. Note that this ctor takes ownership of the ActualArgs pointer.
  24. void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
  25. MacroArgs *Actuals) {
  26. // If the client is reusing a TokenLexer, make sure to free any memory
  27. // associated with it.
  28. destroy();
  29. Macro = MI;
  30. ActualArgs = Actuals;
  31. CurToken = 0;
  32. ExpandLocStart = Tok.getLocation();
  33. ExpandLocEnd = ELEnd;
  34. AtStartOfLine = Tok.isAtStartOfLine();
  35. HasLeadingSpace = Tok.hasLeadingSpace();
  36. NextTokGetsSpace = false;
  37. Tokens = &*Macro->tokens_begin();
  38. OwnsTokens = false;
  39. DisableMacroExpansion = false;
  40. NumTokens = Macro->tokens_end()-Macro->tokens_begin();
  41. MacroExpansionStart = SourceLocation();
  42. SourceManager &SM = PP.getSourceManager();
  43. MacroStartSLocOffset = SM.getNextLocalOffset();
  44. if (NumTokens > 0) {
  45. assert(Tokens[0].getLocation().isValid());
  46. assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
  47. "Macro defined in macro?");
  48. assert(ExpandLocStart.isValid());
  49. // Reserve a source location entry chunk for the length of the macro
  50. // definition. Tokens that get lexed directly from the definition will
  51. // have their locations pointing inside this chunk. This is to avoid
  52. // creating separate source location entries for each token.
  53. MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
  54. MacroDefLength = Macro->getDefinitionLength(SM);
  55. MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
  56. ExpandLocStart,
  57. ExpandLocEnd,
  58. MacroDefLength);
  59. }
  60. // If this is a function-like macro, expand the arguments and change
  61. // Tokens to point to the expanded tokens.
  62. if (Macro->isFunctionLike() && Macro->getNumArgs())
  63. ExpandFunctionArguments();
  64. // Mark the macro as currently disabled, so that it is not recursively
  65. // expanded. The macro must be disabled only after argument pre-expansion of
  66. // function-like macro arguments occurs.
  67. Macro->DisableMacro();
  68. }
  69. /// Create a TokenLexer for the specified token stream. This does not
  70. /// take ownership of the specified token vector.
  71. void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
  72. bool disableMacroExpansion, bool ownsTokens) {
  73. // If the client is reusing a TokenLexer, make sure to free any memory
  74. // associated with it.
  75. destroy();
  76. Macro = nullptr;
  77. ActualArgs = nullptr;
  78. Tokens = TokArray;
  79. OwnsTokens = ownsTokens;
  80. DisableMacroExpansion = disableMacroExpansion;
  81. NumTokens = NumToks;
  82. CurToken = 0;
  83. ExpandLocStart = ExpandLocEnd = SourceLocation();
  84. AtStartOfLine = false;
  85. HasLeadingSpace = false;
  86. NextTokGetsSpace = false;
  87. MacroExpansionStart = SourceLocation();
  88. // Set HasLeadingSpace/AtStartOfLine so that the first token will be
  89. // returned unmodified.
  90. if (NumToks != 0) {
  91. AtStartOfLine = TokArray[0].isAtStartOfLine();
  92. HasLeadingSpace = TokArray[0].hasLeadingSpace();
  93. }
  94. }
  95. void TokenLexer::destroy() {
  96. // If this was a function-like macro that actually uses its arguments, delete
  97. // the expanded tokens.
  98. if (OwnsTokens) {
  99. delete [] Tokens;
  100. Tokens = nullptr;
  101. OwnsTokens = false;
  102. }
  103. // TokenLexer owns its formal arguments.
  104. if (ActualArgs) ActualArgs->destroy(PP);
  105. }
  106. bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
  107. SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
  108. unsigned MacroArgNo, Preprocessor &PP) {
  109. // Is the macro argument __VA_ARGS__?
  110. if (!Macro->isVariadic() || MacroArgNo != Macro->getNumArgs()-1)
  111. return false;
  112. // In Microsoft-compatibility mode, a comma is removed in the expansion
  113. // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty. This extension is
  114. // not supported by gcc.
  115. if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat)
  116. return false;
  117. // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
  118. // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
  119. // named arguments, where it remains. In all other modes, including C99
  120. // with GNU extensions, it is removed regardless of named arguments.
  121. // Microsoft also appears to support this extension, unofficially.
  122. if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode
  123. && Macro->getNumArgs() < 2)
  124. return false;
  125. // Is a comma available to be removed?
  126. if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
  127. return false;
  128. // Issue an extension diagnostic for the paste operator.
  129. if (HasPasteOperator)
  130. PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
  131. // Remove the comma.
  132. ResultToks.pop_back();
  133. // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
  134. // then removal of the comma should produce a placemarker token (in C99
  135. // terms) which we model by popping off the previous ##, giving us a plain
  136. // "X" when __VA_ARGS__ is empty.
  137. if (!ResultToks.empty() && ResultToks.back().is(tok::hashhash))
  138. ResultToks.pop_back();
  139. // Never add a space, even if the comma, ##, or arg had a space.
  140. NextTokGetsSpace = false;
  141. return true;
  142. }
  143. /// Expand the arguments of a function-like macro so that we can quickly
  144. /// return preexpanded tokens from Tokens.
  145. void TokenLexer::ExpandFunctionArguments() {
  146. SmallVector<Token, 128> ResultToks;
  147. // Loop through 'Tokens', expanding them into ResultToks. Keep
  148. // track of whether we change anything. If not, no need to keep them. If so,
  149. // we install the newly expanded sequence as the new 'Tokens' list.
  150. bool MadeChange = false;
  151. for (unsigned i = 0, e = NumTokens; i != e; ++i) {
  152. // If we found the stringify operator, get the argument stringified. The
  153. // preprocessor already verified that the following token is a macro name
  154. // when the #define was parsed.
  155. const Token &CurTok = Tokens[i];
  156. if (i != 0 && !Tokens[i-1].is(tok::hashhash) && CurTok.hasLeadingSpace())
  157. NextTokGetsSpace = true;
  158. if (CurTok.isOneOf(tok::hash, tok::hashat)) {
  159. int ArgNo = Macro->getArgumentNum(Tokens[i+1].getIdentifierInfo());
  160. assert(ArgNo != -1 && "Token following # is not an argument?");
  161. SourceLocation ExpansionLocStart =
  162. getExpansionLocForMacroDefLoc(CurTok.getLocation());
  163. SourceLocation ExpansionLocEnd =
  164. getExpansionLocForMacroDefLoc(Tokens[i+1].getLocation());
  165. Token Res;
  166. if (CurTok.is(tok::hash)) // Stringify
  167. Res = ActualArgs->getStringifiedArgument(ArgNo, PP,
  168. ExpansionLocStart,
  169. ExpansionLocEnd);
  170. else {
  171. // 'charify': don't bother caching these.
  172. Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo),
  173. PP, true,
  174. ExpansionLocStart,
  175. ExpansionLocEnd);
  176. }
  177. Res.setFlag(Token::StringifiedInMacro);
  178. // The stringified/charified string leading space flag gets set to match
  179. // the #/#@ operator.
  180. if (NextTokGetsSpace)
  181. Res.setFlag(Token::LeadingSpace);
  182. ResultToks.push_back(Res);
  183. MadeChange = true;
  184. ++i; // Skip arg name.
  185. NextTokGetsSpace = false;
  186. continue;
  187. }
  188. // Find out if there is a paste (##) operator before or after the token.
  189. bool NonEmptyPasteBefore =
  190. !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
  191. bool PasteBefore = i != 0 && Tokens[i-1].is(tok::hashhash);
  192. bool PasteAfter = i+1 != e && Tokens[i+1].is(tok::hashhash);
  193. assert(!NonEmptyPasteBefore || PasteBefore);
  194. // Otherwise, if this is not an argument token, just add the token to the
  195. // output buffer.
  196. IdentifierInfo *II = CurTok.getIdentifierInfo();
  197. int ArgNo = II ? Macro->getArgumentNum(II) : -1;
  198. if (ArgNo == -1) {
  199. // This isn't an argument, just add it.
  200. ResultToks.push_back(CurTok);
  201. if (NextTokGetsSpace) {
  202. ResultToks.back().setFlag(Token::LeadingSpace);
  203. NextTokGetsSpace = false;
  204. } else if (PasteBefore && !NonEmptyPasteBefore)
  205. ResultToks.back().clearFlag(Token::LeadingSpace);
  206. continue;
  207. }
  208. // An argument is expanded somehow, the result is different than the
  209. // input.
  210. MadeChange = true;
  211. // Otherwise, this is a use of the argument.
  212. // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
  213. // are no trailing commas if __VA_ARGS__ is empty.
  214. if (!PasteBefore && ActualArgs->isVarargsElidedUse() &&
  215. MaybeRemoveCommaBeforeVaArgs(ResultToks,
  216. /*HasPasteOperator=*/false,
  217. Macro, ArgNo, PP))
  218. continue;
  219. // If it is not the LHS/RHS of a ## operator, we must pre-expand the
  220. // argument and substitute the expanded tokens into the result. This is
  221. // C99 6.10.3.1p1.
  222. if (PP.PPOpts.get()->ExpandTokPastingArg || !PasteBefore && !PasteAfter) { // HLSL Change
  223. const Token *ResultArgToks;
  224. // Only preexpand the argument if it could possibly need it. This
  225. // avoids some work in common cases.
  226. const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
  227. if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
  228. ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, Macro, PP)[0];
  229. else
  230. ResultArgToks = ArgTok; // Use non-preexpanded tokens.
  231. // If the arg token expanded into anything, append it.
  232. if (ResultArgToks->isNot(tok::eof)) {
  233. unsigned FirstResult = ResultToks.size();
  234. unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
  235. ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
  236. // In Microsoft-compatibility mode, we follow MSVC's preprocessing
  237. // behavior by not considering single commas from nested macro
  238. // expansions as argument separators. Set a flag on the token so we can
  239. // test for this later when the macro expansion is processed.
  240. if (PP.getLangOpts().MSVCCompat && NumToks == 1 &&
  241. ResultToks.back().is(tok::comma))
  242. ResultToks.back().setFlag(Token::IgnoredComma);
  243. // If the '##' came from expanding an argument, turn it into 'unknown'
  244. // to avoid pasting.
  245. for (unsigned i = FirstResult, e = ResultToks.size(); i != e; ++i) {
  246. Token &Tok = ResultToks[i];
  247. if (Tok.is(tok::hashhash))
  248. Tok.setKind(tok::unknown);
  249. }
  250. if(ExpandLocStart.isValid()) {
  251. updateLocForMacroArgTokens(CurTok.getLocation(),
  252. ResultToks.begin()+FirstResult,
  253. ResultToks.end());
  254. }
  255. // If any tokens were substituted from the argument, the whitespace
  256. // before the first token should match the whitespace of the arg
  257. // identifier.
  258. ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
  259. NextTokGetsSpace);
  260. NextTokGetsSpace = false;
  261. }
  262. continue;
  263. }
  264. // Okay, we have a token that is either the LHS or RHS of a paste (##)
  265. // argument. It gets substituted as its non-pre-expanded tokens.
  266. const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
  267. unsigned NumToks = MacroArgs::getArgLength(ArgToks);
  268. if (NumToks) { // Not an empty argument?
  269. // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
  270. // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
  271. // the expander trys to paste ',' with the first token of the __VA_ARGS__
  272. // expansion.
  273. if (NonEmptyPasteBefore && ResultToks.size() >= 2 &&
  274. ResultToks[ResultToks.size()-2].is(tok::comma) &&
  275. (unsigned)ArgNo == Macro->getNumArgs()-1 &&
  276. Macro->isVariadic()) {
  277. // Remove the paste operator, report use of the extension.
  278. PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
  279. }
  280. ResultToks.append(ArgToks, ArgToks+NumToks);
  281. // If the '##' came from expanding an argument, turn it into 'unknown'
  282. // to avoid pasting.
  283. for (unsigned i = ResultToks.size() - NumToks, e = ResultToks.size();
  284. i != e; ++i) {
  285. Token &Tok = ResultToks[i];
  286. if (Tok.is(tok::hashhash))
  287. Tok.setKind(tok::unknown);
  288. }
  289. if (ExpandLocStart.isValid()) {
  290. updateLocForMacroArgTokens(CurTok.getLocation(),
  291. ResultToks.end()-NumToks, ResultToks.end());
  292. }
  293. // If this token (the macro argument) was supposed to get leading
  294. // whitespace, transfer this information onto the first token of the
  295. // expansion.
  296. //
  297. // Do not do this if the paste operator occurs before the macro argument,
  298. // as in "A ## MACROARG". In valid code, the first token will get
  299. // smooshed onto the preceding one anyway (forming AMACROARG). In
  300. // assembler-with-cpp mode, invalid pastes are allowed through: in this
  301. // case, we do not want the extra whitespace to be added. For example,
  302. // we want ". ## foo" -> ".foo" not ". foo".
  303. if (NextTokGetsSpace)
  304. ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace);
  305. NextTokGetsSpace = false;
  306. continue;
  307. }
  308. // If an empty argument is on the LHS or RHS of a paste, the standard (C99
  309. // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We
  310. // implement this by eating ## operators when a LHS or RHS expands to
  311. // empty.
  312. if (PasteAfter) {
  313. // Discard the argument token and skip (don't copy to the expansion
  314. // buffer) the paste operator after it.
  315. ++i;
  316. continue;
  317. }
  318. // If this is on the RHS of a paste operator, we've already copied the
  319. // paste operator to the ResultToks list, unless the LHS was empty too.
  320. // Remove it.
  321. assert(PasteBefore);
  322. if (NonEmptyPasteBefore) {
  323. assert(ResultToks.back().is(tok::hashhash));
  324. ResultToks.pop_back();
  325. }
  326. // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
  327. // and if the macro had at least one real argument, and if the token before
  328. // the ## was a comma, remove the comma. This is a GCC extension which is
  329. // disabled when using -std=c99.
  330. if (ActualArgs->isVarargsElidedUse())
  331. MaybeRemoveCommaBeforeVaArgs(ResultToks,
  332. /*HasPasteOperator=*/true,
  333. Macro, ArgNo, PP);
  334. continue;
  335. }
  336. // If anything changed, install this as the new Tokens list.
  337. if (MadeChange) {
  338. assert(!OwnsTokens && "This would leak if we already own the token list");
  339. // This is deleted in the dtor.
  340. NumTokens = ResultToks.size();
  341. // The tokens will be added to Preprocessor's cache and will be removed
  342. // when this TokenLexer finishes lexing them.
  343. Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
  344. // The preprocessor cache of macro expanded tokens owns these tokens,not us.
  345. OwnsTokens = false;
  346. }
  347. }
  348. /// \brief Checks if two tokens form wide string literal.
  349. static bool isWideStringLiteralFromMacro(const Token &FirstTok,
  350. const Token &SecondTok) {
  351. return FirstTok.is(tok::identifier) &&
  352. FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
  353. SecondTok.stringifiedInMacro();
  354. }
  355. /// Lex - Lex and return a token from this macro stream.
  356. ///
  357. bool TokenLexer::Lex(Token &Tok) {
  358. // Lexing off the end of the macro, pop this macro off the expansion stack.
  359. if (isAtEnd()) {
  360. // If this is a macro (not a token stream), mark the macro enabled now
  361. // that it is no longer being expanded.
  362. if (Macro) Macro->EnableMacro();
  363. Tok.startToken();
  364. Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
  365. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace);
  366. if (CurToken == 0)
  367. Tok.setFlag(Token::LeadingEmptyMacro);
  368. return PP.HandleEndOfTokenLexer(Tok);
  369. }
  370. SourceManager &SM = PP.getSourceManager();
  371. // If this is the first token of the expanded result, we inherit spacing
  372. // properties later.
  373. bool isFirstToken = CurToken == 0;
  374. // Get the next token to return.
  375. Tok = Tokens[CurToken++];
  376. bool TokenIsFromPaste = false;
  377. // If this token is followed by a token paste (##) operator, paste the tokens!
  378. // Note that ## is a normal token when not expanding a macro.
  379. if (!isAtEnd() && Macro &&
  380. (Tokens[CurToken].is(tok::hashhash) ||
  381. // Special processing of L#x macros in -fms-compatibility mode.
  382. // Microsoft compiler is able to form a wide string literal from
  383. // 'L#macro_arg' construct in a function-like macro.
  384. (PP.getLangOpts().MSVCCompat &&
  385. isWideStringLiteralFromMacro(Tok, Tokens[CurToken])))) {
  386. // When handling the microsoft /##/ extension, the final token is
  387. // returned by PasteTokens, not the pasted token.
  388. if (PasteTokens(Tok))
  389. return true;
  390. TokenIsFromPaste = true;
  391. }
  392. // The token's current location indicate where the token was lexed from. We
  393. // need this information to compute the spelling of the token, but any
  394. // diagnostics for the expanded token should appear as if they came from
  395. // ExpansionLoc. Pull this information together into a new SourceLocation
  396. // that captures all of this.
  397. if (ExpandLocStart.isValid() && // Don't do this for token streams.
  398. // Check that the token's location was not already set properly.
  399. SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) {
  400. SourceLocation instLoc;
  401. if (Tok.is(tok::comment)) {
  402. instLoc = SM.createExpansionLoc(Tok.getLocation(),
  403. ExpandLocStart,
  404. ExpandLocEnd,
  405. Tok.getLength());
  406. } else {
  407. instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
  408. }
  409. Tok.setLocation(instLoc);
  410. }
  411. // If this is the first token, set the lexical properties of the token to
  412. // match the lexical properties of the macro identifier.
  413. if (isFirstToken) {
  414. Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
  415. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
  416. } else {
  417. // If this is not the first token, we may still need to pass through
  418. // leading whitespace if we've expanded a macro.
  419. if (AtStartOfLine) Tok.setFlag(Token::StartOfLine);
  420. if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace);
  421. }
  422. AtStartOfLine = false;
  423. HasLeadingSpace = false;
  424. // Handle recursive expansion!
  425. if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
  426. // Change the kind of this identifier to the appropriate token kind, e.g.
  427. // turning "for" into a keyword.
  428. IdentifierInfo *II = Tok.getIdentifierInfo();
  429. Tok.setKind(II->getTokenID());
  430. // If this identifier was poisoned and from a paste, emit an error. This
  431. // won't be handled by Preprocessor::HandleIdentifier because this is coming
  432. // from a macro expansion.
  433. if (II->isPoisoned() && TokenIsFromPaste) {
  434. PP.HandlePoisonedIdentifier(Tok);
  435. }
  436. if (!DisableMacroExpansion && II->isHandleIdentifierCase())
  437. return PP.HandleIdentifier(Tok);
  438. }
  439. // Otherwise, return a normal token.
  440. return true;
  441. }
  442. /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
  443. /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there
  444. /// are more ## after it, chomp them iteratively. Return the result as Tok.
  445. /// If this returns true, the caller should immediately return the token.
  446. bool TokenLexer::PasteTokens(Token &Tok) {
  447. // MSVC: If previous token was pasted, this must be a recovery from an invalid
  448. // paste operation. Ignore spaces before this token to mimic MSVC output.
  449. // Required for generating valid UUID strings in some MS headers.
  450. if (PP.getLangOpts().MicrosoftExt && (CurToken >= 2) &&
  451. Tokens[CurToken - 2].is(tok::hashhash))
  452. Tok.clearFlag(Token::LeadingSpace);
  453. SmallString<128> Buffer;
  454. const char *ResultTokStrPtr = nullptr;
  455. SourceLocation StartLoc = Tok.getLocation();
  456. SourceLocation PasteOpLoc;
  457. do {
  458. // Consume the ## operator if any.
  459. PasteOpLoc = Tokens[CurToken].getLocation();
  460. if (Tokens[CurToken].is(tok::hashhash))
  461. ++CurToken;
  462. assert(!isAtEnd() && "No token on the RHS of a paste operator!");
  463. // Get the RHS token.
  464. const Token &RHS = Tokens[CurToken];
  465. // Allocate space for the result token. This is guaranteed to be enough for
  466. // the two tokens.
  467. Buffer.resize(Tok.getLength() + RHS.getLength());
  468. // Get the spelling of the LHS token in Buffer.
  469. const char *BufPtr = &Buffer[0];
  470. bool Invalid = false;
  471. unsigned LHSLen = PP.getSpelling(Tok, BufPtr, &Invalid);
  472. if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer!
  473. memcpy(&Buffer[0], BufPtr, LHSLen);
  474. if (Invalid)
  475. return true;
  476. BufPtr = Buffer.data() + LHSLen;
  477. unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
  478. if (Invalid)
  479. return true;
  480. if (RHSLen && BufPtr != &Buffer[LHSLen])
  481. // Really, we want the chars in Buffer!
  482. memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
  483. // Trim excess space.
  484. Buffer.resize(LHSLen+RHSLen);
  485. // Plop the pasted result (including the trailing newline and null) into a
  486. // scratch buffer where we can lex it.
  487. Token ResultTokTmp;
  488. ResultTokTmp.startToken();
  489. // Claim that the tmp token is a string_literal so that we can get the
  490. // character pointer back from CreateString in getLiteralData().
  491. ResultTokTmp.setKind(tok::string_literal);
  492. PP.CreateString(Buffer, ResultTokTmp);
  493. SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
  494. ResultTokStrPtr = ResultTokTmp.getLiteralData();
  495. // Lex the resultant pasted token into Result.
  496. Token Result;
  497. if (Tok.isAnyIdentifier() && RHS.isAnyIdentifier()) {
  498. // Common paste case: identifier+identifier = identifier. Avoid creating
  499. // a lexer and other overhead.
  500. PP.IncrementPasteCounter(true);
  501. Result.startToken();
  502. Result.setKind(tok::raw_identifier);
  503. Result.setRawIdentifierData(ResultTokStrPtr);
  504. Result.setLocation(ResultTokLoc);
  505. Result.setLength(LHSLen+RHSLen);
  506. } else {
  507. PP.IncrementPasteCounter(false);
  508. assert(ResultTokLoc.isFileID() &&
  509. "Should be a raw location into scratch buffer");
  510. SourceManager &SourceMgr = PP.getSourceManager();
  511. FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
  512. bool Invalid = false;
  513. const char *ScratchBufStart
  514. = SourceMgr.getBufferData(LocFileID, &Invalid).data();
  515. if (Invalid)
  516. return false;
  517. // Make a lexer to lex this string from. Lex just this one token.
  518. // Make a lexer object so that we lex and expand the paste result.
  519. Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
  520. PP.getLangOpts(), ScratchBufStart,
  521. ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
  522. // Lex a token in raw mode. This way it won't look up identifiers
  523. // automatically, lexing off the end will return an eof token, and
  524. // warnings are disabled. This returns true if the result token is the
  525. // entire buffer.
  526. bool isInvalid = !TL.LexFromRawLexer(Result);
  527. // If we got an EOF token, we didn't form even ONE token. For example, we
  528. // did "/ ## /" to get "//".
  529. isInvalid |= Result.is(tok::eof);
  530. // If pasting the two tokens didn't form a full new token, this is an
  531. // error. This occurs with "x ## +" and other stuff. Return with Tok
  532. // unmodified and with RHS as the next token to lex.
  533. if (isInvalid) {
  534. // Test for the Microsoft extension of /##/ turning into // here on the
  535. // error path.
  536. if (PP.getLangOpts().MicrosoftExt && Tok.is(tok::slash) &&
  537. RHS.is(tok::slash)) {
  538. HandleMicrosoftCommentPaste(Tok);
  539. return true;
  540. }
  541. // Do not emit the error when preprocessing assembler code.
  542. if (!PP.getLangOpts().AsmPreprocessor) {
  543. // Explicitly convert the token location to have proper expansion
  544. // information so that the user knows where it came from.
  545. SourceManager &SM = PP.getSourceManager();
  546. SourceLocation Loc =
  547. SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
  548. // If we're in microsoft extensions mode, downgrade this from a hard
  549. // error to an extension that defaults to an error. This allows
  550. // disabling it.
  551. PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms
  552. : diag::err_pp_bad_paste)
  553. << Buffer;
  554. }
  555. // An error has occurred so exit loop.
  556. break;
  557. }
  558. // Turn ## into 'unknown' to avoid # ## # from looking like a paste
  559. // operator.
  560. if (Result.is(tok::hashhash))
  561. Result.setKind(tok::unknown);
  562. }
  563. // Transfer properties of the LHS over the Result.
  564. Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine());
  565. Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace());
  566. // Finally, replace LHS with the result, consume the RHS, and iterate.
  567. ++CurToken;
  568. Tok = Result;
  569. } while (!isAtEnd() && Tokens[CurToken].is(tok::hashhash));
  570. SourceLocation EndLoc = Tokens[CurToken - 1].getLocation();
  571. // The token's current location indicate where the token was lexed from. We
  572. // need this information to compute the spelling of the token, but any
  573. // diagnostics for the expanded token should appear as if the token was
  574. // expanded from the full ## expression. Pull this information together into
  575. // a new SourceLocation that captures all of this.
  576. SourceManager &SM = PP.getSourceManager();
  577. if (StartLoc.isFileID())
  578. StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
  579. if (EndLoc.isFileID())
  580. EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
  581. FileID MacroFID = SM.getFileID(MacroExpansionStart);
  582. while (SM.getFileID(StartLoc) != MacroFID)
  583. StartLoc = SM.getImmediateExpansionRange(StartLoc).first;
  584. while (SM.getFileID(EndLoc) != MacroFID)
  585. EndLoc = SM.getImmediateExpansionRange(EndLoc).second;
  586. Tok.setLocation(SM.createExpansionLoc(Tok.getLocation(), StartLoc, EndLoc,
  587. Tok.getLength()));
  588. // Now that we got the result token, it will be subject to expansion. Since
  589. // token pasting re-lexes the result token in raw mode, identifier information
  590. // isn't looked up. As such, if the result is an identifier, look up id info.
  591. if (Tok.is(tok::raw_identifier)) {
  592. // Look up the identifier info for the token. We disabled identifier lookup
  593. // by saying we're skipping contents, so we need to do this manually.
  594. PP.LookUpIdentifierInfo(Tok);
  595. }
  596. return false;
  597. }
  598. /// isNextTokenLParen - If the next token lexed will pop this macro off the
  599. /// expansion stack, return 2. If the next unexpanded token is a '(', return
  600. /// 1, otherwise return 0.
  601. unsigned TokenLexer::isNextTokenLParen() const {
  602. // Out of tokens?
  603. if (isAtEnd())
  604. return 2;
  605. return Tokens[CurToken].is(tok::l_paren);
  606. }
  607. /// isParsingPreprocessorDirective - Return true if we are in the middle of a
  608. /// preprocessor directive.
  609. bool TokenLexer::isParsingPreprocessorDirective() const {
  610. return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd();
  611. }
  612. /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
  613. /// together to form a comment that comments out everything in the current
  614. /// macro, other active macros, and anything left on the current physical
  615. /// source line of the expanded buffer. Handle this by returning the
  616. /// first token on the next line.
  617. void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok) {
  618. // We 'comment out' the rest of this macro by just ignoring the rest of the
  619. // tokens that have not been lexed yet, if any.
  620. // Since this must be a macro, mark the macro enabled now that it is no longer
  621. // being expanded.
  622. assert(Macro && "Token streams can't paste comments");
  623. Macro->EnableMacro();
  624. PP.HandleMicrosoftCommentPaste(Tok);
  625. }
  626. /// \brief If \arg loc is a file ID and points inside the current macro
  627. /// definition, returns the appropriate source location pointing at the
  628. /// macro expansion source location entry, otherwise it returns an invalid
  629. /// SourceLocation.
  630. SourceLocation
  631. TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
  632. assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
  633. "Not appropriate for token streams");
  634. assert(loc.isValid() && loc.isFileID());
  635. SourceManager &SM = PP.getSourceManager();
  636. assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
  637. "Expected loc to come from the macro definition");
  638. unsigned relativeOffset = 0;
  639. SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
  640. return MacroExpansionStart.getLocWithOffset(relativeOffset);
  641. }
  642. /// \brief Finds the tokens that are consecutive (from the same FileID)
  643. /// creates a single SLocEntry, and assigns SourceLocations to each token that
  644. /// point to that SLocEntry. e.g for
  645. /// assert(foo == bar);
  646. /// There will be a single SLocEntry for the "foo == bar" chunk and locations
  647. /// for the 'foo', '==', 'bar' tokens will point inside that chunk.
  648. ///
  649. /// \arg begin_tokens will be updated to a position past all the found
  650. /// consecutive tokens.
  651. static void updateConsecutiveMacroArgTokens(SourceManager &SM,
  652. SourceLocation InstLoc,
  653. Token *&begin_tokens,
  654. Token * end_tokens) {
  655. assert(begin_tokens < end_tokens);
  656. SourceLocation FirstLoc = begin_tokens->getLocation();
  657. SourceLocation CurLoc = FirstLoc;
  658. // Compare the source location offset of tokens and group together tokens that
  659. // are close, even if their locations point to different FileIDs. e.g.
  660. //
  661. // |bar | foo | cake | (3 tokens from 3 consecutive FileIDs)
  662. // ^ ^
  663. // |bar foo cake| (one SLocEntry chunk for all tokens)
  664. //
  665. // we can perform this "merge" since the token's spelling location depends
  666. // on the relative offset.
  667. Token *NextTok = begin_tokens + 1;
  668. for (; NextTok < end_tokens; ++NextTok) {
  669. SourceLocation NextLoc = NextTok->getLocation();
  670. if (CurLoc.isFileID() != NextLoc.isFileID())
  671. break; // Token from different kind of FileID.
  672. int RelOffs;
  673. if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
  674. break; // Token from different local/loaded location.
  675. // Check that token is not before the previous token or more than 50
  676. // "characters" away.
  677. if (RelOffs < 0 || RelOffs > 50)
  678. break;
  679. CurLoc = NextLoc;
  680. }
  681. // For the consecutive tokens, find the length of the SLocEntry to contain
  682. // all of them.
  683. Token &LastConsecutiveTok = *(NextTok-1);
  684. int LastRelOffs = 0;
  685. SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
  686. &LastRelOffs);
  687. unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength();
  688. // Create a macro expansion SLocEntry that will "contain" all of the tokens.
  689. SourceLocation Expansion =
  690. SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
  691. // Change the location of the tokens from the spelling location to the new
  692. // expanded location.
  693. for (; begin_tokens < NextTok; ++begin_tokens) {
  694. Token &Tok = *begin_tokens;
  695. int RelOffs = 0;
  696. SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
  697. Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
  698. }
  699. }
  700. /// \brief Creates SLocEntries and updates the locations of macro argument
  701. /// tokens to their new expanded locations.
  702. ///
  703. /// \param ArgIdDefLoc the location of the macro argument id inside the macro
  704. /// definition.
  705. /// \param Tokens the macro argument tokens to update.
  706. void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
  707. Token *begin_tokens,
  708. Token *end_tokens) {
  709. SourceManager &SM = PP.getSourceManager();
  710. SourceLocation InstLoc =
  711. getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
  712. while (begin_tokens < end_tokens) {
  713. // If there's only one token just create a SLocEntry for it.
  714. if (end_tokens - begin_tokens == 1) {
  715. Token &Tok = *begin_tokens;
  716. Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
  717. InstLoc,
  718. Tok.getLength()));
  719. return;
  720. }
  721. updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
  722. }
  723. }
  724. void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
  725. AtStartOfLine = Result.isAtStartOfLine();
  726. HasLeadingSpace = Result.hasLeadingSpace();
  727. }