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