1 //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===// 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 /// \file 10 /// This file implements FormatTokenLexer, which tokenizes a source file 11 /// into a FormatToken stream suitable for ClangFormat. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "FormatTokenLexer.h" 16 #include "FormatToken.h" 17 #include "clang/Basic/SourceLocation.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Format/Format.h" 20 #include "llvm/Support/Regex.h" 21 22 namespace clang { 23 namespace format { 24 25 FormatTokenLexer::FormatTokenLexer(const SourceManager &SourceMgr, FileID ID, 26 unsigned Column, const FormatStyle &Style, 27 encoding::Encoding Encoding) 28 : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}), 29 Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID), 30 Style(Style), IdentTable(getFormattingLangOpts(Style)), 31 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0), 32 FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin), 33 MacroBlockEndRegex(Style.MacroBlockEnd) { 34 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr, 35 getFormattingLangOpts(Style))); 36 Lex->SetKeepWhitespaceMode(true); 37 38 for (const std::string &ForEachMacro : Style.ForEachMacros) 39 Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro}); 40 for (const std::string &StatementMacro : Style.StatementMacros) 41 Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro}); 42 for (const std::string &TypenameMacro : Style.TypenameMacros) 43 Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro}); 44 for (const std::string &NamespaceMacro : Style.NamespaceMacros) 45 Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro}); 46 } 47 48 ArrayRef<FormatToken *> FormatTokenLexer::lex() { 49 assert(Tokens.empty()); 50 assert(FirstInLineIndex == 0); 51 do { 52 Tokens.push_back(getNextToken()); 53 if (Style.Language == FormatStyle::LK_JavaScript) { 54 tryParseJSRegexLiteral(); 55 handleTemplateStrings(); 56 } 57 if (Style.Language == FormatStyle::LK_TextProto) 58 tryParsePythonComment(); 59 tryMergePreviousTokens(); 60 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline) 61 FirstInLineIndex = Tokens.size() - 1; 62 } while (Tokens.back()->Tok.isNot(tok::eof)); 63 return Tokens; 64 } 65 66 void FormatTokenLexer::tryMergePreviousTokens() { 67 if (tryMerge_TMacro()) 68 return; 69 if (tryMergeConflictMarkers()) 70 return; 71 if (tryMergeLessLess()) 72 return; 73 74 if (Style.isCSharp()) { 75 if (tryMergeCSharpKeywordVariables()) 76 return; 77 if (tryMergeCSharpStringLiteral()) 78 return; 79 if (tryMergeCSharpDoubleQuestion()) 80 return; 81 if (tryMergeCSharpNullConditionals()) 82 return; 83 if (tryTransformCSharpForEach()) 84 return; 85 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater}; 86 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow)) 87 return; 88 } 89 90 if (tryMergeNSStringLiteral()) 91 return; 92 93 if (Style.Language == FormatStyle::LK_JavaScript) { 94 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal}; 95 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, 96 tok::equal}; 97 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater, 98 tok::greaterequal}; 99 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater}; 100 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star}; 101 static const tok::TokenKind JSExponentiationEqual[] = {tok::star, 102 tok::starequal}; 103 static const tok::TokenKind JSNullPropagatingOperator[] = {tok::question, 104 tok::period}; 105 static const tok::TokenKind JSNullishOperator[] = {tok::question, 106 tok::question}; 107 108 // FIXME: Investigate what token type gives the correct operator priority. 109 if (tryMergeTokens(JSIdentity, TT_BinaryOperator)) 110 return; 111 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator)) 112 return; 113 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator)) 114 return; 115 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow)) 116 return; 117 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation)) 118 return; 119 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) { 120 Tokens.back()->Tok.setKind(tok::starequal); 121 return; 122 } 123 if (tryMergeTokens(JSNullishOperator, TT_JsNullishCoalescingOperator)) { 124 // Treat like the "||" operator (as opposed to the ternary ?). 125 Tokens.back()->Tok.setKind(tok::pipepipe); 126 return; 127 } 128 if (tryMergeTokens(JSNullPropagatingOperator, 129 TT_JsNullPropagatingOperator)) { 130 // Treat like a regular "." access. 131 Tokens.back()->Tok.setKind(tok::period); 132 return; 133 } 134 if (tryMergeJSPrivateIdentifier()) 135 return; 136 } 137 138 if (Style.Language == FormatStyle::LK_Java) { 139 static const tok::TokenKind JavaRightLogicalShiftAssign[] = { 140 tok::greater, tok::greater, tok::greaterequal}; 141 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator)) 142 return; 143 } 144 } 145 146 bool FormatTokenLexer::tryMergeNSStringLiteral() { 147 if (Tokens.size() < 2) 148 return false; 149 auto &At = *(Tokens.end() - 2); 150 auto &String = *(Tokens.end() - 1); 151 if (!At->is(tok::at) || !String->is(tok::string_literal)) 152 return false; 153 At->Tok.setKind(tok::string_literal); 154 At->TokenText = StringRef(At->TokenText.begin(), 155 String->TokenText.end() - At->TokenText.begin()); 156 At->ColumnWidth += String->ColumnWidth; 157 At->Type = TT_ObjCStringLiteral; 158 Tokens.erase(Tokens.end() - 1); 159 return true; 160 } 161 162 bool FormatTokenLexer::tryMergeJSPrivateIdentifier() { 163 // Merges #idenfier into a single identifier with the text #identifier 164 // but the token tok::identifier. 165 if (Tokens.size() < 2) 166 return false; 167 auto &Hash = *(Tokens.end() - 2); 168 auto &Identifier = *(Tokens.end() - 1); 169 if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier)) 170 return false; 171 Hash->Tok.setKind(tok::identifier); 172 Hash->TokenText = 173 StringRef(Hash->TokenText.begin(), 174 Identifier->TokenText.end() - Hash->TokenText.begin()); 175 Hash->ColumnWidth += Identifier->ColumnWidth; 176 Hash->Type = TT_JsPrivateIdentifier; 177 Tokens.erase(Tokens.end() - 1); 178 return true; 179 } 180 181 // Search for verbatim or interpolated string literals @"ABC" or 182 // $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to 183 // prevent splitting of @, $ and ". 184 bool FormatTokenLexer::tryMergeCSharpStringLiteral() { 185 if (Tokens.size() < 2) 186 return false; 187 188 auto &CSharpStringLiteral = *(Tokens.end() - 2); 189 190 // Interpolated strings could contain { } with " characters inside. 191 // $"{x ?? "null"}" 192 // should not be split into $"{x ?? ", null, "}" but should treated as a 193 // single string-literal. 194 // 195 // We opt not to try and format expressions inside {} within a C# 196 // interpolated string. Formatting expressions within an interpolated string 197 // would require similar work as that done for JavaScript template strings 198 // in `handleTemplateStrings()`. 199 auto &CSharpInterpolatedString = *(Tokens.end() - 2); 200 if (CSharpInterpolatedString->Type == TT_CSharpStringLiteral && 201 (CSharpInterpolatedString->TokenText.startswith(R"($")") || 202 CSharpInterpolatedString->TokenText.startswith(R"($@")"))) { 203 int UnmatchedOpeningBraceCount = 0; 204 205 auto TokenTextSize = CSharpInterpolatedString->TokenText.size(); 206 for (size_t Index = 0; Index < TokenTextSize; ++Index) { 207 char C = CSharpInterpolatedString->TokenText[Index]; 208 if (C == '{') { 209 // "{{" inside an interpolated string is an escaped '{' so skip it. 210 if (Index + 1 < TokenTextSize && 211 CSharpInterpolatedString->TokenText[Index + 1] == '{') { 212 ++Index; 213 continue; 214 } 215 ++UnmatchedOpeningBraceCount; 216 } else if (C == '}') { 217 // "}}" inside an interpolated string is an escaped '}' so skip it. 218 if (Index + 1 < TokenTextSize && 219 CSharpInterpolatedString->TokenText[Index + 1] == '}') { 220 ++Index; 221 continue; 222 } 223 --UnmatchedOpeningBraceCount; 224 } 225 } 226 227 if (UnmatchedOpeningBraceCount > 0) { 228 auto &NextToken = *(Tokens.end() - 1); 229 CSharpInterpolatedString->TokenText = 230 StringRef(CSharpInterpolatedString->TokenText.begin(), 231 NextToken->TokenText.end() - 232 CSharpInterpolatedString->TokenText.begin()); 233 CSharpInterpolatedString->ColumnWidth += NextToken->ColumnWidth; 234 Tokens.erase(Tokens.end() - 1); 235 return true; 236 } 237 } 238 239 // verbatim strings could contain "" which C# sees as an escaped ". 240 // @"""Hello""" will have been tokenized as @"" "Hello" "" and needs 241 // merging into a single string literal. 242 auto &String = *(Tokens.end() - 1); 243 if (!String->is(tok::string_literal)) 244 return false; 245 246 if (CSharpStringLiteral->Type == TT_CSharpStringLiteral && 247 (CSharpStringLiteral->TokenText.startswith(R"(@")") || 248 CSharpStringLiteral->TokenText.startswith(R"($@")"))) { 249 CSharpStringLiteral->TokenText = StringRef( 250 CSharpStringLiteral->TokenText.begin(), 251 String->TokenText.end() - CSharpStringLiteral->TokenText.begin()); 252 CSharpStringLiteral->ColumnWidth += String->ColumnWidth; 253 Tokens.erase(Tokens.end() - 1); 254 return true; 255 } 256 257 auto &At = *(Tokens.end() - 2); 258 259 // Look for @"aaaaaa" or $"aaaaaa". 260 if (!(At->is(tok::at) || At->TokenText == "$")) 261 return false; 262 263 if (Tokens.size() > 2 && At->is(tok::at)) { 264 auto &Dollar = *(Tokens.end() - 3); 265 if (Dollar->TokenText == "$") { 266 // This looks like $@"aaaaa" so we need to combine all 3 tokens. 267 Dollar->Tok.setKind(tok::string_literal); 268 Dollar->TokenText = 269 StringRef(Dollar->TokenText.begin(), 270 String->TokenText.end() - Dollar->TokenText.begin()); 271 Dollar->ColumnWidth += (At->ColumnWidth + String->ColumnWidth); 272 Dollar->Type = TT_CSharpStringLiteral; 273 Tokens.erase(Tokens.end() - 2); 274 Tokens.erase(Tokens.end() - 1); 275 return true; 276 } 277 } 278 279 // Convert back into just a string_literal. 280 At->Tok.setKind(tok::string_literal); 281 At->TokenText = StringRef(At->TokenText.begin(), 282 String->TokenText.end() - At->TokenText.begin()); 283 At->ColumnWidth += String->ColumnWidth; 284 At->Type = TT_CSharpStringLiteral; 285 Tokens.erase(Tokens.end() - 1); 286 return true; 287 } 288 289 bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() { 290 if (Tokens.size() < 2) 291 return false; 292 auto &FirstQuestion = *(Tokens.end() - 2); 293 auto &SecondQuestion = *(Tokens.end() - 1); 294 if (!FirstQuestion->is(tok::question) || !SecondQuestion->is(tok::question)) 295 return false; 296 FirstQuestion->Tok.setKind(tok::question); 297 FirstQuestion->TokenText = StringRef(FirstQuestion->TokenText.begin(), 298 SecondQuestion->TokenText.end() - 299 FirstQuestion->TokenText.begin()); 300 FirstQuestion->ColumnWidth += SecondQuestion->ColumnWidth; 301 FirstQuestion->Type = TT_CSharpNullCoalescing; 302 Tokens.erase(Tokens.end() - 1); 303 return true; 304 } 305 306 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() { 307 if (Tokens.size() < 2) 308 return false; 309 auto &At = *(Tokens.end() - 2); 310 auto &Keyword = *(Tokens.end() - 1); 311 if (!At->is(tok::at)) 312 return false; 313 if (!Keywords.isCSharpKeyword(*Keyword)) 314 return false; 315 316 At->Tok.setKind(tok::identifier); 317 At->TokenText = StringRef(At->TokenText.begin(), 318 Keyword->TokenText.end() - At->TokenText.begin()); 319 At->ColumnWidth += Keyword->ColumnWidth; 320 At->Type = Keyword->Type; 321 Tokens.erase(Tokens.end() - 1); 322 return true; 323 } 324 325 // In C# merge the Identifier and the ? together e.g. arg?. 326 bool FormatTokenLexer::tryMergeCSharpNullConditionals() { 327 if (Tokens.size() < 2) 328 return false; 329 auto &Identifier = *(Tokens.end() - 2); 330 auto &Question = *(Tokens.end() - 1); 331 if (!Identifier->isOneOf(tok::r_square, tok::identifier) || 332 !Question->is(tok::question)) 333 return false; 334 Identifier->TokenText = 335 StringRef(Identifier->TokenText.begin(), 336 Question->TokenText.end() - Identifier->TokenText.begin()); 337 Identifier->ColumnWidth += Question->ColumnWidth; 338 Tokens.erase(Tokens.end() - 1); 339 return true; 340 } 341 342 // In C# transform identifier foreach into kw_foreach 343 bool FormatTokenLexer::tryTransformCSharpForEach() { 344 if (Tokens.size() < 1) 345 return false; 346 auto &Identifier = *(Tokens.end() - 1); 347 if (!Identifier->is(tok::identifier)) 348 return false; 349 if (Identifier->TokenText != "foreach") 350 return false; 351 352 Identifier->Type = TT_ForEachMacro; 353 Identifier->Tok.setKind(tok::kw_for); 354 return true; 355 } 356 357 bool FormatTokenLexer::tryMergeLessLess() { 358 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less. 359 if (Tokens.size() < 3) 360 return false; 361 362 bool FourthTokenIsLess = false; 363 if (Tokens.size() > 3) 364 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less); 365 366 auto First = Tokens.end() - 3; 367 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) || 368 First[0]->isNot(tok::less) || FourthTokenIsLess) 369 return false; 370 371 // Only merge if there currently is no whitespace between the two "<". 372 if (First[1]->WhitespaceRange.getBegin() != 373 First[1]->WhitespaceRange.getEnd()) 374 return false; 375 376 First[0]->Tok.setKind(tok::lessless); 377 First[0]->TokenText = "<<"; 378 First[0]->ColumnWidth += 1; 379 Tokens.erase(Tokens.end() - 2); 380 return true; 381 } 382 383 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, 384 TokenType NewType) { 385 if (Tokens.size() < Kinds.size()) 386 return false; 387 388 SmallVectorImpl<FormatToken *>::const_iterator First = 389 Tokens.end() - Kinds.size(); 390 if (!First[0]->is(Kinds[0])) 391 return false; 392 unsigned AddLength = 0; 393 for (unsigned i = 1; i < Kinds.size(); ++i) { 394 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() != 395 First[i]->WhitespaceRange.getEnd()) 396 return false; 397 AddLength += First[i]->TokenText.size(); 398 } 399 Tokens.resize(Tokens.size() - Kinds.size() + 1); 400 First[0]->TokenText = StringRef(First[0]->TokenText.data(), 401 First[0]->TokenText.size() + AddLength); 402 First[0]->ColumnWidth += AddLength; 403 First[0]->Type = NewType; 404 return true; 405 } 406 407 // Returns \c true if \p Tok can only be followed by an operand in JavaScript. 408 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) { 409 // NB: This is not entirely correct, as an r_paren can introduce an operand 410 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough 411 // corner case to not matter in practice, though. 412 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace, 413 tok::r_brace, tok::l_square, tok::semi, tok::exclaim, 414 tok::colon, tok::question, tok::tilde) || 415 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw, 416 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void, 417 tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) || 418 Tok->isBinaryOperator(); 419 } 420 421 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) { 422 if (!Prev) 423 return true; 424 425 // Regex literals can only follow after prefix unary operators, not after 426 // postfix unary operators. If the '++' is followed by a non-operand 427 // introducing token, the slash here is the operand and not the start of a 428 // regex. 429 // `!` is an unary prefix operator, but also a post-fix operator that casts 430 // away nullability, so the same check applies. 431 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim)) 432 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3])); 433 434 // The previous token must introduce an operand location where regex 435 // literals can occur. 436 if (!precedesOperand(Prev)) 437 return false; 438 439 return true; 440 } 441 442 // Tries to parse a JavaScript Regex literal starting at the current token, 443 // if that begins with a slash and is in a location where JavaScript allows 444 // regex literals. Changes the current token to a regex literal and updates 445 // its text if successful. 446 void FormatTokenLexer::tryParseJSRegexLiteral() { 447 FormatToken *RegexToken = Tokens.back(); 448 if (!RegexToken->isOneOf(tok::slash, tok::slashequal)) 449 return; 450 451 FormatToken *Prev = nullptr; 452 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) { 453 // NB: Because previous pointers are not initialized yet, this cannot use 454 // Token.getPreviousNonComment. 455 if ((*I)->isNot(tok::comment)) { 456 Prev = *I; 457 break; 458 } 459 } 460 461 if (!canPrecedeRegexLiteral(Prev)) 462 return; 463 464 // 'Manually' lex ahead in the current file buffer. 465 const char *Offset = Lex->getBufferLocation(); 466 const char *RegexBegin = Offset - RegexToken->TokenText.size(); 467 StringRef Buffer = Lex->getBuffer(); 468 bool InCharacterClass = false; 469 bool HaveClosingSlash = false; 470 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) { 471 // Regular expressions are terminated with a '/', which can only be 472 // escaped using '\' or a character class between '[' and ']'. 473 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5. 474 switch (*Offset) { 475 case '\\': 476 // Skip the escaped character. 477 ++Offset; 478 break; 479 case '[': 480 InCharacterClass = true; 481 break; 482 case ']': 483 InCharacterClass = false; 484 break; 485 case '/': 486 if (!InCharacterClass) 487 HaveClosingSlash = true; 488 break; 489 } 490 } 491 492 RegexToken->Type = TT_RegexLiteral; 493 // Treat regex literals like other string_literals. 494 RegexToken->Tok.setKind(tok::string_literal); 495 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin); 496 RegexToken->ColumnWidth = RegexToken->TokenText.size(); 497 498 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); 499 } 500 501 void FormatTokenLexer::handleTemplateStrings() { 502 FormatToken *BacktickToken = Tokens.back(); 503 504 if (BacktickToken->is(tok::l_brace)) { 505 StateStack.push(LexerState::NORMAL); 506 return; 507 } 508 if (BacktickToken->is(tok::r_brace)) { 509 if (StateStack.size() == 1) 510 return; 511 StateStack.pop(); 512 if (StateStack.top() != LexerState::TEMPLATE_STRING) 513 return; 514 // If back in TEMPLATE_STRING, fallthrough and continue parsing the 515 } else if (BacktickToken->is(tok::unknown) && 516 BacktickToken->TokenText == "`") { 517 StateStack.push(LexerState::TEMPLATE_STRING); 518 } else { 519 return; // Not actually a template 520 } 521 522 // 'Manually' lex ahead in the current file buffer. 523 const char *Offset = Lex->getBufferLocation(); 524 const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`" 525 for (; Offset != Lex->getBuffer().end(); ++Offset) { 526 if (Offset[0] == '`') { 527 StateStack.pop(); 528 break; 529 } 530 if (Offset[0] == '\\') { 531 ++Offset; // Skip the escaped character. 532 } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' && 533 Offset[1] == '{') { 534 // '${' introduces an expression interpolation in the template string. 535 StateStack.push(LexerState::NORMAL); 536 ++Offset; 537 break; 538 } 539 } 540 541 StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1); 542 BacktickToken->Type = TT_TemplateString; 543 BacktickToken->Tok.setKind(tok::string_literal); 544 BacktickToken->TokenText = LiteralText; 545 546 // Adjust width for potentially multiline string literals. 547 size_t FirstBreak = LiteralText.find('\n'); 548 StringRef FirstLineText = FirstBreak == StringRef::npos 549 ? LiteralText 550 : LiteralText.substr(0, FirstBreak); 551 BacktickToken->ColumnWidth = encoding::columnWidthWithTabs( 552 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding); 553 size_t LastBreak = LiteralText.rfind('\n'); 554 if (LastBreak != StringRef::npos) { 555 BacktickToken->IsMultiline = true; 556 unsigned StartColumn = 0; // The template tail spans the entire line. 557 BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs( 558 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn, 559 Style.TabWidth, Encoding); 560 } 561 562 SourceLocation loc = Offset < Lex->getBuffer().end() 563 ? Lex->getSourceLocation(Offset + 1) 564 : SourceMgr.getLocForEndOfFile(ID); 565 resetLexer(SourceMgr.getFileOffset(loc)); 566 } 567 568 void FormatTokenLexer::tryParsePythonComment() { 569 FormatToken *HashToken = Tokens.back(); 570 if (!HashToken->isOneOf(tok::hash, tok::hashhash)) 571 return; 572 // Turn the remainder of this line into a comment. 573 const char *CommentBegin = 574 Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#" 575 size_t From = CommentBegin - Lex->getBuffer().begin(); 576 size_t To = Lex->getBuffer().find_first_of('\n', From); 577 if (To == StringRef::npos) 578 To = Lex->getBuffer().size(); 579 size_t Len = To - From; 580 HashToken->Type = TT_LineComment; 581 HashToken->Tok.setKind(tok::comment); 582 HashToken->TokenText = Lex->getBuffer().substr(From, Len); 583 SourceLocation Loc = To < Lex->getBuffer().size() 584 ? Lex->getSourceLocation(CommentBegin + Len) 585 : SourceMgr.getLocForEndOfFile(ID); 586 resetLexer(SourceMgr.getFileOffset(Loc)); 587 } 588 589 bool FormatTokenLexer::tryMerge_TMacro() { 590 if (Tokens.size() < 4) 591 return false; 592 FormatToken *Last = Tokens.back(); 593 if (!Last->is(tok::r_paren)) 594 return false; 595 596 FormatToken *String = Tokens[Tokens.size() - 2]; 597 if (!String->is(tok::string_literal) || String->IsMultiline) 598 return false; 599 600 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) 601 return false; 602 603 FormatToken *Macro = Tokens[Tokens.size() - 4]; 604 if (Macro->TokenText != "_T") 605 return false; 606 607 const char *Start = Macro->TokenText.data(); 608 const char *End = Last->TokenText.data() + Last->TokenText.size(); 609 String->TokenText = StringRef(Start, End - Start); 610 String->IsFirst = Macro->IsFirst; 611 String->LastNewlineOffset = Macro->LastNewlineOffset; 612 String->WhitespaceRange = Macro->WhitespaceRange; 613 String->OriginalColumn = Macro->OriginalColumn; 614 String->ColumnWidth = encoding::columnWidthWithTabs( 615 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); 616 String->NewlinesBefore = Macro->NewlinesBefore; 617 String->HasUnescapedNewline = Macro->HasUnescapedNewline; 618 619 Tokens.pop_back(); 620 Tokens.pop_back(); 621 Tokens.pop_back(); 622 Tokens.back() = String; 623 return true; 624 } 625 626 bool FormatTokenLexer::tryMergeConflictMarkers() { 627 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof)) 628 return false; 629 630 // Conflict lines look like: 631 // <marker> <text from the vcs> 632 // For example: 633 // >>>>>>> /file/in/file/system at revision 1234 634 // 635 // We merge all tokens in a line that starts with a conflict marker 636 // into a single token with a special token type that the unwrapped line 637 // parser will use to correctly rebuild the underlying code. 638 639 FileID ID; 640 // Get the position of the first token in the line. 641 unsigned FirstInLineOffset; 642 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc( 643 Tokens[FirstInLineIndex]->getStartOfNonWhitespace()); 644 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer(); 645 // Calculate the offset of the start of the current line. 646 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset); 647 if (LineOffset == StringRef::npos) { 648 LineOffset = 0; 649 } else { 650 ++LineOffset; 651 } 652 653 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset); 654 StringRef LineStart; 655 if (FirstSpace == StringRef::npos) { 656 LineStart = Buffer.substr(LineOffset); 657 } else { 658 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset); 659 } 660 661 TokenType Type = TT_Unknown; 662 if (LineStart == "<<<<<<<" || LineStart == ">>>>") { 663 Type = TT_ConflictStart; 664 } else if (LineStart == "|||||||" || LineStart == "=======" || 665 LineStart == "====") { 666 Type = TT_ConflictAlternative; 667 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") { 668 Type = TT_ConflictEnd; 669 } 670 671 if (Type != TT_Unknown) { 672 FormatToken *Next = Tokens.back(); 673 674 Tokens.resize(FirstInLineIndex + 1); 675 // We do not need to build a complete token here, as we will skip it 676 // during parsing anyway (as we must not touch whitespace around conflict 677 // markers). 678 Tokens.back()->Type = Type; 679 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype); 680 681 Tokens.push_back(Next); 682 return true; 683 } 684 685 return false; 686 } 687 688 FormatToken *FormatTokenLexer::getStashedToken() { 689 // Create a synthesized second '>' or '<' token. 690 Token Tok = FormatTok->Tok; 691 StringRef TokenText = FormatTok->TokenText; 692 693 unsigned OriginalColumn = FormatTok->OriginalColumn; 694 FormatTok = new (Allocator.Allocate()) FormatToken; 695 FormatTok->Tok = Tok; 696 SourceLocation TokLocation = 697 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1); 698 FormatTok->Tok.setLocation(TokLocation); 699 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation); 700 FormatTok->TokenText = TokenText; 701 FormatTok->ColumnWidth = 1; 702 FormatTok->OriginalColumn = OriginalColumn + 1; 703 704 return FormatTok; 705 } 706 707 FormatToken *FormatTokenLexer::getNextToken() { 708 if (StateStack.top() == LexerState::TOKEN_STASHED) { 709 StateStack.pop(); 710 return getStashedToken(); 711 } 712 713 FormatTok = new (Allocator.Allocate()) FormatToken; 714 readRawToken(*FormatTok); 715 SourceLocation WhitespaceStart = 716 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); 717 FormatTok->IsFirst = IsFirstToken; 718 IsFirstToken = false; 719 720 // Consume and record whitespace until we find a significant token. 721 unsigned WhitespaceLength = TrailingWhitespace; 722 while (FormatTok->Tok.is(tok::unknown)) { 723 StringRef Text = FormatTok->TokenText; 724 auto EscapesNewline = [&](int pos) { 725 // A '\r' here is just part of '\r\n'. Skip it. 726 if (pos >= 0 && Text[pos] == '\r') 727 --pos; 728 // See whether there is an odd number of '\' before this. 729 // FIXME: This is wrong. A '\' followed by a newline is always removed, 730 // regardless of whether there is another '\' before it. 731 // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph. 732 unsigned count = 0; 733 for (; pos >= 0; --pos, ++count) 734 if (Text[pos] != '\\') 735 break; 736 return count & 1; 737 }; 738 // FIXME: This miscounts tok:unknown tokens that are not just 739 // whitespace, e.g. a '`' character. 740 for (int i = 0, e = Text.size(); i != e; ++i) { 741 switch (Text[i]) { 742 case '\n': 743 ++FormatTok->NewlinesBefore; 744 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1); 745 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 746 Column = 0; 747 break; 748 case '\r': 749 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 750 Column = 0; 751 break; 752 case '\f': 753 case '\v': 754 Column = 0; 755 break; 756 case ' ': 757 ++Column; 758 break; 759 case '\t': 760 Column += 761 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0); 762 break; 763 case '\\': 764 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n')) 765 FormatTok->Type = TT_ImplicitStringLiteral; 766 break; 767 default: 768 FormatTok->Type = TT_ImplicitStringLiteral; 769 break; 770 } 771 if (FormatTok->Type == TT_ImplicitStringLiteral) 772 break; 773 } 774 775 if (FormatTok->is(TT_ImplicitStringLiteral)) 776 break; 777 WhitespaceLength += FormatTok->Tok.getLength(); 778 779 readRawToken(*FormatTok); 780 } 781 782 // JavaScript and Java do not allow to escape the end of the line with a 783 // backslash. Backslashes are syntax errors in plain source, but can occur in 784 // comments. When a single line comment ends with a \, it'll cause the next 785 // line of code to be lexed as a comment, breaking formatting. The code below 786 // finds comments that contain a backslash followed by a line break, truncates 787 // the comment token at the backslash, and resets the lexer to restart behind 788 // the backslash. 789 if ((Style.Language == FormatStyle::LK_JavaScript || 790 Style.Language == FormatStyle::LK_Java) && 791 FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) { 792 size_t BackslashPos = FormatTok->TokenText.find('\\'); 793 while (BackslashPos != StringRef::npos) { 794 if (BackslashPos + 1 < FormatTok->TokenText.size() && 795 FormatTok->TokenText[BackslashPos + 1] == '\n') { 796 const char *Offset = Lex->getBufferLocation(); 797 Offset -= FormatTok->TokenText.size(); 798 Offset += BackslashPos + 1; 799 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); 800 FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1); 801 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 802 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth, 803 Encoding); 804 break; 805 } 806 BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1); 807 } 808 } 809 810 // In case the token starts with escaped newlines, we want to 811 // take them into account as whitespace - this pattern is quite frequent 812 // in macro definitions. 813 // FIXME: Add a more explicit test. 814 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') { 815 unsigned SkippedWhitespace = 0; 816 if (FormatTok->TokenText.size() > 2 && 817 (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n')) 818 SkippedWhitespace = 3; 819 else if (FormatTok->TokenText[1] == '\n') 820 SkippedWhitespace = 2; 821 else 822 break; 823 824 ++FormatTok->NewlinesBefore; 825 WhitespaceLength += SkippedWhitespace; 826 FormatTok->LastNewlineOffset = SkippedWhitespace; 827 Column = 0; 828 FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace); 829 } 830 831 FormatTok->WhitespaceRange = SourceRange( 832 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); 833 834 FormatTok->OriginalColumn = Column; 835 836 TrailingWhitespace = 0; 837 if (FormatTok->Tok.is(tok::comment)) { 838 // FIXME: Add the trimmed whitespace to Column. 839 StringRef UntrimmedText = FormatTok->TokenText; 840 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); 841 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); 842 } else if (FormatTok->Tok.is(tok::raw_identifier)) { 843 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); 844 FormatTok->Tok.setIdentifierInfo(&Info); 845 FormatTok->Tok.setKind(Info.getTokenID()); 846 if (Style.Language == FormatStyle::LK_Java && 847 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete, 848 tok::kw_operator)) { 849 FormatTok->Tok.setKind(tok::identifier); 850 FormatTok->Tok.setIdentifierInfo(nullptr); 851 } else if (Style.Language == FormatStyle::LK_JavaScript && 852 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, 853 tok::kw_operator)) { 854 FormatTok->Tok.setKind(tok::identifier); 855 FormatTok->Tok.setIdentifierInfo(nullptr); 856 } 857 } else if (FormatTok->Tok.is(tok::greatergreater)) { 858 FormatTok->Tok.setKind(tok::greater); 859 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 860 ++Column; 861 StateStack.push(LexerState::TOKEN_STASHED); 862 } else if (FormatTok->Tok.is(tok::lessless)) { 863 FormatTok->Tok.setKind(tok::less); 864 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 865 ++Column; 866 StateStack.push(LexerState::TOKEN_STASHED); 867 } 868 869 // Now FormatTok is the next non-whitespace token. 870 871 StringRef Text = FormatTok->TokenText; 872 size_t FirstNewlinePos = Text.find('\n'); 873 if (FirstNewlinePos == StringRef::npos) { 874 // FIXME: ColumnWidth actually depends on the start column, we need to 875 // take this into account when the token is moved. 876 FormatTok->ColumnWidth = 877 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); 878 Column += FormatTok->ColumnWidth; 879 } else { 880 FormatTok->IsMultiline = true; 881 // FIXME: ColumnWidth actually depends on the start column, we need to 882 // take this into account when the token is moved. 883 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 884 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); 885 886 // The last line of the token always starts in column 0. 887 // Thus, the length can be precomputed even in the presence of tabs. 888 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( 889 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding); 890 Column = FormatTok->LastLineColumnWidth; 891 } 892 893 if (Style.isCpp()) { 894 auto it = Macros.find(FormatTok->Tok.getIdentifierInfo()); 895 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() && 896 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() == 897 tok::pp_define) && 898 it != Macros.end()) { 899 FormatTok->Type = it->second; 900 } else if (FormatTok->is(tok::identifier)) { 901 if (MacroBlockBeginRegex.match(Text)) { 902 FormatTok->Type = TT_MacroBlockBegin; 903 } else if (MacroBlockEndRegex.match(Text)) { 904 FormatTok->Type = TT_MacroBlockEnd; 905 } 906 } 907 } 908 909 return FormatTok; 910 } 911 912 void FormatTokenLexer::readRawToken(FormatToken &Tok) { 913 Lex->LexFromRawLexer(Tok.Tok); 914 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), 915 Tok.Tok.getLength()); 916 // For formatting, treat unterminated string literals like normal string 917 // literals. 918 if (Tok.is(tok::unknown)) { 919 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') { 920 Tok.Tok.setKind(tok::string_literal); 921 Tok.IsUnterminatedLiteral = true; 922 } else if (Style.Language == FormatStyle::LK_JavaScript && 923 Tok.TokenText == "''") { 924 Tok.Tok.setKind(tok::string_literal); 925 } 926 } 927 928 if ((Style.Language == FormatStyle::LK_JavaScript || 929 Style.Language == FormatStyle::LK_Proto || 930 Style.Language == FormatStyle::LK_TextProto) && 931 Tok.is(tok::char_constant)) { 932 Tok.Tok.setKind(tok::string_literal); 933 } 934 935 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" || 936 Tok.TokenText == "/* clang-format on */")) { 937 FormattingDisabled = false; 938 } 939 940 Tok.Finalized = FormattingDisabled; 941 942 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" || 943 Tok.TokenText == "/* clang-format off */")) { 944 FormattingDisabled = true; 945 } 946 } 947 948 void FormatTokenLexer::resetLexer(unsigned Offset) { 949 StringRef Buffer = SourceMgr.getBufferData(ID); 950 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), 951 getFormattingLangOpts(Style), Buffer.begin(), 952 Buffer.begin() + Offset, Buffer.end())); 953 Lex->SetKeepWhitespaceMode(true); 954 TrailingWhitespace = 0; 955 } 956 957 } // namespace format 958 } // namespace clang 959