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