LLDB mainline
FileSpec.h
Go to the documentation of this file.
1//===-- FileSpec.h ----------------------------------------------*- 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#ifndef LLDB_UTILITY_FILESPEC_H
10#define LLDB_UTILITY_FILESPEC_H
11
12#include <functional>
13#include <optional>
14#include <string>
15
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/FormatVariadic.h"
20#include "llvm/Support/JSON.h"
21#include "llvm/Support/Path.h"
22
23#include <cstddef>
24#include <cstdint>
25
26namespace lldb_private {
27class Stream;
28}
29namespace llvm {
30class Triple;
31}
32namespace llvm {
33class raw_ostream;
34}
35namespace llvm {
36template <typename T> class SmallVectorImpl;
37}
38
39namespace lldb_private {
40
41/// \class FileSpec FileSpec.h "lldb/Utility/FileSpec.h"
42/// A file utility class.
43///
44/// A file specification class that divides paths up into a directory
45/// and basename. These string values of the paths are put into uniqued string
46/// pools for fast comparisons and efficient memory usage.
47///
48/// Another reason the paths are split into the directory and basename is to
49/// allow efficient debugger searching. Often in a debugger the user types in
50/// the basename of the file, for example setting a breakpoint by file and
51/// line, or specifying a module (shared library) to limit the scope in which
52/// to execute a command. The user rarely types in a full path. When the paths
53/// are already split up, it makes it easy for us to compare only the
54/// basenames of a lot of file specifications without having to split up the
55/// file path each time to get to the basename.
56class FileSpec {
57public:
58 using Style = llvm::sys::path::Style;
59
60 FileSpec();
61
62 /// Constructor with path.
63 ///
64 /// Takes a path to a file which can be just a filename, or a full path. If
65 /// \a path is not nullptr or empty, this function will call
66 /// FileSpec::SetFile (const char *path).
67 ///
68 /// \param[in] path
69 /// The full or partial path to a file.
70 ///
71 /// \param[in] style
72 /// The style of the path
73 ///
74 /// \see FileSpec::SetFile (const char *path)
75 explicit FileSpec(llvm::StringRef path, Style style = Style::native);
76
77 explicit FileSpec(llvm::StringRef path, const llvm::Triple &triple);
78
79 bool DirectoryEquals(const FileSpec &other) const;
80
81 bool FileEquals(const FileSpec &other) const;
82
83 /// Equal to operator
84 ///
85 /// Tests if this object is equal to \a rhs.
86 ///
87 /// \param[in] rhs
88 /// A const FileSpec object reference to compare this object
89 /// to.
90 ///
91 /// \return
92 /// \b true if this object is equal to \a rhs, \b false
93 /// otherwise.
94 bool operator==(const FileSpec &rhs) const;
95
96 /// Not equal to operator
97 ///
98 /// Tests if this object is not equal to \a rhs.
99 ///
100 /// \param[in] rhs
101 /// A const FileSpec object reference to compare this object
102 /// to.
103 ///
104 /// \return
105 /// \b true if this object is equal to \a rhs, \b false
106 /// otherwise.
107 bool operator!=(const FileSpec &rhs) const;
108
109 /// Less than to operator
110 ///
111 /// Tests if this object is less than \a rhs.
112 ///
113 /// \param[in] rhs
114 /// A const FileSpec object reference to compare this object
115 /// to.
116 ///
117 /// \return
118 /// \b true if this object is less than \a rhs, \b false
119 /// otherwise.
120 bool operator<(const FileSpec &rhs) const;
121
122 /// Convert to pointer operator.
123 ///
124 /// This allows code to check a FileSpec object to see if it contains
125 /// anything valid using code such as:
126 ///
127 /// \code
128 /// FileSpec file_spec(...);
129 /// if (file_spec)
130 /// { ...
131 /// \endcode
132 ///
133 /// \return
134 /// A pointer to this object if either the directory or filename
135 /// is valid, nullptr otherwise.
136 explicit operator bool() const;
137
138 /// Logical NOT operator.
139 ///
140 /// This allows code to check a FileSpec object to see if it is invalid
141 /// using code such as:
142 ///
143 /// \code
144 /// FileSpec file_spec(...);
145 /// if (!file_spec)
146 /// { ...
147 /// \endcode
148 ///
149 /// \return
150 /// Returns \b true if the object has an empty directory and
151 /// filename, \b false otherwise.
152 bool operator!() const;
153
154 /// Clears the object state.
155 ///
156 /// Clear this object by releasing both the directory and filename string
157 /// values and reverting them to empty strings.
158 void Clear();
159
160 /// Compare two FileSpec objects.
161 ///
162 /// If \a full is true, then both the directory and the filename must match.
163 /// If \a full is false, then the directory names for \a lhs and \a rhs are
164 /// only compared if they are both not empty. This allows a FileSpec object
165 /// to only contain a filename and it can match FileSpec objects that have
166 /// matching filenames with different paths.
167 ///
168 /// \param[in] lhs
169 /// A const reference to the Left Hand Side object to compare.
170 ///
171 /// \param[in] rhs
172 /// A const reference to the Right Hand Side object to compare.
173 ///
174 /// \param[in] full
175 /// If true, then both the directory and filenames will have to
176 /// match for a compare to return zero (equal to). If false
177 /// and either directory from \a lhs or \a rhs is empty, then
178 /// only the filename will be compared, else a full comparison
179 /// is done.
180 ///
181 /// \return -1 if \a lhs is less than \a rhs, 0 if \a lhs is equal to \a rhs,
182 /// 1 if \a lhs is greater than \a rhs
183 static int Compare(const FileSpec &lhs, const FileSpec &rhs, bool full);
184
185 static bool Equal(const FileSpec &a, const FileSpec &b, bool full);
186
187 /// Match FileSpec \a pattern against FileSpec \a file. If \a pattern has a
188 /// directory component, then the \a file must have the same directory
189 /// component. Otherwise, just it matches just the filename. An empty \a
190 /// pattern matches everything.
191 static bool Match(const FileSpec &pattern, const FileSpec &file);
192
193 /// Attempt to guess path style for a given path string. It returns a style,
194 /// if it was able to make a reasonable guess, or std::nullopt if it wasn't.
195 /// The guess will be correct if the input path was a valid absolute path on
196 /// the system which produced it. On other paths the result of this function
197 /// is unreliable (e.g. "c:\foo.txt" is a valid relative posix path).
198 static std::optional<Style> GuessPathStyle(llvm::StringRef absolute_path);
199
200 /// Case sensitivity of path.
201 ///
202 /// \return
203 /// \b true if the file path is case sensitive (POSIX), false
204 /// if case insensitive (Windows).
205 bool IsCaseSensitive() const { return is_style_posix(m_style); }
206
207 /// Dump this object to a Stream.
208 ///
209 /// Dump the object to the supplied stream \a s. If the object contains a
210 /// valid directory name, it will be displayed followed by a directory
211 /// delimiter, and the filename.
212 ///
213 /// \param[in] s
214 /// The stream to which to dump the object description.
215 void Dump(llvm::raw_ostream &s) const;
216
217 /// Convert the filespec object to a json value.
218 ///
219 /// Convert the filespec object to a json value. If the object contains a
220 /// valid directory name, it will be displayed followed by a directory
221 /// delimiter, and the filename.
222 ///
223 /// \return
224 /// A json value representation of a filespec.
225 llvm::json::Value ToJSON() const;
226
227 Style GetPathStyle() const;
228
229 /// Directory string const get accessor.
230 ///
231 /// \return
232 /// A const reference to the directory string object.
233 llvm::StringRef GetDirectory() const { return m_directory; }
234
235 /// Directory string set accessor.
236 ///
237 /// \param[in] directory
238 /// The value to replace the directory with.
239 void SetDirectory(llvm::StringRef directory);
240
241 /// Clear the directory in this object.
242 void ClearDirectory();
243
244 /// Filename string const get accessor.
245 ///
246 /// \return
247 /// A const reference to the filename string object.
248 llvm::StringRef GetFilename() const { return m_filename; }
249
250 /// Filename string set accessor.
251 ///
252 /// \param[in] filename
253 /// The const string to replace the directory with.
254 void SetFilename(llvm::StringRef filename);
255
256 /// Clear the filename in this object.
257 void ClearFilename();
258
259 /// Returns true if the filespec represents an implementation source file
260 /// (files with a ".c", ".cpp", ".m", ".mm" (many more) extension).
261 ///
262 /// \return
263 /// \b true if the FileSpec represents an implementation source
264 /// file, \b false otherwise.
265 bool IsSourceImplementationFile() const;
266
267 /// Returns true if the filespec represents a relative path.
268 ///
269 /// \return
270 /// \b true if the filespec represents a relative path,
271 /// \b false otherwise.
272 bool IsRelative() const;
273
274 /// Returns true if the filespec represents an absolute path.
275 ///
276 /// \return
277 /// \b true if the filespec represents an absolute path,
278 /// \b false otherwise.
279 bool IsAbsolute() const;
280
281 /// Make the FileSpec absolute by treating it relative to \a dir. Absolute
282 /// FileSpecs are never changed by this function.
283 void MakeAbsolute(const FileSpec &dir);
284
285 /// Temporary helper for FileSystem change.
286 void SetPath(llvm::StringRef p) { SetFile(p); }
287
288 /// Extract the full path to the file.
289 ///
290 /// Extract the directory and path into a fixed buffer. This is needed as
291 /// the directory and path are stored in separate string values.
292 ///
293 /// \param[out] path
294 /// The buffer in which to place the extracted full path.
295 ///
296 /// \param[in] max_path_length
297 /// The maximum length of \a path.
298 ///
299 /// \return
300 /// Returns the number of characters that would be needed to
301 /// properly copy the full path into \a path. If the returned
302 /// number is less than \a max_path_length, then the path is
303 /// properly copied and terminated. If the return value is
304 /// >= \a max_path_length, then the path was truncated (but is
305 /// still NULL terminated).
306 size_t GetPath(char *path, size_t max_path_length,
307 bool denormalize = true) const;
308
309 /// Extract the full path to the file.
310 ///
311 /// Extract the directory and path into a std::string, which is returned.
312 ///
313 /// \return
314 /// Returns a std::string with the directory and filename
315 /// concatenated.
316 std::string GetPath(bool denormalize = true) const;
317
318 /// Extract the full path to the file.
319 ///
320 /// Extract the directory and path into an llvm::SmallVectorImpl<>
322 bool denormalize = true) const;
323
324 /// Extract the extension of the file.
325 ///
326 /// Returns a StringRef that represents the extension of the filename for
327 /// this FileSpec object. If this object does not represent a file, or the
328 /// filename has no extension, an empty StringRef is returned. The dot
329 /// ('.') character is the first character in the returned string.
330 ///
331 /// \return Returns the extension of the file as a StringRef.
332 llvm::StringRef GetFileNameExtension() const;
333
334 /// Return the filename without the extension part
335 ///
336 /// Returns a StringRef that represents the filename of this object
337 /// without the extension part (e.g. for a file named "foo.bar", "foo" is
338 /// returned)
339 ///
340 /// \return Returns the filename without extension as a StringRef object.
341 llvm::StringRef GetFileNameStrippingExtension() const;
342
343 /// Get the memory cost of this object.
344 ///
345 /// Return the size in bytes that this object takes in memory. This returns
346 /// the size in bytes of this object, not any shared string values it may
347 /// refer to.
348 ///
349 /// \return
350 /// The number of bytes that this object occupies in memory.
351 size_t MemorySize() const;
352
353 /// Change the file specified with a new path.
354 ///
355 /// Update the contents of this object with a new path. The path will be
356 /// split up into a directory and filename and stored as uniqued string
357 /// values for quick comparison and efficient memory usage.
358 ///
359 /// \param[in] path
360 /// A full, partial, or relative path to a file.
361 ///
362 /// \param[in] style
363 /// The style for the given path.
364 void SetFile(llvm::StringRef path, Style style);
365
366 /// Change the file specified with a new path.
367 ///
368 /// Update the contents of this object with a new path. The path will be
369 /// split up into a directory and filename and stored as uniqued string
370 /// values for quick comparison and efficient memory usage.
371 ///
372 /// \param[in] path
373 /// A full, partial, or relative path to a file.
374 ///
375 /// \param[in] triple
376 /// The triple which is used to set the Path style.
377 void SetFile(llvm::StringRef path, const llvm::Triple &triple);
378
379 FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const;
381
382 void PrependPathComponent(llvm::StringRef component);
383 void PrependPathComponent(const FileSpec &new_path);
384
385 void AppendPathComponent(llvm::StringRef component);
386 void AppendPathComponent(const FileSpec &new_path);
387
388 /// Removes the last path component by replacing the current path with its
389 /// parent. When the current path has no parent, this is a no-op.
390 ///
391 /// \return
392 /// A boolean value indicating whether the path was updated.
394
395 /// Gets the components of the FileSpec's path.
396 /// For example, given the path:
397 /// /System/Library/PrivateFrameworks/UIFoundation.framework/UIFoundation
398 ///
399 /// This function returns:
400 /// {"System", "Library", "PrivateFrameworks", "UIFoundation.framework",
401 /// "UIFoundation"}
402 /// \return
403 /// A std::vector of llvm::StringRefs for each path component.
404 /// The lifetime of the StringRefs is tied to the lifetime of the FileSpec.
405 std::vector<llvm::StringRef> GetComponents() const;
406
407protected:
408 static constexpr size_t directory_size = 256;
409 static constexpr size_t filename_size = 32;
410
411 // Convenience method for setting the file without changing the style.
412 void SetFile(llvm::StringRef path);
413
414 /// Called anytime m_directory or m_filename is changed to clear any cached
415 /// state in this object.
417
418 enum class Absolute : uint8_t { Calculate, Yes, No };
419
420 /// The unique'd directory path.
421 llvm::SmallString<directory_size> m_directory;
422
423 /// The unique'd filename path.
424 llvm::SmallString<filename_size> m_filename;
425
426 /// Cache whether this path is absolute.
428
429 /// The syntax that this path uses. (e.g. Windows / Posix)
431};
432
433/// Dump a FileSpec object to a stream
434Stream &operator<<(Stream &s, const FileSpec &f);
435} // namespace lldb_private
436
437namespace llvm {
438
439/// Implementation of format_provider<T> for FileSpec.
440///
441/// The options string of a FileSpec has the grammar:
442///
443/// file_spec_options :: (empty) | F | D
444///
445/// =======================================================
446/// | style | Meaning | Example |
447/// -------------------------------------------------------
448/// | | | Input | Output |
449/// =======================================================
450/// | F | Only print filename | /foo/bar | bar |
451/// | D | Only print directory | /foo/bar | /foo/ |
452/// | (empty) | Print file and dir | | |
453/// =======================================================
454///
455/// Any other value is considered an invalid format string.
456///
457template <> struct format_provider<lldb_private::FileSpec> {
458 static void format(const lldb_private::FileSpec &F, llvm::raw_ostream &Stream,
459 StringRef Style);
460};
461
462/// DenseMapInfo implementation.
463/// \{
464template <> struct DenseMapInfo<lldb_private::FileSpec> {
465 static unsigned getHashValue(lldb_private::FileSpec file_spec) {
466 return llvm::hash_combine(
467 DenseMapInfo<llvm::StringRef>::getHashValue(file_spec.GetDirectory()),
468 DenseMapInfo<llvm::StringRef>::getHashValue(file_spec.GetFilename()),
469 DenseMapInfo<llvm::sys::path::Style>::getHashValue(
470 file_spec.GetPathStyle()));
471 }
473 return LHS == RHS;
474 }
475};
476/// \}
477
478} // namespace llvm
479
480#endif // LLDB_UTILITY_FILESPEC_H
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
llvm::SmallString< filename_size > m_filename
The unique'd filename path.
Definition FileSpec.h:424
static bool Equal(const FileSpec &a, const FileSpec &b, bool full)
Definition FileSpec.cpp:310
llvm::SmallString< directory_size > m_directory
The unique'd directory path.
Definition FileSpec.h:421
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:326
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:317
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:514
bool FileEquals(const FileSpec &other) const
Definition FileSpec.cpp:238
bool operator<(const FileSpec &rhs) const
Less than to operator.
Definition FileSpec.cpp:253
bool RemoveLastPathComponent()
Removes the last path component by replacing the current path with its parent.
Definition FileSpec.cpp:465
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
void MakeAbsolute(const FileSpec &dir)
Make the FileSpec absolute by treating it relative to dir.
Definition FileSpec.cpp:537
bool operator!() const
Logical NOT operator.
Definition FileSpec.cpp:228
std::vector< llvm::StringRef > GetComponents() const
Gets the components of the FileSpec's path.
Definition FileSpec.cpp:475
void ClearDirectory()
Clear the directory in this object.
Definition FileSpec.cpp:373
bool IsCaseSensitive() const
Case sensitivity of path.
Definition FileSpec.h:205
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition FileSpec.h:286
bool DirectoryEquals(const FileSpec &other) const
Definition FileSpec.cpp:232
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
bool IsAbsolute() const
Returns true if the filespec represents an absolute path.
Definition FileSpec.cpp:518
Style GetPathStyle() const
Definition FileSpec.cpp:356
void PathWasModified()
Called anytime m_directory or m_filename is changed to clear any cached state in this object.
Definition FileSpec.h:416
size_t MemorySize() const
Get the memory cost of this object.
Definition FileSpec.cpp:420
static int Compare(const FileSpec &lhs, const FileSpec &rhs, bool full)
Compare two FileSpec objects.
Definition FileSpec.cpp:279
llvm::json::Value ToJSON() const
Convert the filespec object to a json value.
Definition FileSpec.cpp:349
Style m_style
The syntax that this path uses. (e.g. Windows / Posix)
Definition FileSpec.h:430
void PrependPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:440
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
static constexpr size_t filename_size
Definition FileSpec.h:409
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
static constexpr size_t directory_size
Definition FileSpec.h:408
Absolute m_absolute
Cache whether this path is absolute.
Definition FileSpec.h:427
bool operator!=(const FileSpec &rhs) const
Not equal to operator.
Definition FileSpec.cpp:250
void SetDirectory(llvm::StringRef directory)
Directory string set accessor.
Definition FileSpec.cpp:358
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:341
bool IsSourceImplementationFile() const
Returns true if the filespec represents an implementation source file (files with a "....
Definition FileSpec.cpp:501
bool operator==(const FileSpec &rhs) const
Equal to operator.
Definition FileSpec.cpp:245
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:431
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:410
llvm::sys::path::Style Style
Definition FileSpec.h:58
void ClearFilename()
Clear the filename in this object.
Definition FileSpec.cpp:368
A stream class that can stream formatted output to a file.
Definition Stream.h:28
A class that represents a running process on the host machine.
Stream & operator<<(Stream &s, const Mangled &obj)
static unsigned getHashValue(lldb_private::FileSpec file_spec)
Definition FileSpec.h:465
static bool isEqual(lldb_private::FileSpec LHS, lldb_private::FileSpec RHS)
Definition FileSpec.h:472
static void format(const lldb_private::FileSpec &F, llvm::raw_ostream &Stream, StringRef Style)