clang-tools  10.0.0svn
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 
16 #include "Context.h"
17 #include "Protocol.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Format/Format.h"
23 #include "clang/Tooling/Core/Replacement.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/SHA1.h"
28 #include <string>
29 
30 namespace clang {
31 class SourceManager;
32 
33 namespace clangd {
34 
35 // We tend to generate digests for source codes in a lot of different places.
36 // This represents the type for those digests to prevent us hard coding details
37 // of hashing function at every place that needs to store this information.
38 using FileDigest = std::array<uint8_t, 8>;
39 FileDigest digest(StringRef Content);
40 Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
41 
42 // This context variable controls the behavior of functions in this file
43 // that convert between LSP offsets and native clang byte offsets.
44 // If not set, defaults to UTF-16 for backwards-compatibility.
46 
47 // Counts the number of UTF-16 code units needed to represent a string (LSP
48 // specifies string lengths in UTF-16 code units).
49 // Use of UTF-16 may be overridden by kCurrentOffsetEncoding.
50 size_t lspLength(StringRef Code);
51 
52 /// Turn a [line, column] pair into an offset in Code.
53 ///
54 /// If P.character exceeds the line length, returns the offset at end-of-line.
55 /// (If !AllowColumnsBeyondLineLength, then returns an error instead).
56 /// If the line number is out of range, returns an error.
57 ///
58 /// The returned value is in the range [0, Code.size()].
59 llvm::Expected<size_t>
60 positionToOffset(llvm::StringRef Code, Position P,
61  bool AllowColumnsBeyondLineLength = true);
62 
63 /// Turn an offset in Code into a [line, column] pair.
64 /// The offset must be in range [0, Code.size()].
65 Position offsetToPosition(llvm::StringRef Code, size_t Offset);
66 
67 /// Turn a SourceLocation into a [line, column] pair.
68 /// FIXME: This should return an error if the location is invalid.
69 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc);
70 
71 /// Returns the taken range at \p TokLoc.
72 llvm::Optional<Range> getTokenRange(const SourceManager &SM,
73  const LangOptions &LangOpts,
74  SourceLocation TokLoc);
75 
76 /// Return the file location, corresponding to \p P. Note that one should take
77 /// care to avoid comparing the result with expansion locations.
78 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
79  Position P);
80 
81 /// Get the beginning SourceLocation at a specified \p Pos in the main file.
82 /// May be invalid if Pos is, or if there's no identifier.
83 /// The returned position is in the main file, callers may prefer to
84 /// obtain the macro expansion location.
85 SourceLocation getBeginningOfIdentifier(const Position &Pos,
86  const SourceManager &SM,
87  const LangOptions &LangOpts);
88 
89 /// Returns true iff \p Loc is inside the main file. This function handles
90 /// file & macro locations. For macro locations, returns iff the macro is being
91 /// expanded inside the main file.
92 ///
93 /// The function is usually used to check whether a declaration is inside the
94 /// the main file.
95 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM);
96 
97 /// Returns the #include location through which IncludedFIle was loaded.
98 /// Where SM.getIncludeLoc() returns the location of the *filename*, which may
99 /// be in a macro, includeHashLoc() returns the location of the #.
100 SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM);
101 
102 /// Returns true if the token at Loc is spelled in the source code.
103 /// This is not the case for:
104 /// * symbols formed via macro concatenation, the spelling location will
105 /// be "<scratch space>"
106 /// * symbols controlled and defined by a compile command-line option
107 /// `-DName=foo`, the spelling location will be "<command line>".
108 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM);
109 
110 /// Returns the spelling location of the token at Loc if isSpelledInSource,
111 /// otherwise its expansion location.
112 /// FIXME: Most callers likely want some variant of "file location" instead.
113 SourceLocation spellingLocIfSpelled(SourceLocation Loc,
114  const SourceManager &SM);
115 
116 /// Turns a token range into a half-open range and checks its correctness.
117 /// The resulting range will have only valid source location on both sides, both
118 /// of which are file locations.
119 ///
120 /// File locations always point to a particular offset in a file, i.e. they
121 /// never refer to a location inside a macro expansion. Turning locations from
122 /// macro expansions into file locations is ambiguous - one can use
123 /// SourceManager::{getExpansion|getFile|getSpelling}Loc. This function
124 /// calls SourceManager::getFileLoc on both ends of \p R to do the conversion.
125 ///
126 /// User input (e.g. cursor position) is expressed as a file location, so this
127 /// function can be viewed as a way to normalize the ranges used in the clang
128 /// AST so that they are comparable with ranges coming from the user input.
129 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
130  const LangOptions &LangOpts,
131  SourceRange R);
132 
133 /// Returns true iff all of the following conditions hold:
134 /// - start and end locations are valid,
135 /// - start and end locations are file locations from the same file
136 /// (i.e. expansion locations are not taken into account).
137 /// - start offset <= end offset.
138 /// FIXME: introduce a type for source range with this invariant.
139 bool isValidFileRange(const SourceManager &Mgr, SourceRange R);
140 
141 /// Returns true iff \p L is contained in \p R.
142 /// EXPECTS: isValidFileRange(R) == true, L is a file location.
143 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
144  SourceLocation L);
145 
146 /// Returns true iff \p L is contained in \p R or \p L is equal to the end point
147 /// of \p R.
148 /// EXPECTS: isValidFileRange(R) == true, L is a file location.
149 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
150  SourceLocation L);
151 
152 /// Returns the source code covered by the source range.
153 /// EXPECTS: isValidFileRange(R) == true.
154 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R);
155 
156 // Converts a half-open clang source range to an LSP range.
157 // Note that clang also uses closed source ranges, which this can't handle!
158 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R);
159 
160 // Converts an offset to a clang line/column (1-based, columns are bytes).
161 // The offset must be in range [0, Code.size()].
162 // Prefer to use SourceManager if one is available.
163 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
164  size_t Offset);
165 
166 /// From "a::b::c", return {"a::b::", "c"}. Scope is empty if there's no
167 /// qualifier.
168 std::pair<llvm::StringRef, llvm::StringRef>
169 splitQualifiedName(llvm::StringRef QName);
170 
171 TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R);
172 
173 std::vector<TextEdit> replacementsToEdits(StringRef Code,
174  const tooling::Replacements &Repls);
175 
176 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
177  const LangOptions &L);
178 
179 /// Get the canonical path of \p F. This means:
180 ///
181 /// - Absolute path
182 /// - Symlinks resolved
183 /// - No "." or ".." component
184 /// - No duplicate or trailing directory separator
185 ///
186 /// This function should be used when paths needs to be used outside the
187 /// component that generate it, so that paths are normalized as much as
188 /// possible.
189 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
190  const SourceManager &SourceMgr);
191 
192 bool isRangeConsecutive(const Range &Left, const Range &Right);
193 
194 /// Choose the clang-format style we should apply to a certain file.
195 /// This will usually use FS to look for .clang-format directories.
196 /// FIXME: should we be caching the .clang-format file search?
197 /// This uses format::DefaultFormatStyle and format::DefaultFallbackStyle,
198 /// though the latter may have been overridden in main()!
199 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
200  llvm::StringRef Content,
201  llvm::vfs::FileSystem *FS);
202 
203 /// Cleanup and format the given replacements.
204 llvm::Expected<tooling::Replacements>
205 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
206  const format::FormatStyle &Style);
207 
208 /// A set of edits generated for a single file. Can verify whether it is safe to
209 /// apply these edits to a code block.
210 struct Edit {
211  tooling::Replacements Replacements;
212  std::string InitialCode;
213 
214  Edit(llvm::StringRef Code, tooling::Replacements Reps)
215  : Replacements(std::move(Reps)), InitialCode(Code) {}
216 
217  /// Returns the file contents after changes are applied.
218  llvm::Expected<std::string> apply() const;
219 
220  /// Represents Replacements as TextEdits that are available for use in LSP.
221  std::vector<TextEdit> asTextEdits() const;
222 
223  /// Checks whether the Replacements are applicable to given Code.
224  bool canApplyTo(llvm::StringRef Code) const;
225 };
226 
227 /// Formats the edits and code around it according to Style. Changes
228 /// Replacements to formatted ones if succeeds.
230 
231 /// Collects identifiers with counts in the source code.
232 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
233  const format::FormatStyle &Style);
234 
235 /// Collects words from the source code.
236 /// Unlike collectIdentifiers:
237 /// - also finds text in comments:
238 /// - splits text into words
239 /// - drops stopwords like "get" and "for"
240 llvm::StringSet<> collectWords(llvm::StringRef Content);
241 
242 /// Heuristically determine namespaces visible at a point, without parsing Code.
243 /// This considers using-directives and enclosing namespace-declarations that
244 /// are visible (and not obfuscated) in the file itself (not headers).
245 /// Code should be truncated at the point of interest.
246 ///
247 /// The returned vector is always non-empty.
248 /// - The first element is the namespace that encloses the point: a declaration
249 /// near the point would be within this namespace.
250 /// - The elements are the namespaces in scope at the point: an unqualified
251 /// lookup would search within these namespaces.
252 ///
253 /// Using directives are resolved against all enclosing scopes, but no other
254 /// namespace directives.
255 ///
256 /// example:
257 /// using namespace a;
258 /// namespace foo {
259 /// using namespace b;
260 ///
261 /// visibleNamespaces are {"foo::", "", "a::", "b::", "foo::b::"}, not "a::b::".
262 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
263  const format::FormatStyle &Style);
264 
265 struct DefinedMacro {
266  llvm::StringRef Name;
267  const MacroInfo *Info;
268 };
269 // Gets the macro at a specified \p Loc.
270 llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
271  Preprocessor &PP);
272 
273 } // namespace clangd
274 } // namespace clang
275 #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:855
std::string Code
llvm::Expected< tooling::Replacements > cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces, const format::FormatStyle &Style)
Cleanup and format the given replacements.
Definition: SourceCode.cpp:641
size_t lspLength(llvm::StringRef Code)
Definition: SourceCode.cpp:125
const MacroInfo * Info
Definition: SourceCode.h:267
std::array< uint8_t, 8 > FileDigest
Definition: SourceCode.h:38
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
Definition: SourceCode.cpp:533
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:468
llvm::Expected< std::string > apply() const
Returns the file contents after changes are applied.
Definition: SourceCode.cpp:919
SourceLocation getBeginningOfIdentifier(const Position &Pos, const SourceManager &SM, const LangOptions &LangOpts)
Get the beginning SourceLocation at a specified Pos in the main file.
Definition: SourceCode.cpp:240
bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R, SourceLocation L)
Returns true iff L is contained in R.
Definition: SourceCode.cpp:288
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:303
std::string InitialCode
Definition: SourceCode.h:212
bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM)
Returns true if the token at Loc is spelled in the source code.
Definition: SourceCode.cpp:211
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
Definition: SourceCode.cpp:505
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:805
bool isRangeConsecutive(const Range &Left, const Range &Right)
Definition: SourceCode.cpp:604
bool canApplyTo(llvm::StringRef Code) const
Checks whether the Replacements are applicable to given Code.
Definition: SourceCode.cpp:927
bool isValidFileRange(const SourceManager &Mgr, SourceRange R)
Returns true iff all of the following conditions hold:
Definition: SourceCode.cpp:273
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
Definition: SourceCode.cpp:523
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Definition: SourceCode.cpp:595
std::string QName
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
Definition: SourceCode.cpp:182
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:149
Key< OffsetEncoding > kCurrentOffsetEncoding
Definition: SourceCode.cpp:118
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:229
llvm::Optional< FileDigest > digestFile(const SourceManager &SM, FileID FID)
Definition: SourceCode.cpp:619
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:194
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:627
tooling::Replacements Replacements
Definition: SourceCode.h:211
FileDigest digest(llvm::StringRef Content)
Definition: SourceCode.cpp:609
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:472
SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM)
Returns the #include location through which IncludedFIle was loaded.
Definition: SourceCode.cpp:308
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
Definition: SourceCode.cpp:494
size_t Offset
Edit(llvm::StringRef Code, tooling::Replacements Reps)
Definition: SourceCode.h:214
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:540
SourceLocation spellingLocIfSpelled(SourceLocation Loc, const SourceManager &SM)
Returns the spelling location of the token at Loc if isSpelledInSource, otherwise its expansion locat...
Definition: SourceCode.cpp:221
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
Definition: SourceCode.cpp:556
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
Definition: SourceCode.cpp:548
std::vector< TextEdit > asTextEdits() const
Represents Replacements as TextEdits that are available for use in LSP.
Definition: SourceCode.cpp:923
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:664
llvm::Optional< DefinedMacro > locateMacroAt(SourceLocation Loc, Preprocessor &PP)
Definition: SourceCode.cpp:893
A set of edits generated for a single file.
Definition: SourceCode.h:210
llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style)
Formats the edits and code around it according to Style.
Definition: SourceCode.cpp:963
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:515
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))