1 //===--- SourceCode.h - Manipulating source code as strings -----*- 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 #include "SourceCode.h" 9 10 #include "Context.h" 11 #include "FuzzyMatch.h" 12 #include "Logger.h" 13 #include "Protocol.h" 14 #include "refactor/Tweak.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/Basic/LangOptions.h" 17 #include "clang/Basic/SourceLocation.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/TokenKinds.h" 20 #include "clang/Driver/Types.h" 21 #include "clang/Format/Format.h" 22 #include "clang/Lex/Lexer.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Lex/Token.h" 25 #include "clang/Tooling/Core/Replacement.h" 26 #include "clang/Tooling/Syntax/Tokens.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/None.h" 29 #include "llvm/ADT/STLExtras.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/ADT/StringMap.h" 32 #include "llvm/ADT/StringRef.h" 33 #include "llvm/Support/Compiler.h" 34 #include "llvm/Support/Errc.h" 35 #include "llvm/Support/Error.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/LineIterator.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/SHA1.h" 41 #include "llvm/Support/VirtualFileSystem.h" 42 #include "llvm/Support/xxhash.h" 43 #include <algorithm> 44 #include <cstddef> 45 #include <string> 46 #include <vector> 47 48 namespace clang { 49 namespace clangd { 50 51 // Here be dragons. LSP positions use columns measured in *UTF-16 code units*! 52 // Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial. 53 54 // Iterates over unicode codepoints in the (UTF-8) string. For each, 55 // invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true. 56 // Returns true if CB returned true, false if we hit the end of string. 57 template <typename Callback> 58 static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) { 59 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). 60 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx. 61 for (size_t I = 0; I < U8.size();) { 62 unsigned char C = static_cast<unsigned char>(U8[I]); 63 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character. 64 if (CB(1, 1)) 65 return true; 66 ++I; 67 continue; 68 } 69 // This convenient property of UTF-8 holds for all non-ASCII characters. 70 size_t UTF8Length = llvm::countLeadingOnes(C); 71 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here. 72 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug. 73 assert((UTF8Length >= 2 && UTF8Length <= 4) && 74 "Invalid UTF-8, or transcoding bug?"); 75 I += UTF8Length; // Skip over all trailing bytes. 76 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). 77 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...) 78 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1)) 79 return true; 80 } 81 return false; 82 } 83 84 // Returns the byte offset into the string that is an offset of \p Units in 85 // the specified encoding. 86 // Conceptually, this converts to the encoding, truncates to CodeUnits, 87 // converts back to UTF-8, and returns the length in bytes. 88 static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc, 89 bool &Valid) { 90 Valid = Units >= 0; 91 if (Units <= 0) 92 return 0; 93 size_t Result = 0; 94 switch (Enc) { 95 case OffsetEncoding::UTF8: 96 Result = Units; 97 break; 98 case OffsetEncoding::UTF16: 99 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) { 100 Result += U8Len; 101 Units -= U16Len; 102 return Units <= 0; 103 }); 104 if (Units < 0) // Offset in the middle of a surrogate pair. 105 Valid = false; 106 break; 107 case OffsetEncoding::UTF32: 108 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) { 109 Result += U8Len; 110 Units--; 111 return Units <= 0; 112 }); 113 break; 114 case OffsetEncoding::UnsupportedEncoding: 115 llvm_unreachable("unsupported encoding"); 116 } 117 // Don't return an out-of-range index if we overran. 118 if (Result > U8.size()) { 119 Valid = false; 120 return U8.size(); 121 } 122 return Result; 123 } 124 125 Key<OffsetEncoding> kCurrentOffsetEncoding; 126 static OffsetEncoding lspEncoding() { 127 auto *Enc = Context::current().get(kCurrentOffsetEncoding); 128 return Enc ? *Enc : OffsetEncoding::UTF16; 129 } 130 131 // Like most strings in clangd, the input is UTF-8 encoded. 132 size_t lspLength(llvm::StringRef Code) { 133 size_t Count = 0; 134 switch (lspEncoding()) { 135 case OffsetEncoding::UTF8: 136 Count = Code.size(); 137 break; 138 case OffsetEncoding::UTF16: 139 iterateCodepoints(Code, [&](int U8Len, int U16Len) { 140 Count += U16Len; 141 return false; 142 }); 143 break; 144 case OffsetEncoding::UTF32: 145 iterateCodepoints(Code, [&](int U8Len, int U16Len) { 146 ++Count; 147 return false; 148 }); 149 break; 150 case OffsetEncoding::UnsupportedEncoding: 151 llvm_unreachable("unsupported encoding"); 152 } 153 return Count; 154 } 155 156 llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P, 157 bool AllowColumnsBeyondLineLength) { 158 if (P.line < 0) 159 return llvm::make_error<llvm::StringError>( 160 llvm::formatv("Line value can't be negative ({0})", P.line), 161 llvm::errc::invalid_argument); 162 if (P.character < 0) 163 return llvm::make_error<llvm::StringError>( 164 llvm::formatv("Character value can't be negative ({0})", P.character), 165 llvm::errc::invalid_argument); 166 size_t StartOfLine = 0; 167 for (int I = 0; I != P.line; ++I) { 168 size_t NextNL = Code.find('\n', StartOfLine); 169 if (NextNL == llvm::StringRef::npos) 170 return llvm::make_error<llvm::StringError>( 171 llvm::formatv("Line value is out of range ({0})", P.line), 172 llvm::errc::invalid_argument); 173 StartOfLine = NextNL + 1; 174 } 175 StringRef Line = 176 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; }); 177 178 // P.character may be in UTF-16, transcode if necessary. 179 bool Valid; 180 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid); 181 if (!Valid && !AllowColumnsBeyondLineLength) 182 return llvm::make_error<llvm::StringError>( 183 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(), 184 P.character, P.line), 185 llvm::errc::invalid_argument); 186 return StartOfLine + ByteInLine; 187 } 188 189 Position offsetToPosition(llvm::StringRef Code, size_t Offset) { 190 Offset = std::min(Code.size(), Offset); 191 llvm::StringRef Before = Code.substr(0, Offset); 192 int Lines = Before.count('\n'); 193 size_t PrevNL = Before.rfind('\n'); 194 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1); 195 Position Pos; 196 Pos.line = Lines; 197 Pos.character = lspLength(Before.substr(StartOfLine)); 198 return Pos; 199 } 200 201 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) { 202 // We use the SourceManager's line tables, but its column number is in bytes. 203 FileID FID; 204 unsigned Offset; 205 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc); 206 Position P; 207 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1; 208 bool Invalid = false; 209 llvm::StringRef Code = SM.getBufferData(FID, &Invalid); 210 if (!Invalid) { 211 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1; 212 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes); 213 P.character = lspLength(LineSoFar); 214 } 215 return P; 216 } 217 218 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) { 219 if (Loc.isMacroID()) { 220 std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM); 221 if (llvm::StringRef(PrintLoc).startswith("<scratch") || 222 llvm::StringRef(PrintLoc).startswith("<command line>")) 223 return false; 224 } 225 return true; 226 } 227 228 bool isValidFileRange(const SourceManager &Mgr, SourceRange R) { 229 if (!R.getBegin().isValid() || !R.getEnd().isValid()) 230 return false; 231 232 FileID BeginFID; 233 size_t BeginOffset = 0; 234 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin()); 235 236 FileID EndFID; 237 size_t EndOffset = 0; 238 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd()); 239 240 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset; 241 } 242 243 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R, 244 SourceLocation L) { 245 assert(isValidFileRange(Mgr, R)); 246 247 FileID BeginFID; 248 size_t BeginOffset = 0; 249 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin()); 250 size_t EndOffset = Mgr.getFileOffset(R.getEnd()); 251 252 FileID LFid; 253 size_t LOffset; 254 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L); 255 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset; 256 } 257 258 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R, 259 SourceLocation L) { 260 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L); 261 } 262 263 SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) { 264 assert(SM.getLocForEndOfFile(IncludedFile).isFileID()); 265 FileID IncludingFile; 266 unsigned Offset; 267 std::tie(IncludingFile, Offset) = 268 SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile)); 269 bool Invalid = false; 270 llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid); 271 if (Invalid) 272 return SourceLocation(); 273 // Now buf is "...\n#include <foo>\n..." 274 // and Offset points here: ^ 275 // Rewind to the preceding # on the line. 276 assert(Offset < Buf.size()); 277 for (;; --Offset) { 278 if (Buf[Offset] == '#') 279 return SM.getComposedLoc(IncludingFile, Offset); 280 if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on? 281 return SourceLocation(); 282 } 283 } 284 285 static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM, 286 const LangOptions &LangOpts) { 287 Token TheTok; 288 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts)) 289 return 0; 290 // FIXME: Here we check whether the token at the location is a greatergreater 291 // (>>) token and consider it as a single greater (>). This is to get it 292 // working for templates but it isn't correct for the right shift operator. We 293 // can avoid this by using half open char ranges in getFileRange() but getting 294 // token ending is not well supported in macroIDs. 295 if (TheTok.is(tok::greatergreater)) 296 return 1; 297 return TheTok.getLength(); 298 } 299 300 // Returns location of the last character of the token at a given loc 301 static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc, 302 const SourceManager &SM, 303 const LangOptions &LangOpts) { 304 unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts); 305 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0); 306 } 307 308 // Returns location of the starting of the token at a given EndLoc 309 static SourceLocation getLocForTokenBegin(SourceLocation EndLoc, 310 const SourceManager &SM, 311 const LangOptions &LangOpts) { 312 return EndLoc.getLocWithOffset( 313 -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts)); 314 } 315 316 // Converts a char source range to a token range. 317 static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM, 318 const LangOptions &LangOpts) { 319 if (!Range.isTokenRange()) 320 Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts)); 321 return Range.getAsRange(); 322 } 323 // Returns the union of two token ranges. 324 // To find the maximum of the Ends of the ranges, we compare the location of the 325 // last character of the token. 326 static SourceRange unionTokenRange(SourceRange R1, SourceRange R2, 327 const SourceManager &SM, 328 const LangOptions &LangOpts) { 329 SourceLocation Begin = 330 SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin()) 331 ? R1.getBegin() 332 : R2.getBegin(); 333 SourceLocation End = 334 SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts), 335 getLocForTokenEnd(R2.getEnd(), SM, LangOpts)) 336 ? R2.getEnd() 337 : R1.getEnd(); 338 return SourceRange(Begin, End); 339 } 340 341 // Given a range whose endpoints may be in different expansions or files, 342 // tries to find a range within a common file by following up the expansion and 343 // include location in each. 344 static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM, 345 const LangOptions &LangOpts) { 346 // Fast path for most common cases. 347 if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd())) 348 return R; 349 // Record the stack of expansion locations for the beginning, keyed by FileID. 350 llvm::DenseMap<FileID, SourceLocation> BeginExpansions; 351 for (SourceLocation Begin = R.getBegin(); Begin.isValid(); 352 Begin = Begin.isFileID() 353 ? includeHashLoc(SM.getFileID(Begin), SM) 354 : SM.getImmediateExpansionRange(Begin).getBegin()) { 355 BeginExpansions[SM.getFileID(Begin)] = Begin; 356 } 357 // Move up the stack of expansion locations for the end until we find the 358 // location in BeginExpansions with that has the same file id. 359 for (SourceLocation End = R.getEnd(); End.isValid(); 360 End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM) 361 : toTokenRange(SM.getImmediateExpansionRange(End), 362 SM, LangOpts) 363 .getEnd()) { 364 auto It = BeginExpansions.find(SM.getFileID(End)); 365 if (It != BeginExpansions.end()) { 366 if (SM.getFileOffset(It->second) > SM.getFileOffset(End)) 367 return SourceLocation(); 368 return {It->second, End}; 369 } 370 } 371 return SourceRange(); 372 } 373 374 // Find an expansion range (not necessarily immediate) the ends of which are in 375 // the same file id. 376 static SourceRange 377 getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM, 378 const LangOptions &LangOpts) { 379 return rangeInCommonFile( 380 toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM, 381 LangOpts); 382 } 383 384 // Returns the file range for a given Location as a Token Range 385 // This is quite similar to getFileLoc in SourceManager as both use 386 // getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs). 387 // However: 388 // - We want to maintain the full range information as we move from one file to 389 // the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange. 390 // - We want to split '>>' tokens as the lexer parses the '>>' in nested 391 // template instantiations as a '>>' instead of two '>'s. 392 // There is also getExpansionRange but it simply calls 393 // getImmediateExpansionRange on the begin and ends separately which is wrong. 394 static SourceRange getTokenFileRange(SourceLocation Loc, 395 const SourceManager &SM, 396 const LangOptions &LangOpts) { 397 SourceRange FileRange = Loc; 398 while (!FileRange.getBegin().isFileID()) { 399 if (SM.isMacroArgExpansion(FileRange.getBegin())) { 400 FileRange = unionTokenRange( 401 SM.getImmediateSpellingLoc(FileRange.getBegin()), 402 SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts); 403 assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd())); 404 } else { 405 SourceRange ExpansionRangeForBegin = 406 getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts); 407 SourceRange ExpansionRangeForEnd = 408 getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts); 409 if (ExpansionRangeForBegin.isInvalid() || 410 ExpansionRangeForEnd.isInvalid()) 411 return SourceRange(); 412 assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(), 413 ExpansionRangeForEnd.getBegin()) && 414 "Both Expansion ranges should be in same file."); 415 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd, 416 SM, LangOpts); 417 } 418 } 419 return FileRange; 420 } 421 422 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) { 423 if (!Loc.isValid()) 424 return false; 425 FileID FID = SM.getFileID(SM.getExpansionLoc(Loc)); 426 return FID == SM.getMainFileID() || FID == SM.getPreambleFileID(); 427 } 428 429 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM, 430 const LangOptions &LangOpts, 431 SourceRange R) { 432 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts); 433 if (!isValidFileRange(SM, R1)) 434 return llvm::None; 435 436 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts); 437 if (!isValidFileRange(SM, R2)) 438 return llvm::None; 439 440 SourceRange Result = 441 rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts); 442 unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts); 443 // Convert from closed token range to half-open (char) range 444 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen)); 445 if (!isValidFileRange(SM, Result)) 446 return llvm::None; 447 448 return Result; 449 } 450 451 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) { 452 assert(isValidFileRange(SM, R)); 453 bool Invalid = false; 454 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid); 455 assert(!Invalid); 456 457 size_t BeginOffset = SM.getFileOffset(R.getBegin()); 458 size_t EndOffset = SM.getFileOffset(R.getEnd()); 459 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset); 460 } 461 462 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM, 463 Position P) { 464 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer(); 465 auto Offset = 466 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false); 467 if (!Offset) 468 return Offset.takeError(); 469 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset); 470 } 471 472 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) { 473 // Clang is 1-based, LSP uses 0-based indexes. 474 Position Begin = sourceLocToPosition(SM, R.getBegin()); 475 Position End = sourceLocToPosition(SM, R.getEnd()); 476 477 return {Begin, End}; 478 } 479 480 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code, 481 size_t Offset) { 482 Offset = std::min(Code.size(), Offset); 483 llvm::StringRef Before = Code.substr(0, Offset); 484 int Lines = Before.count('\n'); 485 size_t PrevNL = Before.rfind('\n'); 486 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1); 487 return {Lines + 1, Offset - StartOfLine + 1}; 488 } 489 490 std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) { 491 size_t Pos = QName.rfind("::"); 492 if (Pos == llvm::StringRef::npos) 493 return {llvm::StringRef(), QName}; 494 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)}; 495 } 496 497 TextEdit replacementToEdit(llvm::StringRef Code, 498 const tooling::Replacement &R) { 499 Range ReplacementRange = { 500 offsetToPosition(Code, R.getOffset()), 501 offsetToPosition(Code, R.getOffset() + R.getLength())}; 502 return {ReplacementRange, std::string(R.getReplacementText())}; 503 } 504 505 std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code, 506 const tooling::Replacements &Repls) { 507 std::vector<TextEdit> Edits; 508 for (const auto &R : Repls) 509 Edits.push_back(replacementToEdit(Code, R)); 510 return Edits; 511 } 512 513 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F, 514 const SourceManager &SourceMgr) { 515 if (!F) 516 return None; 517 518 llvm::SmallString<128> FilePath = F->getName(); 519 if (!llvm::sys::path::is_absolute(FilePath)) { 520 if (auto EC = 521 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute( 522 FilePath)) { 523 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath, 524 EC.message()); 525 return None; 526 } 527 } 528 529 // Handle the symbolic link path case where the current working directory 530 // (getCurrentWorkingDirectory) is a symlink. We always want to the real 531 // file path (instead of the symlink path) for the C++ symbols. 532 // 533 // Consider the following example: 534 // 535 // src dir: /project/src/foo.h 536 // current working directory (symlink): /tmp/build -> /project/src/ 537 // 538 // The file path of Symbol is "/project/src/foo.h" instead of 539 // "/tmp/build/foo.h" 540 if (auto Dir = SourceMgr.getFileManager().getDirectory( 541 llvm::sys::path::parent_path(FilePath))) { 542 llvm::SmallString<128> RealPath; 543 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir); 544 llvm::sys::path::append(RealPath, DirName, 545 llvm::sys::path::filename(FilePath)); 546 return RealPath.str().str(); 547 } 548 549 return FilePath.str().str(); 550 } 551 552 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, 553 const LangOptions &L) { 554 TextEdit Result; 555 Result.range = 556 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L)); 557 Result.newText = FixIt.CodeToInsert; 558 return Result; 559 } 560 561 bool isRangeConsecutive(const Range &Left, const Range &Right) { 562 return Left.end.line == Right.start.line && 563 Left.end.character == Right.start.character; 564 } 565 566 FileDigest digest(llvm::StringRef Content) { 567 uint64_t Hash{llvm::xxHash64(Content)}; 568 FileDigest Result; 569 for (unsigned I = 0; I < Result.size(); ++I) { 570 Result[I] = uint8_t(Hash); 571 Hash >>= 8; 572 } 573 return Result; 574 } 575 576 llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) { 577 bool Invalid = false; 578 llvm::StringRef Content = SM.getBufferData(FID, &Invalid); 579 if (Invalid) 580 return None; 581 return digest(Content); 582 } 583 584 format::FormatStyle getFormatStyleForFile(llvm::StringRef File, 585 llvm::StringRef Content, 586 llvm::vfs::FileSystem *FS) { 587 auto Style = format::getStyle(format::DefaultFormatStyle, File, 588 format::DefaultFallbackStyle, Content, FS); 589 if (!Style) { 590 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File, 591 Style.takeError()); 592 Style = format::getLLVMStyle(); 593 } 594 return *Style; 595 } 596 597 llvm::Expected<tooling::Replacements> 598 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces, 599 const format::FormatStyle &Style) { 600 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style); 601 if (!CleanReplaces) 602 return CleanReplaces; 603 return formatReplacements(Code, std::move(*CleanReplaces), Style); 604 } 605 606 static void 607 lex(llvm::StringRef Code, const LangOptions &LangOpts, 608 llvm::function_ref<void(const syntax::Token &, const SourceManager &SM)> 609 Action) { 610 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated! 611 std::string NullTerminatedCode = Code.str(); 612 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode); 613 auto &SM = FileSM.get(); 614 for (const auto &Tok : syntax::tokenize(SM.getMainFileID(), SM, LangOpts)) 615 Action(Tok, SM); 616 } 617 618 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content, 619 const format::FormatStyle &Style) { 620 llvm::StringMap<unsigned> Identifiers; 621 auto LangOpt = format::getFormattingLangOpts(Style); 622 lex(Content, LangOpt, [&](const syntax::Token &Tok, const SourceManager &SM) { 623 if (Tok.kind() == tok::identifier) 624 ++Identifiers[Tok.text(SM)]; 625 // FIXME: Should this function really return keywords too ? 626 else if (const auto *Keyword = tok::getKeywordSpelling(Tok.kind())) 627 ++Identifiers[Keyword]; 628 }); 629 return Identifiers; 630 } 631 632 std::vector<Range> collectIdentifierRanges(llvm::StringRef Identifier, 633 llvm::StringRef Content, 634 const LangOptions &LangOpts) { 635 std::vector<Range> Ranges; 636 lex(Content, LangOpts, 637 [&](const syntax::Token &Tok, const SourceManager &SM) { 638 if (Tok.kind() != tok::identifier || Tok.text(SM) != Identifier) 639 return; 640 Ranges.push_back(halfOpenToRange(SM, Tok.range(SM).toCharRange(SM))); 641 }); 642 return Ranges; 643 } 644 645 namespace { 646 struct NamespaceEvent { 647 enum { 648 BeginNamespace, // namespace <ns> {. Payload is resolved <ns>. 649 EndNamespace, // } // namespace <ns>. Payload is resolved *outer* 650 // namespace. 651 UsingDirective // using namespace <ns>. Payload is unresolved <ns>. 652 } Trigger; 653 std::string Payload; 654 Position Pos; 655 }; 656 // Scans C++ source code for constructs that change the visible namespaces. 657 void parseNamespaceEvents(llvm::StringRef Code, const LangOptions &LangOpts, 658 llvm::function_ref<void(NamespaceEvent)> Callback) { 659 660 // Stack of enclosing namespaces, e.g. {"clang", "clangd"} 661 std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd" 662 // Stack counts open braces. true if the brace opened a namespace. 663 std::vector<bool> BraceStack; 664 665 enum { 666 Default, 667 Namespace, // just saw 'namespace' 668 NamespaceName, // just saw 'namespace' NSName 669 Using, // just saw 'using' 670 UsingNamespace, // just saw 'using namespace' 671 UsingNamespaceName, // just saw 'using namespace' NSName 672 } State = Default; 673 std::string NSName; 674 675 NamespaceEvent Event; 676 lex(Code, LangOpts, [&](const syntax::Token &Tok, const SourceManager &SM) { 677 Event.Pos = sourceLocToPosition(SM, Tok.location()); 678 switch (Tok.kind()) { 679 case tok::kw_using: 680 State = State == Default ? Using : Default; 681 break; 682 case tok::kw_namespace: 683 switch (State) { 684 case Using: 685 State = UsingNamespace; 686 break; 687 case Default: 688 State = Namespace; 689 break; 690 default: 691 State = Default; 692 break; 693 } 694 break; 695 case tok::identifier: 696 switch (State) { 697 case UsingNamespace: 698 NSName.clear(); 699 LLVM_FALLTHROUGH; 700 case UsingNamespaceName: 701 NSName.append(Tok.text(SM).str()); 702 State = UsingNamespaceName; 703 break; 704 case Namespace: 705 NSName.clear(); 706 LLVM_FALLTHROUGH; 707 case NamespaceName: 708 NSName.append(Tok.text(SM).str()); 709 State = NamespaceName; 710 break; 711 case Using: 712 case Default: 713 State = Default; 714 break; 715 } 716 break; 717 case tok::coloncolon: 718 // This can come at the beginning or in the middle of a namespace 719 // name. 720 switch (State) { 721 case UsingNamespace: 722 NSName.clear(); 723 LLVM_FALLTHROUGH; 724 case UsingNamespaceName: 725 NSName.append("::"); 726 State = UsingNamespaceName; 727 break; 728 case NamespaceName: 729 NSName.append("::"); 730 State = NamespaceName; 731 break; 732 case Namespace: // Not legal here. 733 case Using: 734 case Default: 735 State = Default; 736 break; 737 } 738 break; 739 case tok::l_brace: 740 // Record which { started a namespace, so we know when } ends one. 741 if (State == NamespaceName) { 742 // Parsed: namespace <name> { 743 BraceStack.push_back(true); 744 Enclosing.push_back(NSName); 745 Event.Trigger = NamespaceEvent::BeginNamespace; 746 Event.Payload = llvm::join(Enclosing, "::"); 747 Callback(Event); 748 } else { 749 // This case includes anonymous namespaces (State = Namespace). 750 // For our purposes, they're not namespaces and we ignore them. 751 BraceStack.push_back(false); 752 } 753 State = Default; 754 break; 755 case tok::r_brace: 756 // If braces are unmatched, we're going to be confused, but don't 757 // crash. 758 if (!BraceStack.empty()) { 759 if (BraceStack.back()) { 760 // Parsed: } // namespace 761 Enclosing.pop_back(); 762 Event.Trigger = NamespaceEvent::EndNamespace; 763 Event.Payload = llvm::join(Enclosing, "::"); 764 Callback(Event); 765 } 766 BraceStack.pop_back(); 767 } 768 break; 769 case tok::semi: 770 if (State == UsingNamespaceName) { 771 // Parsed: using namespace <name> ; 772 Event.Trigger = NamespaceEvent::UsingDirective; 773 Event.Payload = std::move(NSName); 774 Callback(Event); 775 } 776 State = Default; 777 break; 778 default: 779 State = Default; 780 break; 781 } 782 }); 783 } 784 785 // Returns the prefix namespaces of NS: {"" ... NS}. 786 llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) { 787 llvm::SmallVector<llvm::StringRef, 8> Results; 788 Results.push_back(NS.take_front(0)); 789 NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 790 for (llvm::StringRef &R : Results) 791 R = NS.take_front(R.end() - NS.begin()); 792 return Results; 793 } 794 795 } // namespace 796 797 std::vector<std::string> visibleNamespaces(llvm::StringRef Code, 798 const LangOptions &LangOpts) { 799 std::string Current; 800 // Map from namespace to (resolved) namespaces introduced via using directive. 801 llvm::StringMap<llvm::StringSet<>> UsingDirectives; 802 803 parseNamespaceEvents(Code, LangOpts, [&](NamespaceEvent Event) { 804 llvm::StringRef NS = Event.Payload; 805 switch (Event.Trigger) { 806 case NamespaceEvent::BeginNamespace: 807 case NamespaceEvent::EndNamespace: 808 Current = std::move(Event.Payload); 809 break; 810 case NamespaceEvent::UsingDirective: 811 if (NS.consume_front("::")) 812 UsingDirectives[Current].insert(NS); 813 else { 814 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) { 815 if (Enclosing.empty()) 816 UsingDirectives[Current].insert(NS); 817 else 818 UsingDirectives[Current].insert((Enclosing + "::" + NS).str()); 819 } 820 } 821 break; 822 } 823 }); 824 825 std::vector<std::string> Found; 826 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) { 827 Found.push_back(std::string(Enclosing)); 828 auto It = UsingDirectives.find(Enclosing); 829 if (It != UsingDirectives.end()) 830 for (const auto &Used : It->second) 831 Found.push_back(std::string(Used.getKey())); 832 } 833 834 llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) { 835 if (Current == RHS) 836 return false; 837 if (Current == LHS) 838 return true; 839 return LHS < RHS; 840 }); 841 Found.erase(std::unique(Found.begin(), Found.end()), Found.end()); 842 return Found; 843 } 844 845 llvm::StringSet<> collectWords(llvm::StringRef Content) { 846 // We assume short words are not significant. 847 // We may want to consider other stopwords, e.g. language keywords. 848 // (A very naive implementation showed no benefit, but lexing might do better) 849 static constexpr int MinWordLength = 4; 850 851 std::vector<CharRole> Roles(Content.size()); 852 calculateRoles(Content, Roles); 853 854 llvm::StringSet<> Result; 855 llvm::SmallString<256> Word; 856 auto Flush = [&] { 857 if (Word.size() >= MinWordLength) { 858 for (char &C : Word) 859 C = llvm::toLower(C); 860 Result.insert(Word); 861 } 862 Word.clear(); 863 }; 864 for (unsigned I = 0; I < Content.size(); ++I) { 865 switch (Roles[I]) { 866 case Head: 867 Flush(); 868 LLVM_FALLTHROUGH; 869 case Tail: 870 Word.push_back(Content[I]); 871 break; 872 case Unknown: 873 case Separator: 874 Flush(); 875 break; 876 } 877 } 878 Flush(); 879 880 return Result; 881 } 882 883 llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok, 884 Preprocessor &PP) { 885 SourceLocation Loc = SpelledTok.location(); 886 assert(Loc.isFileID()); 887 const auto &SM = PP.getSourceManager(); 888 IdentifierInfo *IdentifierInfo = PP.getIdentifierInfo(SpelledTok.text(SM)); 889 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition()) 890 return None; 891 892 // Get the definition just before the searched location so that a macro 893 // referenced in a '#undef MACRO' can still be found. Note that we only do 894 // that if Loc is not pointing at start of file. 895 if (SM.getLocForStartOfFile(SM.getFileID(Loc)) != Loc) 896 Loc = Loc.getLocWithOffset(-1); 897 MacroDefinition MacroDef = PP.getMacroDefinitionAtLoc(IdentifierInfo, Loc); 898 if (auto *MI = MacroDef.getMacroInfo()) 899 return DefinedMacro{IdentifierInfo->getName(), MI}; 900 return None; 901 } 902 903 llvm::Expected<std::string> Edit::apply() const { 904 return tooling::applyAllReplacements(InitialCode, Replacements); 905 } 906 907 std::vector<TextEdit> Edit::asTextEdits() const { 908 return replacementsToEdits(InitialCode, Replacements); 909 } 910 911 bool Edit::canApplyTo(llvm::StringRef Code) const { 912 // Create line iterators, since line numbers are important while applying our 913 // edit we cannot skip blank lines. 914 auto LHS = llvm::MemoryBuffer::getMemBuffer(Code); 915 llvm::line_iterator LHSIt(*LHS, /*SkipBlanks=*/false); 916 917 auto RHS = llvm::MemoryBuffer::getMemBuffer(InitialCode); 918 llvm::line_iterator RHSIt(*RHS, /*SkipBlanks=*/false); 919 920 // Compare the InitialCode we prepared the edit for with the Code we received 921 // line by line to make sure there are no differences. 922 // FIXME: This check is too conservative now, it should be enough to only 923 // check lines around the replacements contained inside the Edit. 924 while (!LHSIt.is_at_eof() && !RHSIt.is_at_eof()) { 925 if (*LHSIt != *RHSIt) 926 return false; 927 ++LHSIt; 928 ++RHSIt; 929 } 930 931 // After we reach EOF for any of the files we make sure the other one doesn't 932 // contain any additional content except empty lines, they should not 933 // interfere with the edit we produced. 934 while (!LHSIt.is_at_eof()) { 935 if (!LHSIt->empty()) 936 return false; 937 ++LHSIt; 938 } 939 while (!RHSIt.is_at_eof()) { 940 if (!RHSIt->empty()) 941 return false; 942 ++RHSIt; 943 } 944 return true; 945 } 946 947 llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style) { 948 if (auto NewEdits = cleanupAndFormat(E.InitialCode, E.Replacements, Style)) 949 E.Replacements = std::move(*NewEdits); 950 else 951 return NewEdits.takeError(); 952 return llvm::Error::success(); 953 } 954 955 EligibleRegion getEligiblePoints(llvm::StringRef Code, 956 llvm::StringRef FullyQualifiedName, 957 const LangOptions &LangOpts) { 958 EligibleRegion ER; 959 // Start with global namespace. 960 std::vector<std::string> Enclosing = {""}; 961 // FIXME: In addition to namespaces try to generate events for function 962 // definitions as well. One might use a closing parantheses(")" followed by an 963 // opening brace "{" to trigger the start. 964 parseNamespaceEvents(Code, LangOpts, [&](NamespaceEvent Event) { 965 // Using Directives only introduces declarations to current scope, they do 966 // not change the current namespace, so skip them. 967 if (Event.Trigger == NamespaceEvent::UsingDirective) 968 return; 969 // Do not qualify the global namespace. 970 if (!Event.Payload.empty()) 971 Event.Payload.append("::"); 972 973 std::string CurrentNamespace; 974 if (Event.Trigger == NamespaceEvent::BeginNamespace) { 975 Enclosing.emplace_back(std::move(Event.Payload)); 976 CurrentNamespace = Enclosing.back(); 977 // parseNameSpaceEvents reports the beginning position of a token; we want 978 // to insert after '{', so increment by one. 979 ++Event.Pos.character; 980 } else { 981 // Event.Payload points to outer namespace when exiting a scope, so use 982 // the namespace we've last entered instead. 983 CurrentNamespace = std::move(Enclosing.back()); 984 Enclosing.pop_back(); 985 assert(Enclosing.back() == Event.Payload); 986 } 987 988 // Ignore namespaces that are not a prefix of the target. 989 if (!FullyQualifiedName.startswith(CurrentNamespace)) 990 return; 991 992 // Prefer the namespace that shares the longest prefix with target. 993 if (CurrentNamespace.size() > ER.EnclosingNamespace.size()) { 994 ER.EligiblePoints.clear(); 995 ER.EnclosingNamespace = CurrentNamespace; 996 } 997 if (CurrentNamespace.size() == ER.EnclosingNamespace.size()) 998 ER.EligiblePoints.emplace_back(std::move(Event.Pos)); 999 }); 1000 // If there were no shared namespaces just return EOF. 1001 if (ER.EligiblePoints.empty()) { 1002 assert(ER.EnclosingNamespace.empty()); 1003 ER.EligiblePoints.emplace_back(offsetToPosition(Code, Code.size())); 1004 } 1005 return ER; 1006 } 1007 1008 bool isHeaderFile(llvm::StringRef FileName, 1009 llvm::Optional<LangOptions> LangOpts) { 1010 // Respect the langOpts, for non-file-extension cases, e.g. standard library 1011 // files. 1012 if (LangOpts && LangOpts->IsHeaderFile) 1013 return true; 1014 namespace types = clang::driver::types; 1015 auto Lang = types::lookupTypeForExtension( 1016 llvm::sys::path::extension(FileName).substr(1)); 1017 return Lang != types::TY_INVALID && types::onlyPrecompileType(Lang); 1018 } 1019 1020 bool isProtoFile(SourceLocation Loc, const SourceManager &SM) { 1021 auto FileName = SM.getFilename(Loc); 1022 if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h")) 1023 return false; 1024 auto FID = SM.getFileID(Loc); 1025 // All proto generated headers should start with this line. 1026 static const char *PROTO_HEADER_COMMENT = 1027 "// Generated by the protocol buffer compiler. DO NOT EDIT!"; 1028 // Double check that this is an actual protobuf header. 1029 return SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT); 1030 } 1031 1032 } // namespace clangd 1033 } // namespace clang 1034