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