clang-tools  9.0.0
SourceCode.h
Go to the documentation of this file.
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 //
9 // Various code that examines C++ source code without using heavy AST machinery
10 // (and often not even the lexer). To be used sparingly!
11 //
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_SOURCECODE_H
14 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SOURCECODE_H
15 #include "Context.h"
16 #include "Protocol.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Format/Format.h"
22 #include "clang/Tooling/Core/Replacement.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Support/SHA1.h"
26 
27 namespace clang {
28 class SourceManager;
29 
30 namespace clangd {
31 
32 // We tend to generate digests for source codes in a lot of different places.
33 // This represents the type for those digests to prevent us hard coding details
34 // of hashing function at every place that needs to store this information.
35 using FileDigest = std::array<uint8_t, 8>;
36 FileDigest digest(StringRef Content);
37 Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
38 
39 // This context variable controls the behavior of functions in this file
40 // that convert between LSP offsets and native clang byte offsets.
41 // If not set, defaults to UTF-16 for backwards-compatibility.
43 
44 // Counts the number of UTF-16 code units needed to represent a string (LSP
45 // specifies string lengths in UTF-16 code units).
46 // Use of UTF-16 may be overridden by kCurrentOffsetEncoding.
47 size_t lspLength(StringRef Code);
48 
49 /// Turn a [line, column] pair into an offset in Code.
50 ///
51 /// If P.character exceeds the line length, returns the offset at end-of-line.
52 /// (If !AllowColumnsBeyondLineLength, then returns an error instead).
53 /// If the line number is out of range, returns an error.
54 ///
55 /// The returned value is in the range [0, Code.size()].
56 llvm::Expected<size_t>
57 positionToOffset(llvm::StringRef Code, Position P,
58  bool AllowColumnsBeyondLineLength = true);
59 
60 /// Turn an offset in Code into a [line, column] pair.
61 /// The offset must be in range [0, Code.size()].
62 Position offsetToPosition(llvm::StringRef Code, size_t Offset);
63 
64 /// Turn a SourceLocation into a [line, column] pair.
65 /// FIXME: This should return an error if the location is invalid.
66 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc);
67 
68 /// Returns the taken range at \p TokLoc.
69 llvm::Optional<Range> getTokenRange(const SourceManager &SM,
70  const LangOptions &LangOpts,
71  SourceLocation TokLoc);
72 
73 /// Return the file location, corresponding to \p P. Note that one should take
74 /// care to avoid comparing the result with expansion locations.
75 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
76  Position P);
77 
78 /// Turns a token range into a half-open range and checks its correctness.
79 /// The resulting range will have only valid source location on both sides, both
80 /// of which are file locations.
81 ///
82 /// File locations always point to a particular offset in a file, i.e. they
83 /// never refer to a location inside a macro expansion. Turning locations from
84 /// macro expansions into file locations is ambiguous - one can use
85 /// SourceManager::{getExpansion|getFile|getSpelling}Loc. This function
86 /// calls SourceManager::getFileLoc on both ends of \p R to do the conversion.
87 ///
88 /// User input (e.g. cursor position) is expressed as a file location, so this
89 /// function can be viewed as a way to normalize the ranges used in the clang
90 /// AST so that they are comparable with ranges coming from the user input.
91 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
92  const LangOptions &LangOpts,
93  SourceRange R);
94 
95 /// Returns true iff all of the following conditions hold:
96 /// - start and end locations are valid,
97 /// - start and end locations are file locations from the same file
98 /// (i.e. expansion locations are not taken into account).
99 /// - start offset <= end offset.
100 /// FIXME: introduce a type for source range with this invariant.
101 bool isValidFileRange(const SourceManager &Mgr, SourceRange R);
102 
103 /// Returns true iff \p L is contained in \p R.
104 /// EXPECTS: isValidFileRange(R) == true, L is a file location.
105 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
106  SourceLocation L);
107 
108 /// Returns true iff \p L is contained in \p R or \p L is equal to the end point
109 /// of \p R.
110 /// EXPECTS: isValidFileRange(R) == true, L is a file location.
111 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
112  SourceLocation L);
113 
114 /// Returns the source code covered by the source range.
115 /// EXPECTS: isValidFileRange(R) == true.
116 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R);
117 
118 // Converts a half-open clang source range to an LSP range.
119 // Note that clang also uses closed source ranges, which this can't handle!
120 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R);
121 
122 // Converts an offset to a clang line/column (1-based, columns are bytes).
123 // The offset must be in range [0, Code.size()].
124 // Prefer to use SourceManager if one is available.
125 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
126  size_t Offset);
127 
128 /// From "a::b::c", return {"a::b::", "c"}. Scope is empty if there's no
129 /// qualifier.
130 std::pair<llvm::StringRef, llvm::StringRef>
131 splitQualifiedName(llvm::StringRef QName);
132 
133 TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R);
134 
135 std::vector<TextEdit> replacementsToEdits(StringRef Code,
136  const tooling::Replacements &Repls);
137 
138 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
139  const LangOptions &L);
140 
141 /// Get the canonical path of \p F. This means:
142 ///
143 /// - Absolute path
144 /// - Symlinks resolved
145 /// - No "." or ".." component
146 /// - No duplicate or trailing directory separator
147 ///
148 /// This function should be used when paths needs to be used outside the
149 /// component that generate it, so that paths are normalized as much as
150 /// possible.
151 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
152  const SourceManager &SourceMgr);
153 
154 bool isRangeConsecutive(const Range &Left, const Range &Right);
155 
156 /// Choose the clang-format style we should apply to a certain file.
157 /// This will usually use FS to look for .clang-format directories.
158 /// FIXME: should we be caching the .clang-format file search?
159 /// This uses format::DefaultFormatStyle and format::DefaultFallbackStyle,
160 /// though the latter may have been overridden in main()!
161 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
162  llvm::StringRef Content,
163  llvm::vfs::FileSystem *FS);
164 
165 // Cleanup and format the given replacements.
166 llvm::Expected<tooling::Replacements>
167 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
168  const format::FormatStyle &Style);
169 
170 /// Collects identifiers with counts in the source code.
171 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
172  const format::FormatStyle &Style);
173 
174 /// Collects words from the source code.
175 /// Unlike collectIdentifiers:
176 /// - also finds text in comments:
177 /// - splits text into words
178 /// - drops stopwords like "get" and "for"
179 llvm::StringSet<> collectWords(llvm::StringRef Content);
180 
181 /// Heuristically determine namespaces visible at a point, without parsing Code.
182 /// This considers using-directives and enclosing namespace-declarations that
183 /// are visible (and not obfuscated) in the file itself (not headers).
184 /// Code should be truncated at the point of interest.
185 ///
186 /// The returned vector is always non-empty.
187 /// - The first element is the namespace that encloses the point: a declaration
188 /// near the point would be within this namespace.
189 /// - The elements are the namespaces in scope at the point: an unqualified
190 /// lookup would search within these namespaces.
191 ///
192 /// Using directives are resolved against all enclosing scopes, but no other
193 /// namespace directives.
194 ///
195 /// example:
196 /// using namespace a;
197 /// namespace foo {
198 /// using namespace b;
199 ///
200 /// visibleNamespaces are {"foo::", "", "a::", "b::", "foo::b::"}, not "a::b::".
201 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
202  const format::FormatStyle &Style);
203 
204 struct DefinedMacro {
205  llvm::StringRef Name;
206  const MacroInfo *Info;
207 };
208 // Gets the macro at a specified \p Loc.
209 llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
210  Preprocessor &PP);
211 
212 } // namespace clangd
213 } // namespace clang
214 #endif
SourceLocation Loc
&#39;#&#39; location in the include directive
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
Definition: SourceCode.cpp:713
llvm::Expected< tooling::Replacements > cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces, const format::FormatStyle &Style)
Definition: SourceCode.cpp:499
size_t lspLength(llvm::StringRef Code)
Definition: SourceCode.cpp:117
const MacroInfo * Info
Definition: SourceCode.h:206
std::array< uint8_t, 8 > FileDigest
Definition: SourceCode.h:35
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
Definition: SourceCode.cpp:391
bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R, SourceLocation L)
Returns true iff L is contained in R.
Definition: SourceCode.cpp:229
Values in a Context are indexed by typed keys.
Definition: Context.h:40
MockFSProvider FS
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.
Definition: SourceCode.cpp:244
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
Definition: SourceCode.cpp:363
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const format::FormatStyle &Style)
Heuristically determine namespaces visible at a point, without parsing Code.
Definition: SourceCode.cpp:663
bool isRangeConsecutive(const Range &Left, const Range &Right)
Definition: SourceCode.cpp:462
bool isValidFileRange(const SourceManager &Mgr, SourceRange R)
Returns true iff all of the following conditions hold:
Definition: SourceCode.cpp:214
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
Definition: SourceCode.cpp:381
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Definition: SourceCode.cpp:453
std::string QName
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
Definition: SourceCode.cpp:174
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Definition: SourceCode.cpp:141
Key< OffsetEncoding > kCurrentOffsetEncoding
Definition: SourceCode.cpp:110
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:203
llvm::Optional< FileDigest > digestFile(const SourceManager &SM, FileID FID)
Definition: SourceCode.cpp:477
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:186
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.
Definition: SourceCode.cpp:485
FileDigest digest(llvm::StringRef Content)
Definition: SourceCode.cpp:467
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.
Definition: SourceCode.cpp:331
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
Definition: SourceCode.cpp:352
size_t Offset
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:398
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
Definition: SourceCode.cpp:414
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
Definition: SourceCode.cpp:406
llvm::Optional< FixItHint > FixIt
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
Definition: SourceCode.cpp:522
llvm::Optional< DefinedMacro > locateMacroAt(SourceLocation Loc, Preprocessor &PP)
Definition: SourceCode.cpp:751
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:373
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))