Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 1 | //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===// |
| 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 | /// \file |
| 11 | /// \brief This file implements FormatTokenLexer, which tokenizes a source file |
| 12 | /// into a FormatToken stream suitable for ClangFormat. |
| 13 | /// |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "FormatTokenLexer.h" |
| 17 | #include "FormatToken.h" |
| 18 | #include "clang/Basic/SourceLocation.h" |
| 19 | #include "clang/Basic/SourceManager.h" |
| 20 | #include "clang/Format/Format.h" |
| 21 | #include "llvm/Support/Regex.h" |
| 22 | |
| 23 | namespace clang { |
| 24 | namespace format { |
| 25 | |
| 26 | FormatTokenLexer::FormatTokenLexer(const SourceManager &SourceMgr, FileID ID, |
| 27 | const FormatStyle &Style, |
| 28 | encoding::Encoding Encoding) |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 29 | : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}), |
| 30 | Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID), |
| 31 | Style(Style), IdentTable(getFormattingLangOpts(Style)), |
| 32 | Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0), |
| 33 | FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin), |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 34 | MacroBlockEndRegex(Style.MacroBlockEnd) { |
| 35 | Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr, |
| 36 | getFormattingLangOpts(Style))); |
| 37 | Lex->SetKeepWhitespaceMode(true); |
| 38 | |
| 39 | for (const std::string &ForEachMacro : Style.ForEachMacros) |
| 40 | ForEachMacros.push_back(&IdentTable.get(ForEachMacro)); |
| 41 | std::sort(ForEachMacros.begin(), ForEachMacros.end()); |
| 42 | } |
| 43 | |
| 44 | ArrayRef<FormatToken *> FormatTokenLexer::lex() { |
| 45 | assert(Tokens.empty()); |
| 46 | assert(FirstInLineIndex == 0); |
| 47 | do { |
| 48 | Tokens.push_back(getNextToken()); |
| 49 | if (Style.Language == FormatStyle::LK_JavaScript) { |
| 50 | tryParseJSRegexLiteral(); |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 51 | handleTemplateStrings(); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 52 | } |
| 53 | tryMergePreviousTokens(); |
| 54 | if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline) |
| 55 | FirstInLineIndex = Tokens.size() - 1; |
| 56 | } while (Tokens.back()->Tok.isNot(tok::eof)); |
| 57 | return Tokens; |
| 58 | } |
| 59 | |
| 60 | void FormatTokenLexer::tryMergePreviousTokens() { |
| 61 | if (tryMerge_TMacro()) |
| 62 | return; |
| 63 | if (tryMergeConflictMarkers()) |
| 64 | return; |
| 65 | if (tryMergeLessLess()) |
| 66 | return; |
Alexander Kornienko | d4fa2e6 | 2017-04-11 09:55:00 +0000 | [diff] [blame] | 67 | if (tryMergeNSStringLiteral()) |
| 68 | return; |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 69 | |
| 70 | if (Style.Language == FormatStyle::LK_JavaScript) { |
| 71 | static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal}; |
| 72 | static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, |
| 73 | tok::equal}; |
| 74 | static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater, |
| 75 | tok::greaterequal}; |
| 76 | static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater}; |
Martin Probst | 4ef0370 | 2017-05-04 15:04:04 +0000 | [diff] [blame] | 77 | static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star}; |
| 78 | static const tok::TokenKind JSExponentiationEqual[] = {tok::star, |
| 79 | tok::starequal}; |
| 80 | |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 81 | // FIXME: Investigate what token type gives the correct operator priority. |
| 82 | if (tryMergeTokens(JSIdentity, TT_BinaryOperator)) |
| 83 | return; |
| 84 | if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator)) |
| 85 | return; |
| 86 | if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator)) |
| 87 | return; |
| 88 | if (tryMergeTokens(JSRightArrow, TT_JsFatArrow)) |
| 89 | return; |
Martin Probst | 4ef0370 | 2017-05-04 15:04:04 +0000 | [diff] [blame] | 90 | if (tryMergeTokens(JSExponentiation, TT_JsExponentiation)) |
| 91 | return; |
| 92 | if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) { |
| 93 | Tokens.back()->Tok.setKind(tok::starequal); |
| 94 | return; |
| 95 | } |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 96 | } |
Nico Weber | 48c94a6 | 2017-04-11 15:50:04 +0000 | [diff] [blame] | 97 | |
| 98 | if (Style.Language == FormatStyle::LK_Java) { |
| 99 | static const tok::TokenKind JavaRightLogicalShift[] = {tok::greater, |
| 100 | tok::greater, |
| 101 | tok::greater}; |
| 102 | static const tok::TokenKind JavaRightLogicalShiftAssign[] = {tok::greater, |
| 103 | tok::greater, |
| 104 | tok::greaterequal}; |
| 105 | if (tryMergeTokens(JavaRightLogicalShift, TT_BinaryOperator)) |
| 106 | return; |
| 107 | if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator)) |
| 108 | return; |
| 109 | } |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 110 | } |
| 111 | |
Alexander Kornienko | d4fa2e6 | 2017-04-11 09:55:00 +0000 | [diff] [blame] | 112 | bool FormatTokenLexer::tryMergeNSStringLiteral() { |
| 113 | if (Tokens.size() < 2) |
| 114 | return false; |
| 115 | auto &At = *(Tokens.end() - 2); |
| 116 | auto &String = *(Tokens.end() - 1); |
| 117 | if (!At->is(tok::at) || !String->is(tok::string_literal)) |
| 118 | return false; |
| 119 | At->Tok.setKind(tok::string_literal); |
| 120 | At->TokenText = StringRef(At->TokenText.begin(), |
| 121 | String->TokenText.end() - At->TokenText.begin()); |
| 122 | At->ColumnWidth += String->ColumnWidth; |
| 123 | At->Type = TT_ObjCStringLiteral; |
| 124 | Tokens.erase(Tokens.end() - 1); |
| 125 | return true; |
| 126 | } |
| 127 | |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 128 | bool FormatTokenLexer::tryMergeLessLess() { |
| 129 | // Merge X,less,less,Y into X,lessless,Y unless X or Y is less. |
| 130 | if (Tokens.size() < 3) |
| 131 | return false; |
| 132 | |
| 133 | bool FourthTokenIsLess = false; |
| 134 | if (Tokens.size() > 3) |
| 135 | FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less); |
| 136 | |
| 137 | auto First = Tokens.end() - 3; |
| 138 | if (First[2]->is(tok::less) || First[1]->isNot(tok::less) || |
| 139 | First[0]->isNot(tok::less) || FourthTokenIsLess) |
| 140 | return false; |
| 141 | |
| 142 | // Only merge if there currently is no whitespace between the two "<". |
| 143 | if (First[1]->WhitespaceRange.getBegin() != |
| 144 | First[1]->WhitespaceRange.getEnd()) |
| 145 | return false; |
| 146 | |
| 147 | First[0]->Tok.setKind(tok::lessless); |
| 148 | First[0]->TokenText = "<<"; |
| 149 | First[0]->ColumnWidth += 1; |
| 150 | Tokens.erase(Tokens.end() - 2); |
| 151 | return true; |
| 152 | } |
| 153 | |
| 154 | bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, |
| 155 | TokenType NewType) { |
| 156 | if (Tokens.size() < Kinds.size()) |
| 157 | return false; |
| 158 | |
| 159 | SmallVectorImpl<FormatToken *>::const_iterator First = |
| 160 | Tokens.end() - Kinds.size(); |
| 161 | if (!First[0]->is(Kinds[0])) |
| 162 | return false; |
| 163 | unsigned AddLength = 0; |
| 164 | for (unsigned i = 1; i < Kinds.size(); ++i) { |
| 165 | if (!First[i]->is(Kinds[i]) || |
| 166 | First[i]->WhitespaceRange.getBegin() != |
| 167 | First[i]->WhitespaceRange.getEnd()) |
| 168 | return false; |
| 169 | AddLength += First[i]->TokenText.size(); |
| 170 | } |
| 171 | Tokens.resize(Tokens.size() - Kinds.size() + 1); |
| 172 | First[0]->TokenText = StringRef(First[0]->TokenText.data(), |
| 173 | First[0]->TokenText.size() + AddLength); |
| 174 | First[0]->ColumnWidth += AddLength; |
| 175 | First[0]->Type = NewType; |
| 176 | return true; |
| 177 | } |
| 178 | |
| 179 | // Returns \c true if \p Tok can only be followed by an operand in JavaScript. |
| 180 | bool FormatTokenLexer::precedesOperand(FormatToken *Tok) { |
| 181 | // NB: This is not entirely correct, as an r_paren can introduce an operand |
| 182 | // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough |
| 183 | // corner case to not matter in practice, though. |
| 184 | return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace, |
| 185 | tok::r_brace, tok::l_square, tok::semi, tok::exclaim, |
| 186 | tok::colon, tok::question, tok::tilde) || |
| 187 | Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw, |
| 188 | tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void, |
| 189 | tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) || |
| 190 | Tok->isBinaryOperator(); |
| 191 | } |
| 192 | |
| 193 | bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) { |
| 194 | if (!Prev) |
| 195 | return true; |
| 196 | |
| 197 | // Regex literals can only follow after prefix unary operators, not after |
| 198 | // postfix unary operators. If the '++' is followed by a non-operand |
| 199 | // introducing token, the slash here is the operand and not the start of a |
| 200 | // regex. |
Martin Probst | 1628299 | 2017-02-07 14:08:03 +0000 | [diff] [blame] | 201 | // `!` is an unary prefix operator, but also a post-fix operator that casts |
| 202 | // away nullability, so the same check applies. |
| 203 | if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim)) |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 204 | return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3])); |
| 205 | |
| 206 | // The previous token must introduce an operand location where regex |
| 207 | // literals can occur. |
| 208 | if (!precedesOperand(Prev)) |
| 209 | return false; |
| 210 | |
| 211 | return true; |
| 212 | } |
| 213 | |
| 214 | // Tries to parse a JavaScript Regex literal starting at the current token, |
| 215 | // if that begins with a slash and is in a location where JavaScript allows |
| 216 | // regex literals. Changes the current token to a regex literal and updates |
| 217 | // its text if successful. |
| 218 | void FormatTokenLexer::tryParseJSRegexLiteral() { |
| 219 | FormatToken *RegexToken = Tokens.back(); |
| 220 | if (!RegexToken->isOneOf(tok::slash, tok::slashequal)) |
| 221 | return; |
| 222 | |
| 223 | FormatToken *Prev = nullptr; |
| 224 | for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) { |
| 225 | // NB: Because previous pointers are not initialized yet, this cannot use |
| 226 | // Token.getPreviousNonComment. |
| 227 | if ((*I)->isNot(tok::comment)) { |
| 228 | Prev = *I; |
| 229 | break; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | if (!canPrecedeRegexLiteral(Prev)) |
| 234 | return; |
| 235 | |
| 236 | // 'Manually' lex ahead in the current file buffer. |
| 237 | const char *Offset = Lex->getBufferLocation(); |
| 238 | const char *RegexBegin = Offset - RegexToken->TokenText.size(); |
| 239 | StringRef Buffer = Lex->getBuffer(); |
| 240 | bool InCharacterClass = false; |
| 241 | bool HaveClosingSlash = false; |
| 242 | for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) { |
| 243 | // Regular expressions are terminated with a '/', which can only be |
| 244 | // escaped using '\' or a character class between '[' and ']'. |
| 245 | // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5. |
| 246 | switch (*Offset) { |
| 247 | case '\\': |
| 248 | // Skip the escaped character. |
| 249 | ++Offset; |
| 250 | break; |
| 251 | case '[': |
| 252 | InCharacterClass = true; |
| 253 | break; |
| 254 | case ']': |
| 255 | InCharacterClass = false; |
| 256 | break; |
| 257 | case '/': |
| 258 | if (!InCharacterClass) |
| 259 | HaveClosingSlash = true; |
| 260 | break; |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | RegexToken->Type = TT_RegexLiteral; |
| 265 | // Treat regex literals like other string_literals. |
| 266 | RegexToken->Tok.setKind(tok::string_literal); |
| 267 | RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin); |
| 268 | RegexToken->ColumnWidth = RegexToken->TokenText.size(); |
| 269 | |
| 270 | resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); |
| 271 | } |
| 272 | |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 273 | void FormatTokenLexer::handleTemplateStrings() { |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 274 | FormatToken *BacktickToken = Tokens.back(); |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 275 | |
| 276 | if (BacktickToken->is(tok::l_brace)) { |
| 277 | StateStack.push(LexerState::NORMAL); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 278 | return; |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 279 | } |
| 280 | if (BacktickToken->is(tok::r_brace)) { |
Daniel Jasper | 58209dd | 2016-09-17 07:20:36 +0000 | [diff] [blame] | 281 | if (StateStack.size() == 1) |
| 282 | return; |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 283 | StateStack.pop(); |
| 284 | if (StateStack.top() != LexerState::TEMPLATE_STRING) |
| 285 | return; |
| 286 | // If back in TEMPLATE_STRING, fallthrough and continue parsing the |
| 287 | } else if (BacktickToken->is(tok::unknown) && |
| 288 | BacktickToken->TokenText == "`") { |
| 289 | StateStack.push(LexerState::TEMPLATE_STRING); |
| 290 | } else { |
| 291 | return; // Not actually a template |
| 292 | } |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 293 | |
| 294 | // 'Manually' lex ahead in the current file buffer. |
| 295 | const char *Offset = Lex->getBufferLocation(); |
| 296 | const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`" |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 297 | for (; Offset != Lex->getBuffer().end(); ++Offset) { |
| 298 | if (Offset[0] == '`') { |
| 299 | StateStack.pop(); |
| 300 | break; |
| 301 | } |
| 302 | if (Offset[0] == '\\') { |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 303 | ++Offset; // Skip the escaped character. |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 304 | } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' && |
| 305 | Offset[1] == '{') { |
| 306 | // '${' introduces an expression interpolation in the template string. |
| 307 | StateStack.push(LexerState::NORMAL); |
| 308 | ++Offset; |
| 309 | break; |
| 310 | } |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 311 | } |
| 312 | |
| 313 | StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1); |
| 314 | BacktickToken->Type = TT_TemplateString; |
| 315 | BacktickToken->Tok.setKind(tok::string_literal); |
| 316 | BacktickToken->TokenText = LiteralText; |
| 317 | |
| 318 | // Adjust width for potentially multiline string literals. |
| 319 | size_t FirstBreak = LiteralText.find('\n'); |
| 320 | StringRef FirstLineText = FirstBreak == StringRef::npos |
| 321 | ? LiteralText |
| 322 | : LiteralText.substr(0, FirstBreak); |
| 323 | BacktickToken->ColumnWidth = encoding::columnWidthWithTabs( |
| 324 | FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding); |
| 325 | size_t LastBreak = LiteralText.rfind('\n'); |
| 326 | if (LastBreak != StringRef::npos) { |
| 327 | BacktickToken->IsMultiline = true; |
| 328 | unsigned StartColumn = 0; // The template tail spans the entire line. |
| 329 | BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs( |
| 330 | LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn, |
| 331 | Style.TabWidth, Encoding); |
| 332 | } |
| 333 | |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 334 | SourceLocation loc = Offset < Lex->getBuffer().end() |
| 335 | ? Lex->getSourceLocation(Offset + 1) |
| 336 | : SourceMgr.getLocForEndOfFile(ID); |
| 337 | resetLexer(SourceMgr.getFileOffset(loc)); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 338 | } |
| 339 | |
| 340 | bool FormatTokenLexer::tryMerge_TMacro() { |
| 341 | if (Tokens.size() < 4) |
| 342 | return false; |
| 343 | FormatToken *Last = Tokens.back(); |
| 344 | if (!Last->is(tok::r_paren)) |
| 345 | return false; |
| 346 | |
| 347 | FormatToken *String = Tokens[Tokens.size() - 2]; |
| 348 | if (!String->is(tok::string_literal) || String->IsMultiline) |
| 349 | return false; |
| 350 | |
| 351 | if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) |
| 352 | return false; |
| 353 | |
| 354 | FormatToken *Macro = Tokens[Tokens.size() - 4]; |
| 355 | if (Macro->TokenText != "_T") |
| 356 | return false; |
| 357 | |
| 358 | const char *Start = Macro->TokenText.data(); |
| 359 | const char *End = Last->TokenText.data() + Last->TokenText.size(); |
| 360 | String->TokenText = StringRef(Start, End - Start); |
| 361 | String->IsFirst = Macro->IsFirst; |
| 362 | String->LastNewlineOffset = Macro->LastNewlineOffset; |
| 363 | String->WhitespaceRange = Macro->WhitespaceRange; |
| 364 | String->OriginalColumn = Macro->OriginalColumn; |
| 365 | String->ColumnWidth = encoding::columnWidthWithTabs( |
| 366 | String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); |
| 367 | String->NewlinesBefore = Macro->NewlinesBefore; |
| 368 | String->HasUnescapedNewline = Macro->HasUnescapedNewline; |
| 369 | |
| 370 | Tokens.pop_back(); |
| 371 | Tokens.pop_back(); |
| 372 | Tokens.pop_back(); |
| 373 | Tokens.back() = String; |
| 374 | return true; |
| 375 | } |
| 376 | |
| 377 | bool FormatTokenLexer::tryMergeConflictMarkers() { |
| 378 | if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof)) |
| 379 | return false; |
| 380 | |
| 381 | // Conflict lines look like: |
| 382 | // <marker> <text from the vcs> |
| 383 | // For example: |
| 384 | // >>>>>>> /file/in/file/system at revision 1234 |
| 385 | // |
| 386 | // We merge all tokens in a line that starts with a conflict marker |
| 387 | // into a single token with a special token type that the unwrapped line |
| 388 | // parser will use to correctly rebuild the underlying code. |
| 389 | |
| 390 | FileID ID; |
| 391 | // Get the position of the first token in the line. |
| 392 | unsigned FirstInLineOffset; |
| 393 | std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc( |
| 394 | Tokens[FirstInLineIndex]->getStartOfNonWhitespace()); |
| 395 | StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer(); |
| 396 | // Calculate the offset of the start of the current line. |
| 397 | auto LineOffset = Buffer.rfind('\n', FirstInLineOffset); |
| 398 | if (LineOffset == StringRef::npos) { |
| 399 | LineOffset = 0; |
| 400 | } else { |
| 401 | ++LineOffset; |
| 402 | } |
| 403 | |
| 404 | auto FirstSpace = Buffer.find_first_of(" \n", LineOffset); |
| 405 | StringRef LineStart; |
| 406 | if (FirstSpace == StringRef::npos) { |
| 407 | LineStart = Buffer.substr(LineOffset); |
| 408 | } else { |
| 409 | LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset); |
| 410 | } |
| 411 | |
| 412 | TokenType Type = TT_Unknown; |
| 413 | if (LineStart == "<<<<<<<" || LineStart == ">>>>") { |
| 414 | Type = TT_ConflictStart; |
| 415 | } else if (LineStart == "|||||||" || LineStart == "=======" || |
| 416 | LineStart == "====") { |
| 417 | Type = TT_ConflictAlternative; |
| 418 | } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") { |
| 419 | Type = TT_ConflictEnd; |
| 420 | } |
| 421 | |
| 422 | if (Type != TT_Unknown) { |
| 423 | FormatToken *Next = Tokens.back(); |
| 424 | |
| 425 | Tokens.resize(FirstInLineIndex + 1); |
| 426 | // We do not need to build a complete token here, as we will skip it |
| 427 | // during parsing anyway (as we must not touch whitespace around conflict |
| 428 | // markers). |
| 429 | Tokens.back()->Type = Type; |
| 430 | Tokens.back()->Tok.setKind(tok::kw___unknown_anytype); |
| 431 | |
| 432 | Tokens.push_back(Next); |
| 433 | return true; |
| 434 | } |
| 435 | |
| 436 | return false; |
| 437 | } |
| 438 | |
| 439 | FormatToken *FormatTokenLexer::getStashedToken() { |
| 440 | // Create a synthesized second '>' or '<' token. |
| 441 | Token Tok = FormatTok->Tok; |
| 442 | StringRef TokenText = FormatTok->TokenText; |
| 443 | |
| 444 | unsigned OriginalColumn = FormatTok->OriginalColumn; |
| 445 | FormatTok = new (Allocator.Allocate()) FormatToken; |
| 446 | FormatTok->Tok = Tok; |
| 447 | SourceLocation TokLocation = |
| 448 | FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1); |
| 449 | FormatTok->Tok.setLocation(TokLocation); |
| 450 | FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation); |
| 451 | FormatTok->TokenText = TokenText; |
| 452 | FormatTok->ColumnWidth = 1; |
| 453 | FormatTok->OriginalColumn = OriginalColumn + 1; |
| 454 | |
| 455 | return FormatTok; |
| 456 | } |
| 457 | |
| 458 | FormatToken *FormatTokenLexer::getNextToken() { |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 459 | if (StateStack.top() == LexerState::TOKEN_STASHED) { |
| 460 | StateStack.pop(); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 461 | return getStashedToken(); |
| 462 | } |
| 463 | |
| 464 | FormatTok = new (Allocator.Allocate()) FormatToken; |
| 465 | readRawToken(*FormatTok); |
| 466 | SourceLocation WhitespaceStart = |
| 467 | FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); |
| 468 | FormatTok->IsFirst = IsFirstToken; |
| 469 | IsFirstToken = false; |
| 470 | |
| 471 | // Consume and record whitespace until we find a significant token. |
| 472 | unsigned WhitespaceLength = TrailingWhitespace; |
| 473 | while (FormatTok->Tok.is(tok::unknown)) { |
| 474 | StringRef Text = FormatTok->TokenText; |
| 475 | auto EscapesNewline = [&](int pos) { |
| 476 | // A '\r' here is just part of '\r\n'. Skip it. |
| 477 | if (pos >= 0 && Text[pos] == '\r') |
| 478 | --pos; |
| 479 | // See whether there is an odd number of '\' before this. |
Richard Smith | 1d2ae94 | 2017-04-17 23:44:51 +0000 | [diff] [blame] | 480 | // FIXME: This is wrong. A '\' followed by a newline is always removed, |
| 481 | // regardless of whether there is another '\' before it. |
| 482 | // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph. |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 483 | unsigned count = 0; |
| 484 | for (; pos >= 0; --pos, ++count) |
| 485 | if (Text[pos] != '\\') |
| 486 | break; |
| 487 | return count & 1; |
| 488 | }; |
| 489 | // FIXME: This miscounts tok:unknown tokens that are not just |
| 490 | // whitespace, e.g. a '`' character. |
| 491 | for (int i = 0, e = Text.size(); i != e; ++i) { |
| 492 | switch (Text[i]) { |
| 493 | case '\n': |
| 494 | ++FormatTok->NewlinesBefore; |
| 495 | FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1); |
| 496 | FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; |
| 497 | Column = 0; |
| 498 | break; |
| 499 | case '\r': |
| 500 | FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; |
| 501 | Column = 0; |
| 502 | break; |
| 503 | case '\f': |
| 504 | case '\v': |
| 505 | Column = 0; |
| 506 | break; |
| 507 | case ' ': |
| 508 | ++Column; |
| 509 | break; |
| 510 | case '\t': |
| 511 | Column += Style.TabWidth - Column % Style.TabWidth; |
| 512 | break; |
| 513 | case '\\': |
| 514 | if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n')) |
| 515 | FormatTok->Type = TT_ImplicitStringLiteral; |
| 516 | break; |
| 517 | default: |
| 518 | FormatTok->Type = TT_ImplicitStringLiteral; |
| 519 | break; |
| 520 | } |
| 521 | if (FormatTok->Type == TT_ImplicitStringLiteral) |
| 522 | break; |
| 523 | } |
| 524 | |
| 525 | if (FormatTok->is(TT_ImplicitStringLiteral)) |
| 526 | break; |
| 527 | WhitespaceLength += FormatTok->Tok.getLength(); |
| 528 | |
| 529 | readRawToken(*FormatTok); |
| 530 | } |
| 531 | |
Martin Probst | 64d31ed | 2017-08-08 14:52:42 +0000 | [diff] [blame^] | 532 | // JavaScript and Java do not allow to escape the end of the line with a |
| 533 | // backslash. Backslashes are syntax errors in plain source, but can occur in |
| 534 | // comments. When a single line comment ends with a \, it'll cause the next |
| 535 | // line of code to be lexed as a comment, breaking formatting. The code below |
| 536 | // finds comments that contain a backslash followed by a line break, truncates |
| 537 | // the comment token at the backslash, and resets the lexer to restart behind |
| 538 | // the backslash. |
| 539 | if ((Style.Language == FormatStyle::LK_JavaScript || |
| 540 | Style.Language == FormatStyle::LK_Java) && |
| 541 | FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) { |
| 542 | size_t BackslashPos = FormatTok->TokenText.find('\\'); |
| 543 | while (BackslashPos != StringRef::npos) { |
| 544 | if (BackslashPos + 1 < FormatTok->TokenText.size() && |
| 545 | FormatTok->TokenText[BackslashPos + 1] == '\n') { |
| 546 | const char *Offset = Lex->getBufferLocation(); |
| 547 | Offset -= FormatTok->TokenText.size(); |
| 548 | Offset += BackslashPos + 1; |
| 549 | resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); |
| 550 | FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1); |
| 551 | FormatTok->ColumnWidth = encoding::columnWidthWithTabs( |
| 552 | FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth, |
| 553 | Encoding); |
| 554 | break; |
| 555 | } |
| 556 | BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1); |
| 557 | } |
| 558 | } |
| 559 | |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 560 | // In case the token starts with escaped newlines, we want to |
| 561 | // take them into account as whitespace - this pattern is quite frequent |
| 562 | // in macro definitions. |
| 563 | // FIXME: Add a more explicit test. |
| 564 | while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' && |
| 565 | FormatTok->TokenText[1] == '\n') { |
| 566 | ++FormatTok->NewlinesBefore; |
| 567 | WhitespaceLength += 2; |
| 568 | FormatTok->LastNewlineOffset = 2; |
| 569 | Column = 0; |
| 570 | FormatTok->TokenText = FormatTok->TokenText.substr(2); |
| 571 | } |
| 572 | |
| 573 | FormatTok->WhitespaceRange = SourceRange( |
| 574 | WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); |
| 575 | |
| 576 | FormatTok->OriginalColumn = Column; |
| 577 | |
| 578 | TrailingWhitespace = 0; |
| 579 | if (FormatTok->Tok.is(tok::comment)) { |
| 580 | // FIXME: Add the trimmed whitespace to Column. |
| 581 | StringRef UntrimmedText = FormatTok->TokenText; |
| 582 | FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); |
| 583 | TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); |
| 584 | } else if (FormatTok->Tok.is(tok::raw_identifier)) { |
| 585 | IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); |
| 586 | FormatTok->Tok.setIdentifierInfo(&Info); |
| 587 | FormatTok->Tok.setKind(Info.getTokenID()); |
| 588 | if (Style.Language == FormatStyle::LK_Java && |
| 589 | FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete, |
| 590 | tok::kw_operator)) { |
| 591 | FormatTok->Tok.setKind(tok::identifier); |
| 592 | FormatTok->Tok.setIdentifierInfo(nullptr); |
| 593 | } else if (Style.Language == FormatStyle::LK_JavaScript && |
| 594 | FormatTok->isOneOf(tok::kw_struct, tok::kw_union, |
| 595 | tok::kw_operator)) { |
| 596 | FormatTok->Tok.setKind(tok::identifier); |
| 597 | FormatTok->Tok.setIdentifierInfo(nullptr); |
| 598 | } |
| 599 | } else if (FormatTok->Tok.is(tok::greatergreater)) { |
| 600 | FormatTok->Tok.setKind(tok::greater); |
| 601 | FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); |
Malcolm Parsons | 6af3f14 | 2016-11-03 16:57:30 +0000 | [diff] [blame] | 602 | ++Column; |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 603 | StateStack.push(LexerState::TOKEN_STASHED); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 604 | } else if (FormatTok->Tok.is(tok::lessless)) { |
| 605 | FormatTok->Tok.setKind(tok::less); |
| 606 | FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); |
Malcolm Parsons | 6af3f14 | 2016-11-03 16:57:30 +0000 | [diff] [blame] | 607 | ++Column; |
Martin Probst | 6181da4 | 2016-08-25 10:13:21 +0000 | [diff] [blame] | 608 | StateStack.push(LexerState::TOKEN_STASHED); |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 609 | } |
| 610 | |
| 611 | // Now FormatTok is the next non-whitespace token. |
| 612 | |
| 613 | StringRef Text = FormatTok->TokenText; |
| 614 | size_t FirstNewlinePos = Text.find('\n'); |
| 615 | if (FirstNewlinePos == StringRef::npos) { |
| 616 | // FIXME: ColumnWidth actually depends on the start column, we need to |
| 617 | // take this into account when the token is moved. |
| 618 | FormatTok->ColumnWidth = |
| 619 | encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); |
| 620 | Column += FormatTok->ColumnWidth; |
| 621 | } else { |
| 622 | FormatTok->IsMultiline = true; |
| 623 | // FIXME: ColumnWidth actually depends on the start column, we need to |
| 624 | // take this into account when the token is moved. |
| 625 | FormatTok->ColumnWidth = encoding::columnWidthWithTabs( |
| 626 | Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); |
| 627 | |
| 628 | // The last line of the token always starts in column 0. |
| 629 | // Thus, the length can be precomputed even in the presence of tabs. |
| 630 | FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( |
| 631 | Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding); |
| 632 | Column = FormatTok->LastLineColumnWidth; |
| 633 | } |
| 634 | |
Daniel Jasper | 1dbc210 | 2017-03-31 13:30:24 +0000 | [diff] [blame] | 635 | if (Style.isCpp()) { |
Martin Probst | c4a0dd4 | 2016-05-20 11:24:24 +0000 | [diff] [blame] | 636 | if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() && |
| 637 | Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() == |
| 638 | tok::pp_define) && |
| 639 | std::find(ForEachMacros.begin(), ForEachMacros.end(), |
| 640 | FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) { |
| 641 | FormatTok->Type = TT_ForEachMacro; |
| 642 | } else if (FormatTok->is(tok::identifier)) { |
| 643 | if (MacroBlockBeginRegex.match(Text)) { |
| 644 | FormatTok->Type = TT_MacroBlockBegin; |
| 645 | } else if (MacroBlockEndRegex.match(Text)) { |
| 646 | FormatTok->Type = TT_MacroBlockEnd; |
| 647 | } |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | return FormatTok; |
| 652 | } |
| 653 | |
| 654 | void FormatTokenLexer::readRawToken(FormatToken &Tok) { |
| 655 | Lex->LexFromRawLexer(Tok.Tok); |
| 656 | Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), |
| 657 | Tok.Tok.getLength()); |
| 658 | // For formatting, treat unterminated string literals like normal string |
| 659 | // literals. |
| 660 | if (Tok.is(tok::unknown)) { |
| 661 | if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') { |
| 662 | Tok.Tok.setKind(tok::string_literal); |
| 663 | Tok.IsUnterminatedLiteral = true; |
| 664 | } else if (Style.Language == FormatStyle::LK_JavaScript && |
| 665 | Tok.TokenText == "''") { |
| 666 | Tok.Tok.setKind(tok::string_literal); |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | if (Style.Language == FormatStyle::LK_JavaScript && |
| 671 | Tok.is(tok::char_constant)) { |
| 672 | Tok.Tok.setKind(tok::string_literal); |
| 673 | } |
| 674 | |
| 675 | if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" || |
| 676 | Tok.TokenText == "/* clang-format on */")) { |
| 677 | FormattingDisabled = false; |
| 678 | } |
| 679 | |
| 680 | Tok.Finalized = FormattingDisabled; |
| 681 | |
| 682 | if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" || |
| 683 | Tok.TokenText == "/* clang-format off */")) { |
| 684 | FormattingDisabled = true; |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | void FormatTokenLexer::resetLexer(unsigned Offset) { |
| 689 | StringRef Buffer = SourceMgr.getBufferData(ID); |
| 690 | Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), |
| 691 | getFormattingLangOpts(Style), Buffer.begin(), |
| 692 | Buffer.begin() + Offset, Buffer.end())); |
| 693 | Lex->SetKeepWhitespaceMode(true); |
| 694 | TrailingWhitespace = 0; |
| 695 | } |
| 696 | |
| 697 | } // namespace format |
| 698 | } // namespace clang |