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