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 bool FourthTokenIsLess = false; 433 if (Tokens.size() > 3) 434 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less); 435 436 auto First = Tokens.end() - 3; 437 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) || 438 First[0]->isNot(tok::less) || FourthTokenIsLess) 439 return false; 440 441 // Only merge if there currently is no whitespace between the two "<". 442 if (First[1]->WhitespaceRange.getBegin() != 443 First[1]->WhitespaceRange.getEnd()) 444 return false; 445 446 First[0]->Tok.setKind(tok::lessless); 447 First[0]->TokenText = "<<"; 448 First[0]->ColumnWidth += 1; 449 Tokens.erase(Tokens.end() - 2); 450 return true; 451 } 452 453 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, 454 TokenType NewType) { 455 if (Tokens.size() < Kinds.size()) 456 return false; 457 458 SmallVectorImpl<FormatToken *>::const_iterator First = 459 Tokens.end() - Kinds.size(); 460 if (!First[0]->is(Kinds[0])) 461 return false; 462 unsigned AddLength = 0; 463 for (unsigned i = 1; i < Kinds.size(); ++i) { 464 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() != 465 First[i]->WhitespaceRange.getEnd()) 466 return false; 467 AddLength += First[i]->TokenText.size(); 468 } 469 Tokens.resize(Tokens.size() - Kinds.size() + 1); 470 First[0]->TokenText = StringRef(First[0]->TokenText.data(), 471 First[0]->TokenText.size() + AddLength); 472 First[0]->ColumnWidth += AddLength; 473 First[0]->setType(NewType); 474 return true; 475 } 476 477 // Returns \c true if \p Tok can only be followed by an operand in JavaScript. 478 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) { 479 // NB: This is not entirely correct, as an r_paren can introduce an operand 480 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough 481 // corner case to not matter in practice, though. 482 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace, 483 tok::r_brace, tok::l_square, tok::semi, tok::exclaim, 484 tok::colon, tok::question, tok::tilde) || 485 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw, 486 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void, 487 tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) || 488 Tok->isBinaryOperator(); 489 } 490 491 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) { 492 if (!Prev) 493 return true; 494 495 // Regex literals can only follow after prefix unary operators, not after 496 // postfix unary operators. If the '++' is followed by a non-operand 497 // introducing token, the slash here is the operand and not the start of a 498 // regex. 499 // `!` is an unary prefix operator, but also a post-fix operator that casts 500 // away nullability, so the same check applies. 501 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim)) 502 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3])); 503 504 // The previous token must introduce an operand location where regex 505 // literals can occur. 506 if (!precedesOperand(Prev)) 507 return false; 508 509 return true; 510 } 511 512 // Tries to parse a JavaScript Regex literal starting at the current token, 513 // if that begins with a slash and is in a location where JavaScript allows 514 // regex literals. Changes the current token to a regex literal and updates 515 // its text if successful. 516 void FormatTokenLexer::tryParseJSRegexLiteral() { 517 FormatToken *RegexToken = Tokens.back(); 518 if (!RegexToken->isOneOf(tok::slash, tok::slashequal)) 519 return; 520 521 FormatToken *Prev = nullptr; 522 for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) { 523 // NB: Because previous pointers are not initialized yet, this cannot use 524 // Token.getPreviousNonComment. 525 if (FT->isNot(tok::comment)) { 526 Prev = FT; 527 break; 528 } 529 } 530 531 if (!canPrecedeRegexLiteral(Prev)) 532 return; 533 534 // 'Manually' lex ahead in the current file buffer. 535 const char *Offset = Lex->getBufferLocation(); 536 const char *RegexBegin = Offset - RegexToken->TokenText.size(); 537 StringRef Buffer = Lex->getBuffer(); 538 bool InCharacterClass = false; 539 bool HaveClosingSlash = false; 540 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) { 541 // Regular expressions are terminated with a '/', which can only be 542 // escaped using '\' or a character class between '[' and ']'. 543 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5. 544 switch (*Offset) { 545 case '\\': 546 // Skip the escaped character. 547 ++Offset; 548 break; 549 case '[': 550 InCharacterClass = true; 551 break; 552 case ']': 553 InCharacterClass = false; 554 break; 555 case '/': 556 if (!InCharacterClass) 557 HaveClosingSlash = true; 558 break; 559 } 560 } 561 562 RegexToken->setType(TT_RegexLiteral); 563 // Treat regex literals like other string_literals. 564 RegexToken->Tok.setKind(tok::string_literal); 565 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin); 566 RegexToken->ColumnWidth = RegexToken->TokenText.size(); 567 568 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); 569 } 570 571 void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() { 572 FormatToken *CSharpStringLiteral = Tokens.back(); 573 574 if (CSharpStringLiteral->getType() != TT_CSharpStringLiteral) 575 return; 576 577 // Deal with multiline strings. 578 if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") || 579 CSharpStringLiteral->TokenText.startswith(R"($@")"))) 580 return; 581 582 const char *StrBegin = 583 Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size(); 584 const char *Offset = StrBegin; 585 if (CSharpStringLiteral->TokenText.startswith(R"(@")")) 586 Offset += 2; 587 else // CSharpStringLiteral->TokenText.startswith(R"($@")") 588 Offset += 3; 589 590 // Look for a terminating '"' in the current file buffer. 591 // Make no effort to format code within an interpolated or verbatim string. 592 for (; Offset != Lex->getBuffer().end(); ++Offset) { 593 if (Offset[0] == '"') { 594 // "" within a verbatim string is an escaped double quote: skip it. 595 if (Offset + 1 < Lex->getBuffer().end() && Offset[1] == '"') 596 ++Offset; 597 else 598 break; 599 } 600 } 601 602 // Make no attempt to format code properly if a verbatim string is 603 // unterminated. 604 if (Offset == Lex->getBuffer().end()) 605 return; 606 607 StringRef LiteralText(StrBegin, Offset - StrBegin + 1); 608 CSharpStringLiteral->TokenText = LiteralText; 609 610 // Adjust width for potentially multiline string literals. 611 size_t FirstBreak = LiteralText.find('\n'); 612 StringRef FirstLineText = FirstBreak == StringRef::npos 613 ? LiteralText 614 : LiteralText.substr(0, FirstBreak); 615 CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs( 616 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth, 617 Encoding); 618 size_t LastBreak = LiteralText.rfind('\n'); 619 if (LastBreak != StringRef::npos) { 620 CSharpStringLiteral->IsMultiline = true; 621 unsigned StartColumn = 0; 622 CSharpStringLiteral->LastLineColumnWidth = encoding::columnWidthWithTabs( 623 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn, 624 Style.TabWidth, Encoding); 625 } 626 627 SourceLocation loc = Offset < Lex->getBuffer().end() 628 ? Lex->getSourceLocation(Offset + 1) 629 : SourceMgr.getLocForEndOfFile(ID); 630 resetLexer(SourceMgr.getFileOffset(loc)); 631 } 632 633 void FormatTokenLexer::handleTemplateStrings() { 634 FormatToken *BacktickToken = Tokens.back(); 635 636 if (BacktickToken->is(tok::l_brace)) { 637 StateStack.push(LexerState::NORMAL); 638 return; 639 } 640 if (BacktickToken->is(tok::r_brace)) { 641 if (StateStack.size() == 1) 642 return; 643 StateStack.pop(); 644 if (StateStack.top() != LexerState::TEMPLATE_STRING) 645 return; 646 // If back in TEMPLATE_STRING, fallthrough and continue parsing the 647 } else if (BacktickToken->is(tok::unknown) && 648 BacktickToken->TokenText == "`") { 649 StateStack.push(LexerState::TEMPLATE_STRING); 650 } else { 651 return; // Not actually a template 652 } 653 654 // 'Manually' lex ahead in the current file buffer. 655 const char *Offset = Lex->getBufferLocation(); 656 const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`" 657 for (; Offset != Lex->getBuffer().end(); ++Offset) { 658 if (Offset[0] == '`') { 659 StateStack.pop(); 660 break; 661 } 662 if (Offset[0] == '\\') { 663 ++Offset; // Skip the escaped character. 664 } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' && 665 Offset[1] == '{') { 666 // '${' introduces an expression interpolation in the template string. 667 StateStack.push(LexerState::NORMAL); 668 ++Offset; 669 break; 670 } 671 } 672 673 StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1); 674 BacktickToken->setType(TT_TemplateString); 675 BacktickToken->Tok.setKind(tok::string_literal); 676 BacktickToken->TokenText = LiteralText; 677 678 // Adjust width for potentially multiline string literals. 679 size_t FirstBreak = LiteralText.find('\n'); 680 StringRef FirstLineText = FirstBreak == StringRef::npos 681 ? LiteralText 682 : LiteralText.substr(0, FirstBreak); 683 BacktickToken->ColumnWidth = encoding::columnWidthWithTabs( 684 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding); 685 size_t LastBreak = LiteralText.rfind('\n'); 686 if (LastBreak != StringRef::npos) { 687 BacktickToken->IsMultiline = true; 688 unsigned StartColumn = 0; // The template tail spans the entire line. 689 BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs( 690 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn, 691 Style.TabWidth, Encoding); 692 } 693 694 SourceLocation loc = Offset < Lex->getBuffer().end() 695 ? Lex->getSourceLocation(Offset + 1) 696 : SourceMgr.getLocForEndOfFile(ID); 697 resetLexer(SourceMgr.getFileOffset(loc)); 698 } 699 700 void FormatTokenLexer::tryParsePythonComment() { 701 FormatToken *HashToken = Tokens.back(); 702 if (!HashToken->isOneOf(tok::hash, tok::hashhash)) 703 return; 704 // Turn the remainder of this line into a comment. 705 const char *CommentBegin = 706 Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#" 707 size_t From = CommentBegin - Lex->getBuffer().begin(); 708 size_t To = Lex->getBuffer().find_first_of('\n', From); 709 if (To == StringRef::npos) 710 To = Lex->getBuffer().size(); 711 size_t Len = To - From; 712 HashToken->setType(TT_LineComment); 713 HashToken->Tok.setKind(tok::comment); 714 HashToken->TokenText = Lex->getBuffer().substr(From, Len); 715 SourceLocation Loc = To < Lex->getBuffer().size() 716 ? Lex->getSourceLocation(CommentBegin + Len) 717 : SourceMgr.getLocForEndOfFile(ID); 718 resetLexer(SourceMgr.getFileOffset(Loc)); 719 } 720 721 bool FormatTokenLexer::tryMerge_TMacro() { 722 if (Tokens.size() < 4) 723 return false; 724 FormatToken *Last = Tokens.back(); 725 if (!Last->is(tok::r_paren)) 726 return false; 727 728 FormatToken *String = Tokens[Tokens.size() - 2]; 729 if (!String->is(tok::string_literal) || String->IsMultiline) 730 return false; 731 732 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) 733 return false; 734 735 FormatToken *Macro = Tokens[Tokens.size() - 4]; 736 if (Macro->TokenText != "_T") 737 return false; 738 739 const char *Start = Macro->TokenText.data(); 740 const char *End = Last->TokenText.data() + Last->TokenText.size(); 741 String->TokenText = StringRef(Start, End - Start); 742 String->IsFirst = Macro->IsFirst; 743 String->LastNewlineOffset = Macro->LastNewlineOffset; 744 String->WhitespaceRange = Macro->WhitespaceRange; 745 String->OriginalColumn = Macro->OriginalColumn; 746 String->ColumnWidth = encoding::columnWidthWithTabs( 747 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); 748 String->NewlinesBefore = Macro->NewlinesBefore; 749 String->HasUnescapedNewline = Macro->HasUnescapedNewline; 750 751 Tokens.pop_back(); 752 Tokens.pop_back(); 753 Tokens.pop_back(); 754 Tokens.back() = String; 755 if (FirstInLineIndex >= Tokens.size()) 756 FirstInLineIndex = Tokens.size() - 1; 757 return true; 758 } 759 760 bool FormatTokenLexer::tryMergeConflictMarkers() { 761 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof)) 762 return false; 763 764 // Conflict lines look like: 765 // <marker> <text from the vcs> 766 // For example: 767 // >>>>>>> /file/in/file/system at revision 1234 768 // 769 // We merge all tokens in a line that starts with a conflict marker 770 // into a single token with a special token type that the unwrapped line 771 // parser will use to correctly rebuild the underlying code. 772 773 FileID ID; 774 // Get the position of the first token in the line. 775 unsigned FirstInLineOffset; 776 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc( 777 Tokens[FirstInLineIndex]->getStartOfNonWhitespace()); 778 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer(); 779 // Calculate the offset of the start of the current line. 780 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset); 781 if (LineOffset == StringRef::npos) { 782 LineOffset = 0; 783 } else { 784 ++LineOffset; 785 } 786 787 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset); 788 StringRef LineStart; 789 if (FirstSpace == StringRef::npos) { 790 LineStart = Buffer.substr(LineOffset); 791 } else { 792 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset); 793 } 794 795 TokenType Type = TT_Unknown; 796 if (LineStart == "<<<<<<<" || LineStart == ">>>>") { 797 Type = TT_ConflictStart; 798 } else if (LineStart == "|||||||" || LineStart == "=======" || 799 LineStart == "====") { 800 Type = TT_ConflictAlternative; 801 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") { 802 Type = TT_ConflictEnd; 803 } 804 805 if (Type != TT_Unknown) { 806 FormatToken *Next = Tokens.back(); 807 808 Tokens.resize(FirstInLineIndex + 1); 809 // We do not need to build a complete token here, as we will skip it 810 // during parsing anyway (as we must not touch whitespace around conflict 811 // markers). 812 Tokens.back()->setType(Type); 813 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype); 814 815 Tokens.push_back(Next); 816 return true; 817 } 818 819 return false; 820 } 821 822 FormatToken *FormatTokenLexer::getStashedToken() { 823 // Create a synthesized second '>' or '<' token. 824 Token Tok = FormatTok->Tok; 825 StringRef TokenText = FormatTok->TokenText; 826 827 unsigned OriginalColumn = FormatTok->OriginalColumn; 828 FormatTok = new (Allocator.Allocate()) FormatToken; 829 FormatTok->Tok = Tok; 830 SourceLocation TokLocation = 831 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1); 832 FormatTok->Tok.setLocation(TokLocation); 833 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation); 834 FormatTok->TokenText = TokenText; 835 FormatTok->ColumnWidth = 1; 836 FormatTok->OriginalColumn = OriginalColumn + 1; 837 838 return FormatTok; 839 } 840 841 FormatToken *FormatTokenLexer::getNextToken() { 842 if (StateStack.top() == LexerState::TOKEN_STASHED) { 843 StateStack.pop(); 844 return getStashedToken(); 845 } 846 847 FormatTok = new (Allocator.Allocate()) FormatToken; 848 readRawToken(*FormatTok); 849 SourceLocation WhitespaceStart = 850 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); 851 FormatTok->IsFirst = IsFirstToken; 852 IsFirstToken = false; 853 854 // Consume and record whitespace until we find a significant token. 855 unsigned WhitespaceLength = TrailingWhitespace; 856 while (FormatTok->Tok.is(tok::unknown)) { 857 StringRef Text = FormatTok->TokenText; 858 auto EscapesNewline = [&](int pos) { 859 // A '\r' here is just part of '\r\n'. Skip it. 860 if (pos >= 0 && Text[pos] == '\r') 861 --pos; 862 // See whether there is an odd number of '\' before this. 863 // FIXME: This is wrong. A '\' followed by a newline is always removed, 864 // regardless of whether there is another '\' before it. 865 // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph. 866 unsigned count = 0; 867 for (; pos >= 0; --pos, ++count) 868 if (Text[pos] != '\\') 869 break; 870 return count & 1; 871 }; 872 // FIXME: This miscounts tok:unknown tokens that are not just 873 // whitespace, e.g. a '`' character. 874 for (int i = 0, e = Text.size(); i != e; ++i) { 875 switch (Text[i]) { 876 case '\n': 877 ++FormatTok->NewlinesBefore; 878 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1); 879 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 880 Column = 0; 881 break; 882 case '\r': 883 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 884 Column = 0; 885 break; 886 case '\f': 887 case '\v': 888 Column = 0; 889 break; 890 case ' ': 891 ++Column; 892 break; 893 case '\t': 894 Column += 895 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0); 896 break; 897 case '\\': 898 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n')) 899 FormatTok->setType(TT_ImplicitStringLiteral); 900 break; 901 default: 902 FormatTok->setType(TT_ImplicitStringLiteral); 903 break; 904 } 905 if (FormatTok->getType() == TT_ImplicitStringLiteral) 906 break; 907 } 908 909 if (FormatTok->is(TT_ImplicitStringLiteral)) 910 break; 911 WhitespaceLength += FormatTok->Tok.getLength(); 912 913 readRawToken(*FormatTok); 914 } 915 916 // JavaScript and Java do not allow to escape the end of the line with a 917 // backslash. Backslashes are syntax errors in plain source, but can occur in 918 // comments. When a single line comment ends with a \, it'll cause the next 919 // line of code to be lexed as a comment, breaking formatting. The code below 920 // finds comments that contain a backslash followed by a line break, truncates 921 // the comment token at the backslash, and resets the lexer to restart behind 922 // the backslash. 923 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) && 924 FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) { 925 size_t BackslashPos = FormatTok->TokenText.find('\\'); 926 while (BackslashPos != StringRef::npos) { 927 if (BackslashPos + 1 < FormatTok->TokenText.size() && 928 FormatTok->TokenText[BackslashPos + 1] == '\n') { 929 const char *Offset = Lex->getBufferLocation(); 930 Offset -= FormatTok->TokenText.size(); 931 Offset += BackslashPos + 1; 932 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); 933 FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1); 934 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 935 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth, 936 Encoding); 937 break; 938 } 939 BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1); 940 } 941 } 942 943 // In case the token starts with escaped newlines, we want to 944 // take them into account as whitespace - this pattern is quite frequent 945 // in macro definitions. 946 // FIXME: Add a more explicit test. 947 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') { 948 unsigned SkippedWhitespace = 0; 949 if (FormatTok->TokenText.size() > 2 && 950 (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n')) 951 SkippedWhitespace = 3; 952 else if (FormatTok->TokenText[1] == '\n') 953 SkippedWhitespace = 2; 954 else 955 break; 956 957 ++FormatTok->NewlinesBefore; 958 WhitespaceLength += SkippedWhitespace; 959 FormatTok->LastNewlineOffset = SkippedWhitespace; 960 Column = 0; 961 FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace); 962 } 963 964 FormatTok->WhitespaceRange = SourceRange( 965 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); 966 967 FormatTok->OriginalColumn = Column; 968 969 TrailingWhitespace = 0; 970 if (FormatTok->Tok.is(tok::comment)) { 971 // FIXME: Add the trimmed whitespace to Column. 972 StringRef UntrimmedText = FormatTok->TokenText; 973 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); 974 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); 975 } else if (FormatTok->Tok.is(tok::raw_identifier)) { 976 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); 977 FormatTok->Tok.setIdentifierInfo(&Info); 978 FormatTok->Tok.setKind(Info.getTokenID()); 979 if (Style.Language == FormatStyle::LK_Java && 980 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete, 981 tok::kw_operator)) { 982 FormatTok->Tok.setKind(tok::identifier); 983 FormatTok->Tok.setIdentifierInfo(nullptr); 984 } else if (Style.isJavaScript() && 985 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, 986 tok::kw_operator)) { 987 FormatTok->Tok.setKind(tok::identifier); 988 FormatTok->Tok.setIdentifierInfo(nullptr); 989 } 990 } else if (FormatTok->Tok.is(tok::greatergreater)) { 991 FormatTok->Tok.setKind(tok::greater); 992 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 993 ++Column; 994 StateStack.push(LexerState::TOKEN_STASHED); 995 } else if (FormatTok->Tok.is(tok::lessless)) { 996 FormatTok->Tok.setKind(tok::less); 997 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 998 ++Column; 999 StateStack.push(LexerState::TOKEN_STASHED); 1000 } 1001 1002 // Now FormatTok is the next non-whitespace token. 1003 1004 StringRef Text = FormatTok->TokenText; 1005 size_t FirstNewlinePos = Text.find('\n'); 1006 if (FirstNewlinePos == StringRef::npos) { 1007 // FIXME: ColumnWidth actually depends on the start column, we need to 1008 // take this into account when the token is moved. 1009 FormatTok->ColumnWidth = 1010 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); 1011 Column += FormatTok->ColumnWidth; 1012 } else { 1013 FormatTok->IsMultiline = true; 1014 // FIXME: ColumnWidth actually depends on the start column, we need to 1015 // take this into account when the token is moved. 1016 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 1017 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); 1018 1019 // The last line of the token always starts in column 0. 1020 // Thus, the length can be precomputed even in the presence of tabs. 1021 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( 1022 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding); 1023 Column = FormatTok->LastLineColumnWidth; 1024 } 1025 1026 if (Style.isCpp()) { 1027 auto it = Macros.find(FormatTok->Tok.getIdentifierInfo()); 1028 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() && 1029 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() == 1030 tok::pp_define) && 1031 it != Macros.end()) { 1032 FormatTok->setType(it->second); 1033 if (it->second == TT_IfMacro) { 1034 // The lexer token currently has type tok::kw_unknown. However, for this 1035 // substitution to be treated correctly in the TokenAnnotator, faking 1036 // the tok value seems to be needed. Not sure if there's a more elegant 1037 // way. 1038 FormatTok->Tok.setKind(tok::kw_if); 1039 } 1040 } else if (FormatTok->is(tok::identifier)) { 1041 if (MacroBlockBeginRegex.match(Text)) { 1042 FormatTok->setType(TT_MacroBlockBegin); 1043 } else if (MacroBlockEndRegex.match(Text)) { 1044 FormatTok->setType(TT_MacroBlockEnd); 1045 } 1046 } 1047 } 1048 1049 return FormatTok; 1050 } 1051 1052 void FormatTokenLexer::readRawToken(FormatToken &Tok) { 1053 Lex->LexFromRawLexer(Tok.Tok); 1054 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), 1055 Tok.Tok.getLength()); 1056 // For formatting, treat unterminated string literals like normal string 1057 // literals. 1058 if (Tok.is(tok::unknown)) { 1059 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') { 1060 Tok.Tok.setKind(tok::string_literal); 1061 Tok.IsUnterminatedLiteral = true; 1062 } else if (Style.isJavaScript() && Tok.TokenText == "''") { 1063 Tok.Tok.setKind(tok::string_literal); 1064 } 1065 } 1066 1067 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto || 1068 Style.Language == FormatStyle::LK_TextProto) && 1069 Tok.is(tok::char_constant)) { 1070 Tok.Tok.setKind(tok::string_literal); 1071 } 1072 1073 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" || 1074 Tok.TokenText == "/* clang-format on */")) { 1075 FormattingDisabled = false; 1076 } 1077 1078 Tok.Finalized = FormattingDisabled; 1079 1080 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" || 1081 Tok.TokenText == "/* clang-format off */")) { 1082 FormattingDisabled = true; 1083 } 1084 } 1085 1086 void FormatTokenLexer::resetLexer(unsigned Offset) { 1087 StringRef Buffer = SourceMgr.getBufferData(ID); 1088 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), 1089 getFormattingLangOpts(Style), Buffer.begin(), 1090 Buffer.begin() + Offset, Buffer.end())); 1091 Lex->SetKeepWhitespaceMode(true); 1092 TrailingWhitespace = 0; 1093 } 1094 1095 } // namespace format 1096 } // namespace clang 1097