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 "Protocol.h"
17 #include "support/Context.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 "clang/Tooling/Syntax/Tokens.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/SHA1.h"
29 #include <string>
30 
31 namespace clang {
32 class SourceManager;
33 
34 namespace clangd {
35 
36 // We tend to generate digests for source codes in a lot of different places.
37 // This represents the type for those digests to prevent us hard coding details
38 // of hashing function at every place that needs to store this information.
39 using FileDigest = std::array<uint8_t, 8>;
40 FileDigest digest(StringRef Content);
41 Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
42 
43 // This context variable controls the behavior of functions in this file
44 // that convert between LSP offsets and native clang byte offsets.
45 // If not set, defaults to UTF-16 for backwards-compatibility.
46 extern Key<OffsetEncoding> kCurrentOffsetEncoding;
47 
48 // Counts the number of UTF-16 code units needed to represent a string (LSP
49 // specifies string lengths in UTF-16 code units).
50 // Use of UTF-16 may be overridden by kCurrentOffsetEncoding.
51 size_t lspLength(StringRef Code);
52 
53 /// Turn a [line, column] pair into an offset in Code.
54 ///
55 /// If P.character exceeds the line length, returns the offset at end-of-line.
56 /// (If !AllowColumnsBeyondLineLength, then returns an error instead).
57 /// If the line number is out of range, returns an error.
58 ///
59 /// The returned value is in the range [0, Code.size()].
60 llvm::Expected<size_t>
61 positionToOffset(llvm::StringRef Code, Position P,
62                  bool AllowColumnsBeyondLineLength = true);
63 
64 /// Turn an offset in Code into a [line, column] pair.
65 /// The offset must be in range [0, Code.size()].
66 Position offsetToPosition(llvm::StringRef Code, size_t Offset);
67 
68 /// Turn a SourceLocation into a [line, column] pair.
69 /// FIXME: This should return an error if the location is invalid.
70 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc);
71 
72 /// Return the file location, corresponding to \p P. Note that one should take
73 /// care to avoid comparing the result with expansion locations.
74 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
75                                                         Position P);
76 
77 /// Returns true iff \p Loc is inside the main file. This function handles
78 /// file & macro locations. For macro locations, returns iff the macro is being
79 /// expanded inside the main file.
80 ///
81 /// The function is usually used to check whether a declaration is inside the
82 /// the main file.
83 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM);
84 
85 /// Returns the #include location through which IncludedFIle was loaded.
86 /// Where SM.getIncludeLoc() returns the location of the *filename*, which may
87 /// be in a macro, includeHashLoc() returns the location of the #.
88 SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM);
89 
90 /// Returns true if the token at Loc is spelled in the source code.
91 /// This is not the case for:
92 ///   * symbols formed via macro concatenation, the spelling location will
93 ///     be "<scratch space>"
94 ///   * symbols controlled and defined by a compile command-line option
95 ///     `-DName=foo`, the spelling location will be "<command line>".
96 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM);
97 
98 /// Turns a token range into a half-open range and checks its correctness.
99 /// The resulting range will have only valid source location on both sides, both
100 /// of which are file locations.
101 ///
102 /// File locations always point to a particular offset in a file, i.e. they
103 /// never refer to a location inside a macro expansion. Turning locations from
104 /// macro expansions into file locations is ambiguous - one can use
105 /// SourceManager::{getExpansion|getFile|getSpelling}Loc. This function
106 /// calls SourceManager::getFileLoc on both ends of \p R to do the conversion.
107 ///
108 /// User input (e.g. cursor position) is expressed as a file location, so this
109 /// function can be viewed as a way to normalize the ranges used in the clang
110 /// AST so that they are comparable with ranges coming from the user input.
111 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
112                                                 const LangOptions &LangOpts,
113                                                 SourceRange R);
114 
115 /// Returns true iff all of the following conditions hold:
116 ///   - start and end locations are valid,
117 ///   - start and end locations are file locations from the same file
118 ///     (i.e. expansion locations are not taken into account).
119 ///   - start offset <= end offset.
120 /// FIXME: introduce a type for source range with this invariant.
121 bool isValidFileRange(const SourceManager &Mgr, SourceRange R);
122 
123 /// Returns the source code covered by the source range.
124 /// EXPECTS: isValidFileRange(R) == true.
125 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R);
126 
127 // Converts a half-open clang source range to an LSP range.
128 // Note that clang also uses closed source ranges, which this can't handle!
129 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R);
130 
131 // Converts an offset to a clang line/column (1-based, columns are bytes).
132 // The offset must be in range [0, Code.size()].
133 // Prefer to use SourceManager if one is available.
134 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
135                                                   size_t Offset);
136 
137 /// From "a::b::c", return {"a::b::", "c"}. Scope is empty if there's no
138 /// qualifier.
139 std::pair<llvm::StringRef, llvm::StringRef>
140 splitQualifiedName(llvm::StringRef QName);
141 
142 TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R);
143 
144 std::vector<TextEdit> replacementsToEdits(StringRef Code,
145                                           const tooling::Replacements &Repls);
146 
147 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
148                     const LangOptions &L);
149 
150 /// Get the canonical path of \p F.  This means:
151 ///
152 ///   - Absolute path
153 ///   - Symlinks resolved
154 ///   - No "." or ".." component
155 ///   - No duplicate or trailing directory separator
156 ///
157 /// This function should be used when paths needs to be used outside the
158 /// component that generate it, so that paths are normalized as much as
159 /// possible.
160 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
161                                              const SourceManager &SourceMgr);
162 
163 /// Choose the clang-format style we should apply to a certain file.
164 /// This will usually use FS to look for .clang-format directories.
165 /// FIXME: should we be caching the .clang-format file search?
166 /// This uses format::DefaultFormatStyle and format::DefaultFallbackStyle,
167 /// though the latter may have been overridden in main()!
168 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
169                                           llvm::StringRef Content,
170                                           llvm::vfs::FileSystem *FS);
171 
172 /// Cleanup and format the given replacements.
173 llvm::Expected<tooling::Replacements>
174 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
175                  const format::FormatStyle &Style);
176 
177 /// A set of edits generated for a single file. Can verify whether it is safe to
178 /// apply these edits to a code block.
179 struct Edit {
180   tooling::Replacements Replacements;
181   std::string InitialCode;
182 
183   Edit(llvm::StringRef Code, tooling::Replacements Reps)
184       : Replacements(std::move(Reps)), InitialCode(Code) {}
185 
186   /// Returns the file contents after changes are applied.
187   llvm::Expected<std::string> apply() const;
188 
189   /// Represents Replacements as TextEdits that are available for use in LSP.
190   std::vector<TextEdit> asTextEdits() const;
191 
192   /// Checks whether the Replacements are applicable to given Code.
193   bool canApplyTo(llvm::StringRef Code) const;
194 };
195 /// A mapping from absolute file path (the one used for accessing the underlying
196 /// VFS) to edits.
197 using FileEdits = llvm::StringMap<Edit>;
198 
199 /// Formats the edits and code around it according to Style. Changes
200 /// Replacements to formatted ones if succeeds.
201 llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style);
202 
203 /// Collects identifiers with counts in the source code.
204 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
205                                              const format::FormatStyle &Style);
206 
207 /// Collects all ranges of the given identifier in the source code.
208 std::vector<Range> collectIdentifierRanges(llvm::StringRef Identifier,
209                                            llvm::StringRef Content,
210                                            const LangOptions &LangOpts);
211 
212 /// Collects words from the source code.
213 /// Unlike collectIdentifiers:
214 /// - also finds text in comments:
215 /// - splits text into words
216 /// - drops stopwords like "get" and "for"
217 llvm::StringSet<> collectWords(llvm::StringRef Content);
218 
219 // Something that looks like a word in the source code.
220 // Could be a "real" token that's "live" in the AST, a spelled token consumed by
221 // the preprocessor, or part of a spelled token (e.g. word in a comment).
222 struct SpelledWord {
223   // (Spelling) location of the start of the word.
224   SourceLocation Location;
225   // The range of the word itself, excluding any quotes.
226   // This is a subrange of the file buffer.
227   llvm::StringRef Text;
228   // Whether this word is likely to refer to an identifier. True if:
229   // - the word is a spelled identifier token
230   // - Text is identifier-like (e.g. "foo_bar")
231   // - Text is surrounded by backticks (e.g. Foo in "// returns `Foo`")
232   bool LikelyIdentifier = false;
233   // Set if the word is contained in a token spelled in the file.
234   // (This should always be true, but comments aren't retained by TokenBuffer).
235   const syntax::Token *PartOfSpelledToken = nullptr;
236   // Set if the word is exactly a token spelled in the file.
237   const syntax::Token *SpelledToken = nullptr;
238   // Set if the word is a token spelled in the file, and that token survives
239   // preprocessing to emit an expanded token spelled the same way.
240   const syntax::Token *ExpandedToken = nullptr;
241 
242   // Find the unique word that contains SpelledLoc or starts/ends there.
243   static llvm::Optional<SpelledWord> touching(SourceLocation SpelledLoc,
244                                               const syntax::TokenBuffer &TB,
245                                               const LangOptions &LangOpts);
246 };
247 
248 /// Heuristically determine namespaces visible at a point, without parsing Code.
249 /// This considers using-directives and enclosing namespace-declarations that
250 /// are visible (and not obfuscated) in the file itself (not headers).
251 /// Code should be truncated at the point of interest.
252 ///
253 /// The returned vector is always non-empty.
254 /// - The first element is the namespace that encloses the point: a declaration
255 ///   near the point would be within this namespace.
256 /// - The elements are the namespaces in scope at the point: an unqualified
257 ///   lookup would search within these namespaces.
258 ///
259 /// Using directives are resolved against all enclosing scopes, but no other
260 /// namespace directives.
261 ///
262 /// example:
263 ///   using namespace a;
264 ///   namespace foo {
265 ///     using namespace b;
266 ///
267 /// visibleNamespaces are {"foo::", "", "a::", "b::", "foo::b::"}, not "a::b::".
268 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
269                                            const LangOptions &LangOpts);
270 
271 /// Represents locations that can accept a definition.
272 struct EligibleRegion {
273   /// Namespace that owns all of the EligiblePoints, e.g.
274   /// namespace a{ namespace b {^ void foo();^} }
275   /// It will be “a::b” for both carrot locations.
276   std::string EnclosingNamespace;
277   /// Offsets into the code marking eligible points to insert a function
278   /// definition.
279   std::vector<Position> EligiblePoints;
280 };
281 
282 /// Returns most eligible region to insert a definition for \p
283 /// FullyQualifiedName in the \p Code.
284 /// Pseudo parses \pCode under the hood to determine namespace decls and
285 /// possible insertion points. Choses the region that matches the longest prefix
286 /// of \p FullyQualifiedName. Returns EOF if there are no shared namespaces.
287 /// \p FullyQualifiedName should not contain anonymous namespaces.
288 EligibleRegion getEligiblePoints(llvm::StringRef Code,
289                                  llvm::StringRef FullyQualifiedName,
290                                  const LangOptions &LangOpts);
291 
292 struct DefinedMacro {
293   llvm::StringRef Name;
294   const MacroInfo *Info;
295 };
296 /// Gets the macro referenced by \p SpelledTok. It must be a spelled token
297 /// aligned to the beginning of an identifier.
298 llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
299                                            Preprocessor &PP);
300 
301 /// Infers whether this is a header from the FileName and LangOpts (if
302 /// presents).
303 bool isHeaderFile(llvm::StringRef FileName,
304                   llvm::Optional<LangOptions> LangOpts = llvm::None);
305 
306 /// Returns true if the given location is in a generated protobuf file.
307 bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);
308 
309 } // namespace clangd
310 } // namespace clang
311 #endif
312