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 "Logger.h" 12 #include "Protocol.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/Basic/SourceManager.h" 15 #include "clang/Lex/Lexer.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Support/Errc.h" 19 #include "llvm/Support/Error.h" 20 #include "llvm/Support/ErrorHandling.h" 21 #include "llvm/Support/Path.h" 22 23 namespace clang { 24 namespace clangd { 25 26 // Here be dragons. LSP positions use columns measured in *UTF-16 code units*! 27 // Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial. 28 29 // Iterates over unicode codepoints in the (UTF-8) string. For each, 30 // invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true. 31 // Returns true if CB returned true, false if we hit the end of string. 32 template <typename Callback> 33 static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) { 34 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). 35 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx. 36 for (size_t I = 0; I < U8.size();) { 37 unsigned char C = static_cast<unsigned char>(U8[I]); 38 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character. 39 if (CB(1, 1)) 40 return true; 41 ++I; 42 continue; 43 } 44 // This convenient property of UTF-8 holds for all non-ASCII characters. 45 size_t UTF8Length = llvm::countLeadingOnes(C); 46 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here. 47 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug. 48 assert((UTF8Length >= 2 && UTF8Length <= 4) && 49 "Invalid UTF-8, or transcoding bug?"); 50 I += UTF8Length; // Skip over all trailing bytes. 51 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). 52 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...) 53 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1)) 54 return true; 55 } 56 return false; 57 } 58 59 // Returns the byte offset into the string that is an offset of \p Units in 60 // the specified encoding. 61 // Conceptually, this converts to the encoding, truncates to CodeUnits, 62 // converts back to UTF-8, and returns the length in bytes. 63 static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc, 64 bool &Valid) { 65 Valid = Units >= 0; 66 if (Units <= 0) 67 return 0; 68 size_t Result = 0; 69 switch (Enc) { 70 case OffsetEncoding::UTF8: 71 Result = Units; 72 break; 73 case OffsetEncoding::UTF16: 74 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) { 75 Result += U8Len; 76 Units -= U16Len; 77 return Units <= 0; 78 }); 79 if (Units < 0) // Offset in the middle of a surrogate pair. 80 Valid = false; 81 break; 82 case OffsetEncoding::UTF32: 83 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) { 84 Result += U8Len; 85 Units--; 86 return Units <= 0; 87 }); 88 break; 89 case OffsetEncoding::UnsupportedEncoding: 90 llvm_unreachable("unsupported encoding"); 91 } 92 // Don't return an out-of-range index if we overran. 93 if (Result > U8.size()) { 94 Valid = false; 95 return U8.size(); 96 } 97 return Result; 98 } 99 100 Key<OffsetEncoding> kCurrentOffsetEncoding; 101 static OffsetEncoding lspEncoding() { 102 auto *Enc = Context::current().get(kCurrentOffsetEncoding); 103 return Enc ? *Enc : OffsetEncoding::UTF16; 104 } 105 106 // Like most strings in clangd, the input is UTF-8 encoded. 107 size_t lspLength(llvm::StringRef Code) { 108 size_t Count = 0; 109 switch (lspEncoding()) { 110 case OffsetEncoding::UTF8: 111 Count = Code.size(); 112 break; 113 case OffsetEncoding::UTF16: 114 iterateCodepoints(Code, [&](int U8Len, int U16Len) { 115 Count += U16Len; 116 return false; 117 }); 118 break; 119 case OffsetEncoding::UTF32: 120 iterateCodepoints(Code, [&](int U8Len, int U16Len) { 121 ++Count; 122 return false; 123 }); 124 break; 125 case OffsetEncoding::UnsupportedEncoding: 126 llvm_unreachable("unsupported encoding"); 127 } 128 return Count; 129 } 130 131 llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P, 132 bool AllowColumnsBeyondLineLength) { 133 if (P.line < 0) 134 return llvm::make_error<llvm::StringError>( 135 llvm::formatv("Line value can't be negative ({0})", P.line), 136 llvm::errc::invalid_argument); 137 if (P.character < 0) 138 return llvm::make_error<llvm::StringError>( 139 llvm::formatv("Character value can't be negative ({0})", P.character), 140 llvm::errc::invalid_argument); 141 size_t StartOfLine = 0; 142 for (int I = 0; I != P.line; ++I) { 143 size_t NextNL = Code.find('\n', StartOfLine); 144 if (NextNL == llvm::StringRef::npos) 145 return llvm::make_error<llvm::StringError>( 146 llvm::formatv("Line value is out of range ({0})", P.line), 147 llvm::errc::invalid_argument); 148 StartOfLine = NextNL + 1; 149 } 150 StringRef Line = 151 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; }); 152 153 // P.character may be in UTF-16, transcode if necessary. 154 bool Valid; 155 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid); 156 if (!Valid && !AllowColumnsBeyondLineLength) 157 return llvm::make_error<llvm::StringError>( 158 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(), 159 P.character, P.line), 160 llvm::errc::invalid_argument); 161 return StartOfLine + ByteInLine; 162 } 163 164 Position offsetToPosition(llvm::StringRef Code, size_t Offset) { 165 Offset = std::min(Code.size(), Offset); 166 llvm::StringRef Before = Code.substr(0, Offset); 167 int Lines = Before.count('\n'); 168 size_t PrevNL = Before.rfind('\n'); 169 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1); 170 Position Pos; 171 Pos.line = Lines; 172 Pos.character = lspLength(Before.substr(StartOfLine)); 173 return Pos; 174 } 175 176 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) { 177 // We use the SourceManager's line tables, but its column number is in bytes. 178 FileID FID; 179 unsigned Offset; 180 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc); 181 Position P; 182 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1; 183 bool Invalid = false; 184 llvm::StringRef Code = SM.getBufferData(FID, &Invalid); 185 if (!Invalid) { 186 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1; 187 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes); 188 P.character = lspLength(LineSoFar); 189 } 190 return P; 191 } 192 193 bool isValidFileRange(const SourceManager &Mgr, SourceRange R) { 194 if (!R.getBegin().isValid() || !R.getEnd().isValid()) 195 return false; 196 197 FileID BeginFID; 198 size_t BeginOffset = 0; 199 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin()); 200 201 FileID EndFID; 202 size_t EndOffset = 0; 203 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd()); 204 205 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset; 206 } 207 208 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R, 209 SourceLocation L) { 210 assert(isValidFileRange(Mgr, R)); 211 212 FileID BeginFID; 213 size_t BeginOffset = 0; 214 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin()); 215 size_t EndOffset = Mgr.getFileOffset(R.getEnd()); 216 217 FileID LFid; 218 size_t LOffset; 219 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L); 220 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset; 221 } 222 223 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R, 224 SourceLocation L) { 225 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L); 226 } 227 228 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr, 229 const LangOptions &LangOpts, 230 SourceRange R) { 231 auto Begin = Mgr.getFileLoc(R.getBegin()); 232 if (Begin.isInvalid()) 233 return llvm::None; 234 auto End = Mgr.getFileLoc(R.getEnd()); 235 if (End.isInvalid()) 236 return llvm::None; 237 End = Lexer::getLocForEndOfToken(End, 0, Mgr, LangOpts); 238 239 SourceRange Result(Begin, End); 240 if (!isValidFileRange(Mgr, Result)) 241 return llvm::None; 242 return Result; 243 } 244 245 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) { 246 assert(isValidFileRange(SM, R)); 247 bool Invalid = false; 248 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid); 249 assert(!Invalid); 250 251 size_t BeginOffset = SM.getFileOffset(R.getBegin()); 252 size_t EndOffset = SM.getFileOffset(R.getEnd()); 253 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset); 254 } 255 256 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM, 257 Position P) { 258 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer(); 259 auto Offset = 260 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false); 261 if (!Offset) 262 return Offset.takeError(); 263 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset); 264 } 265 266 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) { 267 // Clang is 1-based, LSP uses 0-based indexes. 268 Position Begin = sourceLocToPosition(SM, R.getBegin()); 269 Position End = sourceLocToPosition(SM, R.getEnd()); 270 271 return {Begin, End}; 272 } 273 274 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code, 275 size_t Offset) { 276 Offset = std::min(Code.size(), Offset); 277 llvm::StringRef Before = Code.substr(0, Offset); 278 int Lines = Before.count('\n'); 279 size_t PrevNL = Before.rfind('\n'); 280 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1); 281 return {Lines + 1, Offset - StartOfLine + 1}; 282 } 283 284 std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) { 285 size_t Pos = QName.rfind("::"); 286 if (Pos == llvm::StringRef::npos) 287 return {llvm::StringRef(), QName}; 288 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)}; 289 } 290 291 TextEdit replacementToEdit(llvm::StringRef Code, 292 const tooling::Replacement &R) { 293 Range ReplacementRange = { 294 offsetToPosition(Code, R.getOffset()), 295 offsetToPosition(Code, R.getOffset() + R.getLength())}; 296 return {ReplacementRange, R.getReplacementText()}; 297 } 298 299 std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code, 300 const tooling::Replacements &Repls) { 301 std::vector<TextEdit> Edits; 302 for (const auto &R : Repls) 303 Edits.push_back(replacementToEdit(Code, R)); 304 return Edits; 305 } 306 307 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F, 308 const SourceManager &SourceMgr) { 309 if (!F) 310 return None; 311 312 llvm::SmallString<128> FilePath = F->getName(); 313 if (!llvm::sys::path::is_absolute(FilePath)) { 314 if (auto EC = 315 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute( 316 FilePath)) { 317 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath, 318 EC.message()); 319 return None; 320 } 321 } 322 323 // Handle the symbolic link path case where the current working directory 324 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real 325 // file path (instead of the symlink path) for the C++ symbols. 326 // 327 // Consider the following example: 328 // 329 // src dir: /project/src/foo.h 330 // current working directory (symlink): /tmp/build -> /project/src/ 331 // 332 // The file path of Symbol is "/project/src/foo.h" instead of 333 // "/tmp/build/foo.h" 334 if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory( 335 llvm::sys::path::parent_path(FilePath))) { 336 llvm::SmallString<128> RealPath; 337 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir); 338 llvm::sys::path::append(RealPath, DirName, 339 llvm::sys::path::filename(FilePath)); 340 return RealPath.str().str(); 341 } 342 343 return FilePath.str().str(); 344 } 345 346 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, 347 const LangOptions &L) { 348 TextEdit Result; 349 Result.range = 350 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L)); 351 Result.newText = FixIt.CodeToInsert; 352 return Result; 353 } 354 355 bool isRangeConsecutive(const Range &Left, const Range &Right) { 356 return Left.end.line == Right.start.line && 357 Left.end.character == Right.start.character; 358 } 359 360 FileDigest digest(llvm::StringRef Content) { 361 return llvm::SHA1::hash({(const uint8_t *)Content.data(), Content.size()}); 362 } 363 364 llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) { 365 bool Invalid = false; 366 llvm::StringRef Content = SM.getBufferData(FID, &Invalid); 367 if (Invalid) 368 return None; 369 return digest(Content); 370 } 371 372 format::FormatStyle getFormatStyleForFile(llvm::StringRef File, 373 llvm::StringRef Content, 374 llvm::vfs::FileSystem *FS) { 375 auto Style = format::getStyle(format::DefaultFormatStyle, File, 376 format::DefaultFallbackStyle, Content, FS); 377 if (!Style) { 378 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File, 379 Style.takeError()); 380 Style = format::getLLVMStyle(); 381 } 382 return *Style; 383 } 384 385 llvm::Expected<tooling::Replacements> 386 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces, 387 const format::FormatStyle &Style) { 388 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style); 389 if (!CleanReplaces) 390 return CleanReplaces; 391 return formatReplacements(Code, std::move(*CleanReplaces), Style); 392 } 393 394 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content, 395 const format::FormatStyle &Style) { 396 SourceManagerForFile FileSM("dummy.cpp", Content); 397 auto &SM = FileSM.get(); 398 auto FID = SM.getMainFileID(); 399 Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style)); 400 Token Tok; 401 402 llvm::StringMap<unsigned> Identifiers; 403 while (!Lex.LexFromRawLexer(Tok)) { 404 switch (Tok.getKind()) { 405 case tok::identifier: 406 ++Identifiers[Tok.getIdentifierInfo()->getName()]; 407 break; 408 case tok::raw_identifier: 409 ++Identifiers[Tok.getRawIdentifier()]; 410 break; 411 default: 412 continue; 413 } 414 } 415 return Identifiers; 416 } 417 418 } // namespace clangd 419 } // namespace clang 420