1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
|
//===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SourceCode.h"
#include "Context.h"
#include "FuzzyMatch.h"
#include "Logger.h"
#include "Protocol.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
namespace clang {
namespace clangd {
// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
// Iterates over unicode codepoints in the (UTF-8) string. For each,
// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
// Returns true if CB returned true, false if we hit the end of string.
template <typename Callback>
static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
// A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
// Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
for (size_t I = 0; I < U8.size();) {
unsigned char C = static_cast<unsigned char>(U8[I]);
if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
if (CB(1, 1))
return true;
++I;
continue;
}
// This convenient property of UTF-8 holds for all non-ASCII characters.
size_t UTF8Length = llvm::countLeadingOnes(C);
// 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
// 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
assert((UTF8Length >= 2 && UTF8Length <= 4) &&
"Invalid UTF-8, or transcoding bug?");
I += UTF8Length; // Skip over all trailing bytes.
// A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
// Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
return true;
}
return false;
}
// Returns the byte offset into the string that is an offset of \p Units in
// the specified encoding.
// Conceptually, this converts to the encoding, truncates to CodeUnits,
// converts back to UTF-8, and returns the length in bytes.
static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
bool &Valid) {
Valid = Units >= 0;
if (Units <= 0)
return 0;
size_t Result = 0;
switch (Enc) {
case OffsetEncoding::UTF8:
Result = Units;
break;
case OffsetEncoding::UTF16:
Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
Result += U8Len;
Units -= U16Len;
return Units <= 0;
});
if (Units < 0) // Offset in the middle of a surrogate pair.
Valid = false;
break;
case OffsetEncoding::UTF32:
Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
Result += U8Len;
Units--;
return Units <= 0;
});
break;
case OffsetEncoding::UnsupportedEncoding:
llvm_unreachable("unsupported encoding");
}
// Don't return an out-of-range index if we overran.
if (Result > U8.size()) {
Valid = false;
return U8.size();
}
return Result;
}
Key<OffsetEncoding> kCurrentOffsetEncoding;
static OffsetEncoding lspEncoding() {
auto *Enc = Context::current().get(kCurrentOffsetEncoding);
return Enc ? *Enc : OffsetEncoding::UTF16;
}
// Like most strings in clangd, the input is UTF-8 encoded.
size_t lspLength(llvm::StringRef Code) {
size_t Count = 0;
switch (lspEncoding()) {
case OffsetEncoding::UTF8:
Count = Code.size();
break;
case OffsetEncoding::UTF16:
iterateCodepoints(Code, [&](int U8Len, int U16Len) {
Count += U16Len;
return false;
});
break;
case OffsetEncoding::UTF32:
iterateCodepoints(Code, [&](int U8Len, int U16Len) {
++Count;
return false;
});
break;
case OffsetEncoding::UnsupportedEncoding:
llvm_unreachable("unsupported encoding");
}
return Count;
}
llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
bool AllowColumnsBeyondLineLength) {
if (P.line < 0)
return llvm::make_error<llvm::StringError>(
llvm::formatv("Line value can't be negative ({0})", P.line),
llvm::errc::invalid_argument);
if (P.character < 0)
return llvm::make_error<llvm::StringError>(
llvm::formatv("Character value can't be negative ({0})", P.character),
llvm::errc::invalid_argument);
size_t StartOfLine = 0;
for (int I = 0; I != P.line; ++I) {
size_t NextNL = Code.find('\n', StartOfLine);
if (NextNL == llvm::StringRef::npos)
return llvm::make_error<llvm::StringError>(
llvm::formatv("Line value is out of range ({0})", P.line),
llvm::errc::invalid_argument);
StartOfLine = NextNL + 1;
}
StringRef Line =
Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
// P.character may be in UTF-16, transcode if necessary.
bool Valid;
size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
if (!Valid && !AllowColumnsBeyondLineLength)
return llvm::make_error<llvm::StringError>(
llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
P.character, P.line),
llvm::errc::invalid_argument);
return StartOfLine + ByteInLine;
}
Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Offset = std::min(Code.size(), Offset);
llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Position Pos;
Pos.line = Lines;
Pos.character = lspLength(Before.substr(StartOfLine));
return Pos;
}
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
// We use the SourceManager's line tables, but its column number is in bytes.
FileID FID;
unsigned Offset;
std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Position P;
P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
bool Invalid = false;
llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
if (!Invalid) {
auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
P.character = lspLength(LineSoFar);
}
return P;
}
llvm::Optional<Range> getTokenRange(const SourceManager &SM,
const LangOptions &LangOpts,
SourceLocation TokLoc) {
if (!TokLoc.isValid())
return llvm::None;
SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
if (!End.isValid())
return llvm::None;
return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
}
bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
if (!R.getBegin().isValid() || !R.getEnd().isValid())
return false;
FileID BeginFID;
size_t BeginOffset = 0;
std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
FileID EndFID;
size_t EndOffset = 0;
std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
}
bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
SourceLocation L) {
assert(isValidFileRange(Mgr, R));
FileID BeginFID;
size_t BeginOffset = 0;
std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
size_t EndOffset = Mgr.getFileOffset(R.getEnd());
FileID LFid;
size_t LOffset;
std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
}
bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
SourceLocation L) {
return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
}
static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
const LangOptions &LangOpts) {
Token TheTok;
if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
return 0;
// FIXME: Here we check whether the token at the location is a greatergreater
// (>>) token and consider it as a single greater (>). This is to get it
// working for templates but it isn't correct for the right shift operator. We
// can avoid this by using half open char ranges in getFileRange() but getting
// token ending is not well supported in macroIDs.
if (TheTok.is(tok::greatergreater))
return 1;
return TheTok.getLength();
}
// Returns location of the last character of the token at a given loc
static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
const SourceManager &SM,
const LangOptions &LangOpts) {
unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
}
// Returns location of the starting of the token at a given EndLoc
static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
const SourceManager &SM,
const LangOptions &LangOpts) {
return EndLoc.getLocWithOffset(
-(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
}
// Converts a char source range to a token range.
static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
const LangOptions &LangOpts) {
if (!Range.isTokenRange())
Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
return Range.getAsRange();
}
// Returns the union of two token ranges.
// To find the maximum of the Ends of the ranges, we compare the location of the
// last character of the token.
static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
const SourceManager &SM,
const LangOptions &LangOpts) {
SourceLocation E1 = getLocForTokenEnd(R1.getEnd(), SM, LangOpts);
SourceLocation E2 = getLocForTokenEnd(R2.getEnd(), SM, LangOpts);
return SourceRange(std::min(R1.getBegin(), R2.getBegin()),
E1 < E2 ? R2.getEnd() : R1.getEnd());
}
// Check if two locations have the same file id.
static bool inSameFile(SourceLocation Loc1, SourceLocation Loc2,
const SourceManager &SM) {
return SM.getFileID(Loc1) == SM.getFileID(Loc2);
}
// Find an expansion range (not necessarily immediate) the ends of which are in
// the same file id.
static SourceRange
getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
const LangOptions &LangOpts) {
SourceRange ExpansionRange =
toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts);
// Fast path for most common cases.
if (inSameFile(ExpansionRange.getBegin(), ExpansionRange.getEnd(), SM))
return ExpansionRange;
// Record the stack of expansion locations for the beginning, keyed by FileID.
llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
for (SourceLocation Begin = ExpansionRange.getBegin(); Begin.isValid();
Begin = Begin.isFileID()
? SourceLocation()
: SM.getImmediateExpansionRange(Begin).getBegin()) {
BeginExpansions[SM.getFileID(Begin)] = Begin;
}
// Move up the stack of expansion locations for the end until we find the
// location in BeginExpansions with that has the same file id.
for (SourceLocation End = ExpansionRange.getEnd(); End.isValid();
End = End.isFileID() ? SourceLocation()
: toTokenRange(SM.getImmediateExpansionRange(End),
SM, LangOpts)
.getEnd()) {
auto It = BeginExpansions.find(SM.getFileID(End));
if (It != BeginExpansions.end())
return {It->second, End};
}
llvm_unreachable(
"We should able to find a common ancestor in the expansion tree.");
}
// Returns the file range for a given Location as a Token Range
// This is quite similar to getFileLoc in SourceManager as both use
// getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
// However:
// - We want to maintain the full range information as we move from one file to
// the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
// - We want to split '>>' tokens as the lexer parses the '>>' in nested
// template instantiations as a '>>' instead of two '>'s.
// There is also getExpansionRange but it simply calls
// getImmediateExpansionRange on the begin and ends separately which is wrong.
static SourceRange getTokenFileRange(SourceLocation Loc,
const SourceManager &SM,
const LangOptions &LangOpts) {
SourceRange FileRange = Loc;
while (!FileRange.getBegin().isFileID()) {
if (SM.isMacroArgExpansion(FileRange.getBegin())) {
FileRange = unionTokenRange(
SM.getImmediateSpellingLoc(FileRange.getBegin()),
SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
assert(inSameFile(FileRange.getBegin(), FileRange.getEnd(), SM));
} else {
SourceRange ExpansionRangeForBegin =
getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
SourceRange ExpansionRangeForEnd =
getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
assert(inSameFile(ExpansionRangeForBegin.getBegin(),
ExpansionRangeForEnd.getBegin(), SM) &&
"Both Expansion ranges should be in same file.");
FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
SM, LangOpts);
}
}
return FileRange;
}
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
}
llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
const LangOptions &LangOpts,
SourceRange R) {
SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
if (!isValidFileRange(SM, R1))
return llvm::None;
SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
if (!isValidFileRange(SM, R2))
return llvm::None;
SourceRange Result = unionTokenRange(R1, R2, SM, LangOpts);
unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
// Convert from closed token range to half-open (char) range
Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
if (!isValidFileRange(SM, Result))
return llvm::None;
return Result;
}
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
assert(isValidFileRange(SM, R));
bool Invalid = false;
auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
assert(!Invalid);
size_t BeginOffset = SM.getFileOffset(R.getBegin());
size_t EndOffset = SM.getFileOffset(R.getEnd());
return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
}
llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
Position P) {
llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
auto Offset =
positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
if (!Offset)
return Offset.takeError();
return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
}
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
// Clang is 1-based, LSP uses 0-based indexes.
Position Begin = sourceLocToPosition(SM, R.getBegin());
Position End = sourceLocToPosition(SM, R.getEnd());
return {Begin, End};
}
std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
size_t Offset) {
Offset = std::min(Code.size(), Offset);
llvm::StringRef Before = Code.substr(0, Offset);
int Lines = Before.count('\n');
size_t PrevNL = Before.rfind('\n');
size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
return {Lines + 1, Offset - StartOfLine + 1};
}
std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
size_t Pos = QName.rfind("::");
if (Pos == llvm::StringRef::npos)
return {llvm::StringRef(), QName};
return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
}
TextEdit replacementToEdit(llvm::StringRef Code,
const tooling::Replacement &R) {
Range ReplacementRange = {
offsetToPosition(Code, R.getOffset()),
offsetToPosition(Code, R.getOffset() + R.getLength())};
return {ReplacementRange, R.getReplacementText()};
}
std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
const tooling::Replacements &Repls) {
std::vector<TextEdit> Edits;
for (const auto &R : Repls)
Edits.push_back(replacementToEdit(Code, R));
return Edits;
}
llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr) {
if (!F)
return None;
llvm::SmallString<128> FilePath = F->getName();
if (!llvm::sys::path::is_absolute(FilePath)) {
if (auto EC =
SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
FilePath)) {
elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
EC.message());
return None;
}
}
// Handle the symbolic link path case where the current working directory
// (getCurrentWorkingDirectory) is a symlink./ We always want to the real
// file path (instead of the symlink path) for the C++ symbols.
//
// Consider the following example:
//
// src dir: /project/src/foo.h
// current working directory (symlink): /tmp/build -> /project/src/
//
// The file path of Symbol is "/project/src/foo.h" instead of
// "/tmp/build/foo.h"
if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
llvm::sys::path::parent_path(FilePath))) {
llvm::SmallString<128> RealPath;
llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
llvm::sys::path::append(RealPath, DirName,
llvm::sys::path::filename(FilePath));
return RealPath.str().str();
}
return FilePath.str().str();
}
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
const LangOptions &L) {
TextEdit Result;
Result.range =
halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
Result.newText = FixIt.CodeToInsert;
return Result;
}
bool isRangeConsecutive(const Range &Left, const Range &Right) {
return Left.end.line == Right.start.line &&
Left.end.character == Right.start.character;
}
FileDigest digest(llvm::StringRef Content) {
uint64_t Hash{llvm::xxHash64(Content)};
FileDigest Result;
for (unsigned I = 0; I < Result.size(); ++I) {
Result[I] = uint8_t(Hash);
Hash >>= 8;
}
return Result;
}
llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
bool Invalid = false;
llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
if (Invalid)
return None;
return digest(Content);
}
format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
llvm::StringRef Content,
llvm::vfs::FileSystem *FS) {
auto Style = format::getStyle(format::DefaultFormatStyle, File,
format::DefaultFallbackStyle, Content, FS);
if (!Style) {
log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
Style.takeError());
Style = format::getLLVMStyle();
}
return *Style;
}
llvm::Expected<tooling::Replacements>
cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
const format::FormatStyle &Style) {
auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
if (!CleanReplaces)
return CleanReplaces;
return formatReplacements(Code, std::move(*CleanReplaces), Style);
}
template <typename Action>
static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
Action A) {
// FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
std::string NullTerminatedCode = Code.str();
SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
auto &SM = FileSM.get();
auto FID = SM.getMainFileID();
Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
Token Tok;
while (!Lex.LexFromRawLexer(Tok))
A(Tok);
}
llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
const format::FormatStyle &Style) {
llvm::StringMap<unsigned> Identifiers;
lex(Content, Style, [&](const clang::Token &Tok) {
switch (Tok.getKind()) {
case tok::identifier:
++Identifiers[Tok.getIdentifierInfo()->getName()];
break;
case tok::raw_identifier:
++Identifiers[Tok.getRawIdentifier()];
break;
default:
break;
}
});
return Identifiers;
}
namespace {
enum NamespaceEvent {
BeginNamespace, // namespace <ns> {. Payload is resolved <ns>.
EndNamespace, // } // namespace <ns>. Payload is resolved *outer* namespace.
UsingDirective // using namespace <ns>. Payload is unresolved <ns>.
};
// Scans C++ source code for constructs that change the visible namespaces.
void parseNamespaceEvents(
llvm::StringRef Code, const format::FormatStyle &Style,
llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
// Stack of enclosing namespaces, e.g. {"clang", "clangd"}
std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
// Stack counts open braces. true if the brace opened a namespace.
std::vector<bool> BraceStack;
enum {
Default,
Namespace, // just saw 'namespace'
NamespaceName, // just saw 'namespace' NSName
Using, // just saw 'using'
UsingNamespace, // just saw 'using namespace'
UsingNamespaceName, // just saw 'using namespace' NSName
} State = Default;
std::string NSName;
lex(Code, Style, [&](const clang::Token &Tok) {
switch(Tok.getKind()) {
case tok::raw_identifier:
// In raw mode, this could be a keyword or a name.
switch (State) {
case UsingNamespace:
case UsingNamespaceName:
NSName.append(Tok.getRawIdentifier());
State = UsingNamespaceName;
break;
case Namespace:
case NamespaceName:
NSName.append(Tok.getRawIdentifier());
State = NamespaceName;
break;
case Using:
State =
(Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
break;
case Default:
NSName.clear();
if (Tok.getRawIdentifier() == "namespace")
State = Namespace;
else if (Tok.getRawIdentifier() == "using")
State = Using;
break;
}
break;
case tok::coloncolon:
// This can come at the beginning or in the middle of a namespace name.
switch (State) {
case UsingNamespace:
case UsingNamespaceName:
NSName.append("::");
State = UsingNamespaceName;
break;
case NamespaceName:
NSName.append("::");
State = NamespaceName;
break;
case Namespace: // Not legal here.
case Using:
case Default:
State = Default;
break;
}
break;
case tok::l_brace:
// Record which { started a namespace, so we know when } ends one.
if (State == NamespaceName) {
// Parsed: namespace <name> {
BraceStack.push_back(true);
Enclosing.push_back(NSName);
Callback(BeginNamespace, llvm::join(Enclosing, "::"));
} else {
// This case includes anonymous namespaces (State = Namespace).
// For our purposes, they're not namespaces and we ignore them.
BraceStack.push_back(false);
}
State = Default;
break;
case tok::r_brace:
// If braces are unmatched, we're going to be confused, but don't crash.
if (!BraceStack.empty()) {
if (BraceStack.back()) {
// Parsed: } // namespace
Enclosing.pop_back();
Callback(EndNamespace, llvm::join(Enclosing, "::"));
}
BraceStack.pop_back();
}
break;
case tok::semi:
if (State == UsingNamespaceName)
// Parsed: using namespace <name> ;
Callback(UsingDirective, llvm::StringRef(NSName));
State = Default;
break;
default:
State = Default;
break;
}
});
}
// Returns the prefix namespaces of NS: {"" ... NS}.
llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
llvm::SmallVector<llvm::StringRef, 8> Results;
Results.push_back(NS.take_front(0));
NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
for (llvm::StringRef &R : Results)
R = NS.take_front(R.end() - NS.begin());
return Results;
}
} // namespace
std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
const format::FormatStyle &Style) {
std::string Current;
// Map from namespace to (resolved) namespaces introduced via using directive.
llvm::StringMap<llvm::StringSet<>> UsingDirectives;
parseNamespaceEvents(Code, Style,
[&](NamespaceEvent Event, llvm::StringRef NS) {
switch (Event) {
case BeginNamespace:
case EndNamespace:
Current = NS;
break;
case UsingDirective:
if (NS.consume_front("::"))
UsingDirectives[Current].insert(NS);
else {
for (llvm::StringRef Enclosing :
ancestorNamespaces(Current)) {
if (Enclosing.empty())
UsingDirectives[Current].insert(NS);
else
UsingDirectives[Current].insert(
(Enclosing + "::" + NS).str());
}
}
break;
}
});
std::vector<std::string> Found;
for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
Found.push_back(Enclosing);
auto It = UsingDirectives.find(Enclosing);
if (It != UsingDirectives.end())
for (const auto& Used : It->second)
Found.push_back(Used.getKey());
}
llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
if (Current == RHS)
return false;
if (Current == LHS)
return true;
return LHS < RHS;
});
Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
return Found;
}
llvm::StringSet<> collectWords(llvm::StringRef Content) {
// We assume short words are not significant.
// We may want to consider other stopwords, e.g. language keywords.
// (A very naive implementation showed no benefit, but lexing might do better)
static constexpr int MinWordLength = 4;
std::vector<CharRole> Roles(Content.size());
calculateRoles(Content, Roles);
llvm::StringSet<> Result;
llvm::SmallString<256> Word;
auto Flush = [&] {
if (Word.size() >= MinWordLength) {
for (char &C : Word)
C = llvm::toLower(C);
Result.insert(Word);
}
Word.clear();
};
for (unsigned I = 0; I < Content.size(); ++I) {
switch (Roles[I]) {
case Head:
Flush();
LLVM_FALLTHROUGH;
case Tail:
Word.push_back(Content[I]);
break;
case Unknown:
case Separator:
Flush();
break;
}
}
Flush();
return Result;
}
llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
Preprocessor &PP) {
const auto &SM = PP.getSourceManager();
const auto &LangOpts = PP.getLangOpts();
Token Result;
if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
return None;
if (Result.is(tok::raw_identifier))
PP.LookUpIdentifierInfo(Result);
IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
return None;
std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
// Get the definition just before the searched location so that a macro
// referenced in a '#undef MACRO' can still be found.
SourceLocation BeforeSearchedLocation =
SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
.getLocWithOffset(DecLoc.second - 1));
MacroDefinition MacroDef =
PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
if (auto *MI = MacroDef.getMacroInfo())
return DefinedMacro{IdentifierInfo->getName(), MI};
return None;
}
} // namespace clangd
} // namespace clang
|