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