1193326Sed//===--- TokenConcatenation.cpp - Token Concatenation Avoidance -----------===//
2193326Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193326Sed//
7193326Sed//===----------------------------------------------------------------------===//
8193326Sed//
9193326Sed// This file implements the TokenConcatenation class.
10193326Sed//
11193326Sed//===----------------------------------------------------------------------===//
12193326Sed
13193326Sed#include "clang/Lex/TokenConcatenation.h"
14249423Sdim#include "clang/Basic/CharInfo.h"
15193326Sed#include "clang/Lex/Preprocessor.h"
16218893Sdim#include "llvm/Support/ErrorHandling.h"
17198092Srdivackyusing namespace clang;
18193326Sed
19193326Sed
20226633Sdim/// IsStringPrefix - Return true if Str is a string prefix.
21226633Sdim/// 'L', 'u', 'U', or 'u8'. Including raw versions.
22249423Sdimstatic bool IsStringPrefix(StringRef Str, bool CPlusPlus11) {
23198092Srdivacky
24226633Sdim  if (Str[0] == 'L' ||
25249423Sdim      (CPlusPlus11 && (Str[0] == 'u' || Str[0] == 'U' || Str[0] == 'R'))) {
26226633Sdim
27226633Sdim    if (Str.size() == 1)
28226633Sdim      return true; // "L", "u", "U", and "R"
29226633Sdim
30226633Sdim    // Check for raw flavors. Need to make sure the first character wasn't
31249423Sdim    // already R. Need CPlusPlus11 check for "LR".
32249423Sdim    if (Str[1] == 'R' && Str[0] != 'R' && Str.size() == 2 && CPlusPlus11)
33226633Sdim      return true; // "LR", "uR", "UR"
34226633Sdim
35226633Sdim    // Check for "u8" and "u8R"
36226633Sdim    if (Str[0] == 'u' && Str[1] == '8') {
37226633Sdim      if (Str.size() == 2) return true; // "u8"
38226633Sdim      if (Str.size() == 3 && Str[2] == 'R') return true; // "u8R"
39226633Sdim    }
40193326Sed  }
41198092Srdivacky
42226633Sdim  return false;
43193326Sed}
44193326Sed
45226633Sdim/// IsIdentifierStringPrefix - Return true if the spelling of the token
46226633Sdim/// is literally 'L', 'u', 'U', or 'u8'. Including raw versions.
47226633Sdimbool TokenConcatenation::IsIdentifierStringPrefix(const Token &Tok) const {
48234353Sdim  const LangOptions &LangOpts = PP.getLangOpts();
49226633Sdim
50193326Sed  if (!Tok.needsCleaning()) {
51226633Sdim    if (Tok.getLength() < 1 || Tok.getLength() > 3)
52193326Sed      return false;
53193326Sed    SourceManager &SM = PP.getSourceManager();
54226633Sdim    const char *Ptr = SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));
55226633Sdim    return IsStringPrefix(StringRef(Ptr, Tok.getLength()),
56249423Sdim                          LangOpts.CPlusPlus11);
57193326Sed  }
58198092Srdivacky
59193326Sed  if (Tok.getLength() < 256) {
60193326Sed    char Buffer[256];
61193326Sed    const char *TokPtr = Buffer;
62226633Sdim    unsigned length = PP.getSpelling(Tok, TokPtr);
63249423Sdim    return IsStringPrefix(StringRef(TokPtr, length), LangOpts.CPlusPlus11);
64193326Sed  }
65198092Srdivacky
66249423Sdim  return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11);
67193326Sed}
68193326Sed
69344779SdimTokenConcatenation::TokenConcatenation(const Preprocessor &pp) : PP(pp) {
70193326Sed  memset(TokenInfo, 0, sizeof(TokenInfo));
71198092Srdivacky
72193326Sed  // These tokens have custom code in AvoidConcat.
73193326Sed  TokenInfo[tok::identifier      ] |= aci_custom;
74193326Sed  TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
75193326Sed  TokenInfo[tok::period          ] |= aci_custom_firstchar;
76193326Sed  TokenInfo[tok::amp             ] |= aci_custom_firstchar;
77193326Sed  TokenInfo[tok::plus            ] |= aci_custom_firstchar;
78193326Sed  TokenInfo[tok::minus           ] |= aci_custom_firstchar;
79193326Sed  TokenInfo[tok::slash           ] |= aci_custom_firstchar;
80193326Sed  TokenInfo[tok::less            ] |= aci_custom_firstchar;
81193326Sed  TokenInfo[tok::greater         ] |= aci_custom_firstchar;
82193326Sed  TokenInfo[tok::pipe            ] |= aci_custom_firstchar;
83193326Sed  TokenInfo[tok::percent         ] |= aci_custom_firstchar;
84193326Sed  TokenInfo[tok::colon           ] |= aci_custom_firstchar;
85193326Sed  TokenInfo[tok::hash            ] |= aci_custom_firstchar;
86193326Sed  TokenInfo[tok::arrow           ] |= aci_custom_firstchar;
87198092Srdivacky
88234353Sdim  // These tokens have custom code in C++11 mode.
89249423Sdim  if (PP.getLangOpts().CPlusPlus11) {
90234353Sdim    TokenInfo[tok::string_literal      ] |= aci_custom;
91234353Sdim    TokenInfo[tok::wide_string_literal ] |= aci_custom;
92234353Sdim    TokenInfo[tok::utf8_string_literal ] |= aci_custom;
93234353Sdim    TokenInfo[tok::utf16_string_literal] |= aci_custom;
94234353Sdim    TokenInfo[tok::utf32_string_literal] |= aci_custom;
95234353Sdim    TokenInfo[tok::char_constant       ] |= aci_custom;
96234353Sdim    TokenInfo[tok::wide_char_constant  ] |= aci_custom;
97234353Sdim    TokenInfo[tok::utf16_char_constant ] |= aci_custom;
98234353Sdim    TokenInfo[tok::utf32_char_constant ] |= aci_custom;
99234353Sdim  }
100234353Sdim
101327952Sdim  // These tokens have custom code in C++17 mode.
102327952Sdim  if (PP.getLangOpts().CPlusPlus17)
103280031Sdim    TokenInfo[tok::utf8_char_constant] |= aci_custom;
104280031Sdim
105327952Sdim  // These tokens have custom code in C++2a mode.
106327952Sdim  if (PP.getLangOpts().CPlusPlus2a)
107327952Sdim    TokenInfo[tok::lessequal ] |= aci_custom_firstchar;
108327952Sdim
109193326Sed  // These tokens change behavior if followed by an '='.
110193326Sed  TokenInfo[tok::amp         ] |= aci_avoid_equal;           // &=
111193326Sed  TokenInfo[tok::plus        ] |= aci_avoid_equal;           // +=
112193326Sed  TokenInfo[tok::minus       ] |= aci_avoid_equal;           // -=
113193326Sed  TokenInfo[tok::slash       ] |= aci_avoid_equal;           // /=
114193326Sed  TokenInfo[tok::less        ] |= aci_avoid_equal;           // <=
115193326Sed  TokenInfo[tok::greater     ] |= aci_avoid_equal;           // >=
116193326Sed  TokenInfo[tok::pipe        ] |= aci_avoid_equal;           // |=
117193326Sed  TokenInfo[tok::percent     ] |= aci_avoid_equal;           // %=
118193326Sed  TokenInfo[tok::star        ] |= aci_avoid_equal;           // *=
119193326Sed  TokenInfo[tok::exclaim     ] |= aci_avoid_equal;           // !=
120193326Sed  TokenInfo[tok::lessless    ] |= aci_avoid_equal;           // <<=
121206084Srdivacky  TokenInfo[tok::greatergreater] |= aci_avoid_equal;         // >>=
122193326Sed  TokenInfo[tok::caret       ] |= aci_avoid_equal;           // ^=
123193326Sed  TokenInfo[tok::equal       ] |= aci_avoid_equal;           // ==
124193326Sed}
125193326Sed
126193326Sed/// GetFirstChar - Get the first character of the token \arg Tok,
127193326Sed/// avoiding calls to getSpelling where possible.
128344779Sdimstatic char GetFirstChar(const Preprocessor &PP, const Token &Tok) {
129193326Sed  if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
130193326Sed    // Avoid spelling identifiers, the most common form of token.
131198398Srdivacky    return II->getNameStart()[0];
132193326Sed  } else if (!Tok.needsCleaning()) {
133193326Sed    if (Tok.isLiteral() && Tok.getLiteralData()) {
134193326Sed      return *Tok.getLiteralData();
135193326Sed    } else {
136193326Sed      SourceManager &SM = PP.getSourceManager();
137193326Sed      return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));
138193326Sed    }
139193326Sed  } else if (Tok.getLength() < 256) {
140193326Sed    char Buffer[256];
141193326Sed    const char *TokPtr = Buffer;
142193326Sed    PP.getSpelling(Tok, TokPtr);
143193326Sed    return TokPtr[0];
144193326Sed  } else {
145193326Sed    return PP.getSpelling(Tok)[0];
146193326Sed  }
147193326Sed}
148193326Sed
149193326Sed/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
150193326Sed/// the two individual tokens to be lexed as a single token, return true
151193326Sed/// (which causes a space to be printed between them).  This allows the output
152193326Sed/// of -E mode to be lexed to the same token stream as lexing the input
153193326Sed/// directly would.
154193326Sed///
155193326Sed/// This code must conservatively return true if it doesn't want to be 100%
156193326Sed/// accurate.  This will cause the output to include extra space characters,
157193326Sed/// but the resulting output won't have incorrect concatenations going on.
158193326Sed/// Examples include "..", which we print with a space between, because we
159193326Sed/// don't want to track enough to tell "x.." from "...".
160207619Srdivackybool TokenConcatenation::AvoidConcat(const Token &PrevPrevTok,
161207619Srdivacky                                     const Token &PrevTok,
162193326Sed                                     const Token &Tok) const {
163353358Sdim  // Conservatively assume that every annotation token that has a printable
164353358Sdim  // form requires whitespace.
165353358Sdim  if (PrevTok.isAnnotation())
166353358Sdim    return true;
167353358Sdim
168193326Sed  // First, check to see if the tokens were directly adjacent in the original
169193326Sed  // source.  If they were, it must be okay to stick them together: if there
170193326Sed  // were an issue, the tokens would have been lexed differently.
171249423Sdim  SourceManager &SM = PP.getSourceManager();
172249423Sdim  SourceLocation PrevSpellLoc = SM.getSpellingLoc(PrevTok.getLocation());
173249423Sdim  SourceLocation SpellLoc = SM.getSpellingLoc(Tok.getLocation());
174249423Sdim  if (PrevSpellLoc.getLocWithOffset(PrevTok.getLength()) == SpellLoc)
175193326Sed    return false;
176198092Srdivacky
177193326Sed  tok::TokenKind PrevKind = PrevTok.getKind();
178280031Sdim  if (!PrevTok.isAnnotation() && PrevTok.getIdentifierInfo())
179280031Sdim    PrevKind = tok::identifier; // Language keyword or named operator.
180198092Srdivacky
181193326Sed  // Look up information on when we should avoid concatenation with prevtok.
182193326Sed  unsigned ConcatInfo = TokenInfo[PrevKind];
183198092Srdivacky
184193326Sed  // If prevtok never causes a problem for anything after it, return quickly.
185193326Sed  if (ConcatInfo == 0) return false;
186198092Srdivacky
187193326Sed  if (ConcatInfo & aci_avoid_equal) {
188193326Sed    // If the next token is '=' or '==', avoid concatenation.
189288943Sdim    if (Tok.isOneOf(tok::equal, tok::equalequal))
190193326Sed      return true;
191193326Sed    ConcatInfo &= ~aci_avoid_equal;
192193326Sed  }
193280031Sdim  if (Tok.isAnnotation()) {
194280031Sdim    // Modules annotation can show up when generated automatically for includes.
195288943Sdim    assert(Tok.isOneOf(tok::annot_module_include, tok::annot_module_begin,
196288943Sdim                       tok::annot_module_end) &&
197280031Sdim           "unexpected annotation in AvoidConcat");
198280031Sdim    ConcatInfo = 0;
199280031Sdim  }
200198092Srdivacky
201288943Sdim  if (ConcatInfo == 0)
202288943Sdim    return false;
203198092Srdivacky
204193326Sed  // Basic algorithm: we look at the first character of the second token, and
205193326Sed  // determine whether it, if appended to the first token, would form (or
206193326Sed  // would contribute) to a larger token if concatenated.
207193326Sed  char FirstChar = 0;
208193326Sed  if (ConcatInfo & aci_custom) {
209193326Sed    // If the token does not need to know the first character, don't get it.
210193326Sed  } else {
211193326Sed    FirstChar = GetFirstChar(PP, Tok);
212193326Sed  }
213198092Srdivacky
214193326Sed  switch (PrevKind) {
215218893Sdim  default:
216218893Sdim    llvm_unreachable("InitAvoidConcatTokenInfo built wrong");
217218893Sdim
218218893Sdim  case tok::raw_identifier:
219218893Sdim    llvm_unreachable("tok::raw_identifier in non-raw lexing mode!");
220218893Sdim
221234353Sdim  case tok::string_literal:
222234353Sdim  case tok::wide_string_literal:
223234353Sdim  case tok::utf8_string_literal:
224234353Sdim  case tok::utf16_string_literal:
225234353Sdim  case tok::utf32_string_literal:
226234353Sdim  case tok::char_constant:
227234353Sdim  case tok::wide_char_constant:
228280031Sdim  case tok::utf8_char_constant:
229234353Sdim  case tok::utf16_char_constant:
230234353Sdim  case tok::utf32_char_constant:
231249423Sdim    if (!PP.getLangOpts().CPlusPlus11)
232234353Sdim      return false;
233234353Sdim
234234353Sdim    // In C++11, a string or character literal followed by an identifier is a
235234353Sdim    // single token.
236234353Sdim    if (Tok.getIdentifierInfo())
237234353Sdim      return true;
238234353Sdim
239234353Sdim    // A ud-suffix is an identifier. If the previous token ends with one, treat
240234353Sdim    // it as an identifier.
241234353Sdim    if (!PrevTok.hasUDSuffix())
242234353Sdim      return false;
243314564Sdim    LLVM_FALLTHROUGH;
244198092Srdivacky  case tok::identifier:   // id+id or id+number or id+L"foo".
245193326Sed    // id+'.'... will not append.
246193326Sed    if (Tok.is(tok::numeric_constant))
247193326Sed      return GetFirstChar(PP, Tok) != '.';
248193326Sed
249288943Sdim    if (Tok.getIdentifierInfo() ||
250288943Sdim        Tok.isOneOf(tok::wide_string_literal, tok::utf8_string_literal,
251288943Sdim                    tok::utf16_string_literal, tok::utf32_string_literal,
252288943Sdim                    tok::wide_char_constant, tok::utf8_char_constant,
253288943Sdim                    tok::utf16_char_constant, tok::utf32_char_constant))
254193326Sed      return true;
255198092Srdivacky
256193326Sed    // If this isn't identifier + string, we're done.
257193326Sed    if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))
258193326Sed      return false;
259198092Srdivacky
260193326Sed    // Otherwise, this is a narrow character or string.  If the *identifier*
261226633Sdim    // is a literal 'L', 'u8', 'u' or 'U', avoid pasting L "foo" -> L"foo".
262226633Sdim    return IsIdentifierStringPrefix(PrevTok);
263234353Sdim
264193326Sed  case tok::numeric_constant:
265249423Sdim    return isPreprocessingNumberBody(FirstChar) ||
266249423Sdim           FirstChar == '+' || FirstChar == '-';
267193326Sed  case tok::period:          // ..., .*, .1234
268207619Srdivacky    return (FirstChar == '.' && PrevPrevTok.is(tok::period)) ||
269249423Sdim           isDigit(FirstChar) ||
270249423Sdim           (PP.getLangOpts().CPlusPlus && FirstChar == '*');
271193326Sed  case tok::amp:             // &&
272193326Sed    return FirstChar == '&';
273193326Sed  case tok::plus:            // ++
274193326Sed    return FirstChar == '+';
275193326Sed  case tok::minus:           // --, ->, ->*
276193326Sed    return FirstChar == '-' || FirstChar == '>';
277193326Sed  case tok::slash:           //, /*, //
278193326Sed    return FirstChar == '*' || FirstChar == '/';
279193326Sed  case tok::less:            // <<, <<=, <:, <%
280193326Sed    return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
281193326Sed  case tok::greater:         // >>, >>=
282193326Sed    return FirstChar == '>';
283193326Sed  case tok::pipe:            // ||
284193326Sed    return FirstChar == '|';
285193326Sed  case tok::percent:         // %>, %:
286193326Sed    return FirstChar == '>' || FirstChar == ':';
287193326Sed  case tok::colon:           // ::, :>
288194613Sed    return FirstChar == '>' ||
289234353Sdim    (PP.getLangOpts().CPlusPlus && FirstChar == ':');
290193326Sed  case tok::hash:            // ##, #@, %:%:
291193326Sed    return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
292193326Sed  case tok::arrow:           // ->*
293234353Sdim    return PP.getLangOpts().CPlusPlus && FirstChar == '*';
294327952Sdim  case tok::lessequal:       // <=> (C++2a)
295327952Sdim    return PP.getLangOpts().CPlusPlus2a && FirstChar == '>';
296193326Sed  }
297193326Sed}
298