14 #include "clang/AST/ASTContext.h" 15 #include "clang/Basic/LangOptions.h" 16 #include "clang/Basic/SourceLocation.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Basic/TokenKinds.h" 19 #include "clang/Format/Format.h" 20 #include "clang/Lex/Lexer.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "llvm/ADT/None.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Support/Compiler.h" 26 #include "llvm/Support/Errc.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/Path.h" 30 #include "llvm/Support/xxhash.h" 42 template <
typename Callback>
46 for (
size_t I = 0; I < U8.size();) {
47 unsigned char C =
static_cast<unsigned char>(U8[I]);
48 if (LLVM_LIKELY(!(C & 0x80))) {
55 size_t UTF8Length = llvm::countLeadingOnes(C);
58 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
59 "Invalid UTF-8, or transcoding bug?");
63 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
100 llvm_unreachable(
"unsupported encoding");
103 if (Result > U8.size()) {
136 llvm_unreachable(
"unsupported encoding");
142 bool AllowColumnsBeyondLineLength) {
144 return llvm::make_error<llvm::StringError>(
145 llvm::formatv(
"Line value can't be negative ({0})", P.
line),
146 llvm::errc::invalid_argument);
148 return llvm::make_error<llvm::StringError>(
149 llvm::formatv(
"Character value can't be negative ({0})", P.
character),
150 llvm::errc::invalid_argument);
151 size_t StartOfLine = 0;
152 for (
int I = 0; I != P.
line; ++I) {
153 size_t NextNL = Code.find(
'\n', StartOfLine);
154 if (NextNL == llvm::StringRef::npos)
155 return llvm::make_error<llvm::StringError>(
156 llvm::formatv(
"Line value is out of range ({0})", P.
line),
157 llvm::errc::invalid_argument);
158 StartOfLine = NextNL + 1;
161 Code.substr(StartOfLine).take_until([](
char C) {
return C ==
'\n'; });
166 if (!Valid && !AllowColumnsBeyondLineLength)
167 return llvm::make_error<llvm::StringError>(
168 llvm::formatv(
"{0} offset {1} is invalid for line {2}",
lspEncoding(),
170 llvm::errc::invalid_argument);
171 return StartOfLine + ByteInLine;
175 Offset = std::min(Code.size(),
Offset);
176 llvm::StringRef Before = Code.substr(0, Offset);
177 int Lines = Before.count(
'\n');
178 size_t PrevNL = Before.rfind(
'\n');
179 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
190 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
192 P.
line =
static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
193 bool Invalid =
false;
194 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
196 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
197 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
204 const LangOptions &LangOpts,
205 SourceLocation TokLoc) {
206 if (!TokLoc.isValid())
208 SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
211 return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
215 if (!R.getBegin().isValid() || !R.getEnd().isValid())
219 size_t BeginOffset = 0;
220 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
223 size_t EndOffset = 0;
224 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
226 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
234 size_t BeginOffset = 0;
235 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
236 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
240 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
241 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
250 const LangOptions &LangOpts) {
252 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
259 if (TheTok.is(tok::greatergreater))
261 return TheTok.getLength();
266 const SourceManager &SM,
267 const LangOptions &LangOpts) {
269 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
274 const SourceManager &SM,
275 const LangOptions &LangOpts) {
276 return EndLoc.getLocWithOffset(
282 const LangOptions &LangOpts) {
283 if (!Range.isTokenRange())
285 return Range.getAsRange();
291 const SourceManager &SM,
292 const LangOptions &LangOpts) {
295 return SourceRange(std::min(R1.getBegin(), R2.getBegin()),
296 E1 < E2 ? R2.getEnd() : R1.getEnd());
310 const SourceManager &SM,
311 const LangOptions &LangOpts) {
312 SourceRange FileRange =
Loc;
313 while (!FileRange.getBegin().isFileID()) {
314 assert(!FileRange.getEnd().isFileID() &&
315 "Both Begin and End should be MacroIDs.");
316 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
317 FileRange.setBegin(SM.getImmediateSpellingLoc(FileRange.getBegin()));
318 FileRange.setEnd(SM.getImmediateSpellingLoc(FileRange.getEnd()));
321 SM.getImmediateExpansionRange(FileRange.getBegin()), SM, LangOpts);
323 SM.getImmediateExpansionRange(FileRange.getEnd()), SM, LangOpts);
324 FileRange =
unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
332 const LangOptions &LangOpts,
345 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
354 bool Invalid =
false;
355 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
358 size_t BeginOffset = SM.getFileOffset(R.getBegin());
359 size_t EndOffset = SM.getFileOffset(R.getEnd());
360 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
365 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
369 return Offset.takeError();
370 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*
Offset);
383 Offset = std::min(Code.size(),
Offset);
384 llvm::StringRef Before = Code.substr(0, Offset);
385 int Lines = Before.count(
'\n');
386 size_t PrevNL = Before.rfind(
'\n');
387 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
388 return {Lines + 1, Offset - StartOfLine + 1};
392 size_t Pos = QName.rfind(
"::");
393 if (Pos == llvm::StringRef::npos)
394 return {llvm::StringRef(), QName};
395 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
399 const tooling::Replacement &R) {
400 Range ReplacementRange = {
403 return {ReplacementRange, R.getReplacementText()};
407 const tooling::Replacements &Repls) {
408 std::vector<TextEdit> Edits;
409 for (
const auto &R : Repls)
415 const SourceManager &SourceMgr) {
419 llvm::SmallString<128> FilePath = F->getName();
420 if (!llvm::sys::path::is_absolute(FilePath)) {
422 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
424 elog(
"Could not turn relative path '{0}' to absolute: {1}", FilePath,
441 if (
const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
442 llvm::sys::path::parent_path(FilePath))) {
443 llvm::SmallString<128> RealPath;
444 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
445 llvm::sys::path::append(RealPath, DirName,
446 llvm::sys::path::filename(FilePath));
447 return RealPath.str().str();
450 return FilePath.str().str();
454 const LangOptions &L) {
458 Result.
newText = FixIt.CodeToInsert;
468 uint64_t Hash{llvm::xxHash64(Content)};
470 for (
unsigned I = 0; I < Result.size(); ++I) {
471 Result[I] = uint8_t(Hash);
477 llvm::Optional<FileDigest>
digestFile(
const SourceManager &SM, FileID FID) {
478 bool Invalid =
false;
479 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
486 llvm::StringRef Content,
487 llvm::vfs::FileSystem *
FS) {
488 auto Style = format::getStyle(format::DefaultFormatStyle, File,
489 format::DefaultFallbackStyle, Content, FS);
491 log(
"getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
493 Style = format::getLLVMStyle();
498 llvm::Expected<tooling::Replacements>
501 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
503 return CleanReplaces;
504 return formatReplacements(Code, std::move(*CleanReplaces), Style);
507 template <
typename Action>
511 std::string NullTerminatedCode = Code.str();
512 SourceManagerForFile FileSM(
"dummy.cpp", NullTerminatedCode);
513 auto &SM = FileSM.get();
514 auto FID = SM.getMainFileID();
515 Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
518 while (!Lex.LexFromRawLexer(Tok))
524 llvm::StringMap<unsigned> Identifiers;
525 lex(Content, Style, [&](
const clang::Token &Tok) {
526 switch (Tok.getKind()) {
527 case tok::identifier:
528 ++Identifiers[Tok.getIdentifierInfo()->getName()];
530 case tok::raw_identifier:
531 ++Identifiers[Tok.getRawIdentifier()];
547 void parseNamespaceEvents(
552 std::vector<std::string> Enclosing;
554 std::vector<bool> BraceStack;
566 lex(Code, Style, [&](
const clang::Token &Tok) {
567 switch(Tok.getKind()) {
568 case tok::raw_identifier:
572 case UsingNamespaceName:
573 NSName.append(Tok.getRawIdentifier());
574 State = UsingNamespaceName;
578 NSName.append(Tok.getRawIdentifier());
579 State = NamespaceName;
583 (Tok.getRawIdentifier() ==
"namespace") ? UsingNamespace : Default;
587 if (Tok.getRawIdentifier() ==
"namespace")
589 else if (Tok.getRawIdentifier() ==
"using")
594 case tok::coloncolon:
598 case UsingNamespaceName:
600 State = UsingNamespaceName;
604 State = NamespaceName;
615 if (State == NamespaceName) {
617 BraceStack.push_back(
true);
618 Enclosing.push_back(NSName);
623 BraceStack.push_back(
false);
629 if (!BraceStack.empty()) {
630 if (BraceStack.back()) {
632 Enclosing.pop_back();
635 BraceStack.pop_back();
639 if (State == UsingNamespaceName)
641 Callback(UsingDirective, llvm::StringRef(NSName));
652 llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
653 llvm::SmallVector<llvm::StringRef, 8>
Results;
654 Results.push_back(NS.take_front(0));
655 NS.split(Results,
"::", -1,
false);
656 for (llvm::StringRef &R : Results)
657 R = NS.take_front(R.end() - NS.begin());
667 llvm::StringMap<llvm::StringSet<>> UsingDirectives;
669 parseNamespaceEvents(Code, Style,
670 [&](NamespaceEvent
Event, llvm::StringRef NS) {
677 if (NS.consume_front(
"::"))
678 UsingDirectives[Current].insert(NS);
680 for (llvm::StringRef Enclosing :
681 ancestorNamespaces(Current)) {
682 if (Enclosing.empty())
683 UsingDirectives[Current].insert(NS);
685 UsingDirectives[Current].insert(
686 (Enclosing +
"::" + NS).str());
693 std::vector<std::string> Found;
694 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
695 Found.push_back(Enclosing);
696 auto It = UsingDirectives.find(Enclosing);
697 if (It != UsingDirectives.end())
698 for (
const auto& Used : It->second)
699 Found.push_back(Used.getKey());
702 llvm::sort(Found, [&](
const std::string &LHS,
const std::string &RHS) {
709 Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
717 static constexpr
int MinWordLength = 4;
719 std::vector<CharRole> Roles(Content.size());
723 llvm::SmallString<256>
Word;
725 if (Word.size() >= MinWordLength) {
727 C = llvm::toLower(C);
732 for (
unsigned I = 0; I < Content.size(); ++I) {
738 Word.push_back(Content[I]);
753 const auto &SM = PP.getSourceManager();
754 const auto &LangOpts = PP.getLangOpts();
756 if (Lexer::getRawToken(SM.getSpellingLoc(Loc),
Result, SM, LangOpts,
false))
758 if (Result.is(tok::raw_identifier))
759 PP.LookUpIdentifierInfo(Result);
760 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
761 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
764 std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
767 SourceLocation BeforeSearchedLocation =
768 SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
769 .getLocWithOffset(DecLoc.second - 1));
770 MacroDefinition MacroDef =
771 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
772 if (
auto *MI = MacroDef.getMacroInfo())
SourceLocation Loc
'#' location in the include directive
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
llvm::Expected< tooling::Replacements > cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces, const format::FormatStyle &Style)
Position start
The range's start position.
static void lex(llvm::StringRef Code, const format::FormatStyle &Style, Action A)
size_t lspLength(llvm::StringRef Code)
std::array< uint8_t, 8 > FileDigest
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
static SourceRange unionTokenRange(SourceRange R1, SourceRange R2, const SourceManager &SM, const LangOptions &LangOpts)
An Event<T> allows events of type T to be broadcast to listeners.
bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R, SourceLocation L)
Returns true iff L is contained in R.
std::vector< CodeCompletionResult > Results
Values in a Context are indexed by typed keys.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Documents should not be synced at all.
bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R, SourceLocation L)
Returns true iff L is contained in R or L is equal to the end point of R.
void elog(const char *Fmt, Ts &&... Vals)
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const format::FormatStyle &Style)
Heuristically determine namespaces visible at a point, without parsing Code.
bool isRangeConsecutive(const Range &Left, const Range &Right)
bool isValidFileRange(const SourceManager &Mgr, SourceRange R)
Returns true iff all of the following conditions hold:
const Type * get(const Key< Type > &Key) const
Get data stored for a typed Key.
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
std::string newText
The string to be inserted.
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Range range
The range of the text document to be manipulated.
llvm::unique_function< void()> Action
void log(const char *Fmt, Ts &&... Vals)
static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc, bool &Valid)
static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
static const Context & current()
Returns the context for the current thread, creating it if needed.
Key< OffsetEncoding > kCurrentOffsetEncoding
CharTypeSet calculateRoles(llvm::StringRef Text, llvm::MutableArrayRef< CharRole > Roles)
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
llvm::Optional< FileDigest > digestFile(const SourceManager &SM, FileID FID)
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, llvm::vfs::FileSystem *FS)
Choose the clang-format style we should apply to a certain file.
static SourceLocation getLocForTokenBegin(SourceLocation EndLoc, const SourceManager &SM, const LangOptions &LangOpts)
FileDigest digest(llvm::StringRef Content)
llvm::Optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
int line
Line position in a document (zero-based).
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
int character
Character offset on a line in a document (zero-based).
static SourceRange getTokenFileRange(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc, const SourceManager &SM, const LangOptions &LangOpts)
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
llvm::Optional< FixItHint > FixIt
static std::string join(ArrayRef< SpecialMemberFunctionsCheck::SpecialMemberFunctionKind > SMFS, llvm::StringRef AndOr)
Position end
The range's end position.
static OffsetEncoding lspEncoding()
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
llvm::Optional< DefinedMacro > locateMacroAt(SourceLocation Loc, Preprocessor &PP)
static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB)
static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"(
Style for formatting code around applied fixes:
- 'none' (default) turns off formatting
- 'file' (literally 'file', not a placeholder)
uses .clang-format file in the closest parent
directory
- '{ <json> }' specifies options inline, e.g.
-format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
- 'llvm', 'google', 'webkit', 'mozilla'
See clang-format documentation for the up-to-date
information about formatting styles and options.
This option overrides the 'FormatStyle` option in
.clang-tidy file, if any.
)"), cl::init("none"), cl::cat(ClangTidyCategory))