TokenConcatenation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. //===--- TokenConcatenation.cpp - Token Concatenation Avoidance -----------===//
  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 TokenConcatenation class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Lex/TokenConcatenation.h"
  13. #include "clang/Basic/CharInfo.h"
  14. #include "clang/Lex/Preprocessor.h"
  15. #include "llvm/Support/ErrorHandling.h"
  16. using namespace clang;
  17. /// IsStringPrefix - Return true if Str is a string prefix.
  18. /// 'L', 'u', 'U', or 'u8'. Including raw versions.
  19. static bool IsStringPrefix(StringRef Str, bool CPlusPlus11) {
  20. if (Str[0] == 'L' ||
  21. (CPlusPlus11 && (Str[0] == 'u' || Str[0] == 'U' || Str[0] == 'R'))) {
  22. if (Str.size() == 1)
  23. return true; // "L", "u", "U", and "R"
  24. // Check for raw flavors. Need to make sure the first character wasn't
  25. // already R. Need CPlusPlus11 check for "LR".
  26. if (Str[1] == 'R' && Str[0] != 'R' && Str.size() == 2 && CPlusPlus11)
  27. return true; // "LR", "uR", "UR"
  28. // Check for "u8" and "u8R"
  29. if (Str[0] == 'u' && Str[1] == '8') {
  30. if (Str.size() == 2) return true; // "u8"
  31. if (Str.size() == 3 && Str[2] == 'R') return true; // "u8R"
  32. }
  33. }
  34. return false;
  35. }
  36. /// IsIdentifierStringPrefix - Return true if the spelling of the token
  37. /// is literally 'L', 'u', 'U', or 'u8'. Including raw versions.
  38. bool TokenConcatenation::IsIdentifierStringPrefix(const Token &Tok) const {
  39. const LangOptions &LangOpts = PP.getLangOpts();
  40. if (!Tok.needsCleaning()) {
  41. if (Tok.getLength() < 1 || Tok.getLength() > 3)
  42. return false;
  43. SourceManager &SM = PP.getSourceManager();
  44. const char *Ptr = SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));
  45. return IsStringPrefix(StringRef(Ptr, Tok.getLength()),
  46. LangOpts.CPlusPlus11);
  47. }
  48. if (Tok.getLength() < 256) {
  49. char Buffer[256];
  50. const char *TokPtr = Buffer;
  51. unsigned length = PP.getSpelling(Tok, TokPtr);
  52. return IsStringPrefix(StringRef(TokPtr, length), LangOpts.CPlusPlus11);
  53. }
  54. return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11);
  55. }
  56. TokenConcatenation::TokenConcatenation(const Preprocessor &pp) : PP(pp) {
  57. memset(TokenInfo, 0, sizeof(TokenInfo));
  58. // These tokens have custom code in AvoidConcat.
  59. TokenInfo[tok::identifier ] |= aci_custom;
  60. TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
  61. TokenInfo[tok::period ] |= aci_custom_firstchar;
  62. TokenInfo[tok::amp ] |= aci_custom_firstchar;
  63. TokenInfo[tok::plus ] |= aci_custom_firstchar;
  64. TokenInfo[tok::minus ] |= aci_custom_firstchar;
  65. TokenInfo[tok::slash ] |= aci_custom_firstchar;
  66. TokenInfo[tok::less ] |= aci_custom_firstchar;
  67. TokenInfo[tok::greater ] |= aci_custom_firstchar;
  68. TokenInfo[tok::pipe ] |= aci_custom_firstchar;
  69. TokenInfo[tok::percent ] |= aci_custom_firstchar;
  70. TokenInfo[tok::colon ] |= aci_custom_firstchar;
  71. TokenInfo[tok::hash ] |= aci_custom_firstchar;
  72. TokenInfo[tok::arrow ] |= aci_custom_firstchar;
  73. // These tokens have custom code in C++11 mode.
  74. if (PP.getLangOpts().CPlusPlus11) {
  75. TokenInfo[tok::string_literal ] |= aci_custom;
  76. TokenInfo[tok::wide_string_literal ] |= aci_custom;
  77. TokenInfo[tok::utf8_string_literal ] |= aci_custom;
  78. TokenInfo[tok::utf16_string_literal] |= aci_custom;
  79. TokenInfo[tok::utf32_string_literal] |= aci_custom;
  80. TokenInfo[tok::char_constant ] |= aci_custom;
  81. TokenInfo[tok::wide_char_constant ] |= aci_custom;
  82. TokenInfo[tok::utf16_char_constant ] |= aci_custom;
  83. TokenInfo[tok::utf32_char_constant ] |= aci_custom;
  84. }
  85. // These tokens have custom code in C++17 mode.
  86. if (PP.getLangOpts().CPlusPlus17)
  87. TokenInfo[tok::utf8_char_constant] |= aci_custom;
  88. // These tokens have custom code in C++2a mode.
  89. if (PP.getLangOpts().CPlusPlus20)
  90. TokenInfo[tok::lessequal ] |= aci_custom_firstchar;
  91. // These tokens change behavior if followed by an '='.
  92. TokenInfo[tok::amp ] |= aci_avoid_equal; // &=
  93. TokenInfo[tok::plus ] |= aci_avoid_equal; // +=
  94. TokenInfo[tok::minus ] |= aci_avoid_equal; // -=
  95. TokenInfo[tok::slash ] |= aci_avoid_equal; // /=
  96. TokenInfo[tok::less ] |= aci_avoid_equal; // <=
  97. TokenInfo[tok::greater ] |= aci_avoid_equal; // >=
  98. TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=
  99. TokenInfo[tok::percent ] |= aci_avoid_equal; // %=
  100. TokenInfo[tok::star ] |= aci_avoid_equal; // *=
  101. TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=
  102. TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=
  103. TokenInfo[tok::greatergreater] |= aci_avoid_equal; // >>=
  104. TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=
  105. TokenInfo[tok::equal ] |= aci_avoid_equal; // ==
  106. }
  107. /// GetFirstChar - Get the first character of the token \arg Tok,
  108. /// avoiding calls to getSpelling where possible.
  109. static char GetFirstChar(const Preprocessor &PP, const Token &Tok) {
  110. if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  111. // Avoid spelling identifiers, the most common form of token.
  112. return II->getNameStart()[0];
  113. } else if (!Tok.needsCleaning()) {
  114. if (Tok.isLiteral() && Tok.getLiteralData()) {
  115. return *Tok.getLiteralData();
  116. } else {
  117. SourceManager &SM = PP.getSourceManager();
  118. return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));
  119. }
  120. } else if (Tok.getLength() < 256) {
  121. char Buffer[256];
  122. const char *TokPtr = Buffer;
  123. PP.getSpelling(Tok, TokPtr);
  124. return TokPtr[0];
  125. } else {
  126. return PP.getSpelling(Tok)[0];
  127. }
  128. }
  129. /// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
  130. /// the two individual tokens to be lexed as a single token, return true
  131. /// (which causes a space to be printed between them). This allows the output
  132. /// of -E mode to be lexed to the same token stream as lexing the input
  133. /// directly would.
  134. ///
  135. /// This code must conservatively return true if it doesn't want to be 100%
  136. /// accurate. This will cause the output to include extra space characters,
  137. /// but the resulting output won't have incorrect concatenations going on.
  138. /// Examples include "..", which we print with a space between, because we
  139. /// don't want to track enough to tell "x.." from "...".
  140. bool TokenConcatenation::AvoidConcat(const Token &PrevPrevTok,
  141. const Token &PrevTok,
  142. const Token &Tok) const {
  143. // Conservatively assume that every annotation token that has a printable
  144. // form requires whitespace.
  145. if (PrevTok.isAnnotation())
  146. return true;
  147. // First, check to see if the tokens were directly adjacent in the original
  148. // source. If they were, it must be okay to stick them together: if there
  149. // were an issue, the tokens would have been lexed differently.
  150. SourceManager &SM = PP.getSourceManager();
  151. SourceLocation PrevSpellLoc = SM.getSpellingLoc(PrevTok.getLocation());
  152. SourceLocation SpellLoc = SM.getSpellingLoc(Tok.getLocation());
  153. if (PrevSpellLoc.getLocWithOffset(PrevTok.getLength()) == SpellLoc)
  154. return false;
  155. tok::TokenKind PrevKind = PrevTok.getKind();
  156. if (!PrevTok.isAnnotation() && PrevTok.getIdentifierInfo())
  157. PrevKind = tok::identifier; // Language keyword or named operator.
  158. // Look up information on when we should avoid concatenation with prevtok.
  159. unsigned ConcatInfo = TokenInfo[PrevKind];
  160. // If prevtok never causes a problem for anything after it, return quickly.
  161. if (ConcatInfo == 0) return false;
  162. if (ConcatInfo & aci_avoid_equal) {
  163. // If the next token is '=' or '==', avoid concatenation.
  164. if (Tok.isOneOf(tok::equal, tok::equalequal))
  165. return true;
  166. ConcatInfo &= ~aci_avoid_equal;
  167. }
  168. if (Tok.isAnnotation()) {
  169. // Modules annotation can show up when generated automatically for includes.
  170. assert(Tok.isOneOf(tok::annot_module_include, tok::annot_module_begin,
  171. tok::annot_module_end) &&
  172. "unexpected annotation in AvoidConcat");
  173. ConcatInfo = 0;
  174. }
  175. if (ConcatInfo == 0)
  176. return false;
  177. // Basic algorithm: we look at the first character of the second token, and
  178. // determine whether it, if appended to the first token, would form (or
  179. // would contribute) to a larger token if concatenated.
  180. char FirstChar = 0;
  181. if (ConcatInfo & aci_custom) {
  182. // If the token does not need to know the first character, don't get it.
  183. } else {
  184. FirstChar = GetFirstChar(PP, Tok);
  185. }
  186. switch (PrevKind) {
  187. default:
  188. llvm_unreachable("InitAvoidConcatTokenInfo built wrong");
  189. case tok::raw_identifier:
  190. llvm_unreachable("tok::raw_identifier in non-raw lexing mode!");
  191. case tok::string_literal:
  192. case tok::wide_string_literal:
  193. case tok::utf8_string_literal:
  194. case tok::utf16_string_literal:
  195. case tok::utf32_string_literal:
  196. case tok::char_constant:
  197. case tok::wide_char_constant:
  198. case tok::utf8_char_constant:
  199. case tok::utf16_char_constant:
  200. case tok::utf32_char_constant:
  201. if (!PP.getLangOpts().CPlusPlus11)
  202. return false;
  203. // In C++11, a string or character literal followed by an identifier is a
  204. // single token.
  205. if (Tok.getIdentifierInfo())
  206. return true;
  207. // A ud-suffix is an identifier. If the previous token ends with one, treat
  208. // it as an identifier.
  209. if (!PrevTok.hasUDSuffix())
  210. return false;
  211. LLVM_FALLTHROUGH;
  212. case tok::identifier: // id+id or id+number or id+L"foo".
  213. // id+'.'... will not append.
  214. if (Tok.is(tok::numeric_constant))
  215. return GetFirstChar(PP, Tok) != '.';
  216. if (Tok.getIdentifierInfo() ||
  217. Tok.isOneOf(tok::wide_string_literal, tok::utf8_string_literal,
  218. tok::utf16_string_literal, tok::utf32_string_literal,
  219. tok::wide_char_constant, tok::utf8_char_constant,
  220. tok::utf16_char_constant, tok::utf32_char_constant))
  221. return true;
  222. // If this isn't identifier + string, we're done.
  223. if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))
  224. return false;
  225. // Otherwise, this is a narrow character or string. If the *identifier*
  226. // is a literal 'L', 'u8', 'u' or 'U', avoid pasting L "foo" -> L"foo".
  227. return IsIdentifierStringPrefix(PrevTok);
  228. case tok::numeric_constant:
  229. return isPreprocessingNumberBody(FirstChar) ||
  230. FirstChar == '+' || FirstChar == '-';
  231. case tok::period: // ..., .*, .1234
  232. return (FirstChar == '.' && PrevPrevTok.is(tok::period)) ||
  233. isDigit(FirstChar) ||
  234. (PP.getLangOpts().CPlusPlus && FirstChar == '*');
  235. case tok::amp: // &&
  236. return FirstChar == '&';
  237. case tok::plus: // ++
  238. return FirstChar == '+';
  239. case tok::minus: // --, ->, ->*
  240. return FirstChar == '-' || FirstChar == '>';
  241. case tok::slash: //, /*, //
  242. return FirstChar == '*' || FirstChar == '/';
  243. case tok::less: // <<, <<=, <:, <%
  244. return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
  245. case tok::greater: // >>, >>=
  246. return FirstChar == '>';
  247. case tok::pipe: // ||
  248. return FirstChar == '|';
  249. case tok::percent: // %>, %:
  250. return FirstChar == '>' || FirstChar == ':';
  251. case tok::colon: // ::, :>
  252. return FirstChar == '>' ||
  253. (PP.getLangOpts().CPlusPlus && FirstChar == ':');
  254. case tok::hash: // ##, #@, %:%:
  255. return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
  256. case tok::arrow: // ->*
  257. return PP.getLangOpts().CPlusPlus && FirstChar == '*';
  258. case tok::lessequal: // <=> (C++2a)
  259. return PP.getLangOpts().CPlusPlus20 && FirstChar == '>';
  260. }
  261. }