xref: /openbsd-src/gnu/llvm/lldb/source/Utility/FileSpec.cpp (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1dda28197Spatrick //===-- FileSpec.cpp ------------------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9061da546Spatrick #include "lldb/Utility/FileSpec.h"
10061da546Spatrick #include "lldb/Utility/RegularExpression.h"
11061da546Spatrick #include "lldb/Utility/Stream.h"
12061da546Spatrick 
13061da546Spatrick #include "llvm/ADT/SmallString.h"
14061da546Spatrick #include "llvm/ADT/SmallVector.h"
15061da546Spatrick #include "llvm/ADT/StringRef.h"
16061da546Spatrick #include "llvm/ADT/Triple.h"
17061da546Spatrick #include "llvm/ADT/Twine.h"
18061da546Spatrick #include "llvm/Support/ErrorOr.h"
19061da546Spatrick #include "llvm/Support/FileSystem.h"
20061da546Spatrick #include "llvm/Support/Program.h"
21061da546Spatrick #include "llvm/Support/raw_ostream.h"
22061da546Spatrick 
23061da546Spatrick #include <algorithm>
24*f6aab3d8Srobert #include <optional>
25061da546Spatrick #include <system_error>
26061da546Spatrick #include <vector>
27061da546Spatrick 
28be691f3bSpatrick #include <cassert>
29be691f3bSpatrick #include <climits>
30be691f3bSpatrick #include <cstdio>
31be691f3bSpatrick #include <cstring>
32061da546Spatrick 
33061da546Spatrick using namespace lldb;
34061da546Spatrick using namespace lldb_private;
35061da546Spatrick 
36061da546Spatrick namespace {
37061da546Spatrick 
GetNativeStyle()38061da546Spatrick static constexpr FileSpec::Style GetNativeStyle() {
39061da546Spatrick #if defined(_WIN32)
40061da546Spatrick   return FileSpec::Style::windows;
41061da546Spatrick #else
42061da546Spatrick   return FileSpec::Style::posix;
43061da546Spatrick #endif
44061da546Spatrick }
45061da546Spatrick 
PathStyleIsPosix(FileSpec::Style style)46061da546Spatrick bool PathStyleIsPosix(FileSpec::Style style) {
47*f6aab3d8Srobert   return llvm::sys::path::is_style_posix(style);
48061da546Spatrick }
49061da546Spatrick 
GetPathSeparators(FileSpec::Style style)50061da546Spatrick const char *GetPathSeparators(FileSpec::Style style) {
51061da546Spatrick   return llvm::sys::path::get_separator(style).data();
52061da546Spatrick }
53061da546Spatrick 
GetPreferredPathSeparator(FileSpec::Style style)54061da546Spatrick char GetPreferredPathSeparator(FileSpec::Style style) {
55061da546Spatrick   return GetPathSeparators(style)[0];
56061da546Spatrick }
57061da546Spatrick 
Denormalize(llvm::SmallVectorImpl<char> & path,FileSpec::Style style)58061da546Spatrick void Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::Style style) {
59061da546Spatrick   if (PathStyleIsPosix(style))
60061da546Spatrick     return;
61061da546Spatrick 
62061da546Spatrick   std::replace(path.begin(), path.end(), '/', '\\');
63061da546Spatrick }
64061da546Spatrick 
65061da546Spatrick } // end anonymous namespace
66061da546Spatrick 
FileSpec()67061da546Spatrick FileSpec::FileSpec() : m_style(GetNativeStyle()) {}
68061da546Spatrick 
69061da546Spatrick // Default constructor that can take an optional full path to a file on disk.
FileSpec(llvm::StringRef path,Style style)70061da546Spatrick FileSpec::FileSpec(llvm::StringRef path, Style style) : m_style(style) {
71061da546Spatrick   SetFile(path, style);
72061da546Spatrick }
73061da546Spatrick 
FileSpec(llvm::StringRef path,const llvm::Triple & triple)74061da546Spatrick FileSpec::FileSpec(llvm::StringRef path, const llvm::Triple &triple)
75061da546Spatrick     : FileSpec{path, triple.isOSWindows() ? Style::windows : Style::posix} {}
76061da546Spatrick 
77061da546Spatrick namespace {
78061da546Spatrick /// Safely get a character at the specified index.
79061da546Spatrick ///
80061da546Spatrick /// \param[in] path
81061da546Spatrick ///     A full, partial, or relative path to a file.
82061da546Spatrick ///
83061da546Spatrick /// \param[in] i
84061da546Spatrick ///     An index into path which may or may not be valid.
85061da546Spatrick ///
86061da546Spatrick /// \return
87061da546Spatrick ///   The character at index \a i if the index is valid, or 0 if
88061da546Spatrick ///   the index is not valid.
safeCharAtIndex(const llvm::StringRef & path,size_t i)89061da546Spatrick inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
90061da546Spatrick   if (i < path.size())
91061da546Spatrick     return path[i];
92061da546Spatrick   return 0;
93061da546Spatrick }
94061da546Spatrick 
95061da546Spatrick /// Check if a path needs to be normalized.
96061da546Spatrick ///
97061da546Spatrick /// Check if a path needs to be normalized. We currently consider a
98061da546Spatrick /// path to need normalization if any of the following are true
99061da546Spatrick ///  - path contains "/./"
100061da546Spatrick ///  - path contains "/../"
101061da546Spatrick ///  - path contains "//"
102061da546Spatrick ///  - path ends with "/"
103061da546Spatrick /// Paths that start with "./" or with "../" are not considered to
104061da546Spatrick /// need normalization since we aren't trying to resolve the path,
105061da546Spatrick /// we are just trying to remove redundant things from the path.
106061da546Spatrick ///
107061da546Spatrick /// \param[in] path
108061da546Spatrick ///     A full, partial, or relative path to a file.
109061da546Spatrick ///
110061da546Spatrick /// \return
111061da546Spatrick ///   Returns \b true if the path needs to be normalized.
needsNormalization(const llvm::StringRef & path)112061da546Spatrick bool needsNormalization(const llvm::StringRef &path) {
113061da546Spatrick   if (path.empty())
114061da546Spatrick     return false;
115061da546Spatrick   // We strip off leading "." values so these paths need to be normalized
116061da546Spatrick   if (path[0] == '.')
117061da546Spatrick     return true;
118061da546Spatrick   for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
119061da546Spatrick        i = path.find_first_of("\\/", i + 1)) {
120061da546Spatrick     const auto next = safeCharAtIndex(path, i+1);
121061da546Spatrick     switch (next) {
122061da546Spatrick       case 0:
123061da546Spatrick         // path separator char at the end of the string which should be
124061da546Spatrick         // stripped unless it is the one and only character
125061da546Spatrick         return i > 0;
126061da546Spatrick       case '/':
127061da546Spatrick       case '\\':
128061da546Spatrick         // two path separator chars in the middle of a path needs to be
129061da546Spatrick         // normalized
130061da546Spatrick         if (i > 0)
131061da546Spatrick           return true;
132061da546Spatrick         ++i;
133061da546Spatrick         break;
134061da546Spatrick 
135061da546Spatrick       case '.': {
136061da546Spatrick           const auto next_next = safeCharAtIndex(path, i+2);
137061da546Spatrick           switch (next_next) {
138061da546Spatrick             default: break;
139061da546Spatrick             case 0: return true; // ends with "/."
140061da546Spatrick             case '/':
141061da546Spatrick             case '\\':
142061da546Spatrick               return true; // contains "/./"
143061da546Spatrick             case '.': {
144061da546Spatrick               const auto next_next_next = safeCharAtIndex(path, i+3);
145061da546Spatrick               switch (next_next_next) {
146061da546Spatrick                 default: break;
147061da546Spatrick                 case 0: return true; // ends with "/.."
148061da546Spatrick                 case '/':
149061da546Spatrick                 case '\\':
150061da546Spatrick                   return true; // contains "/../"
151061da546Spatrick               }
152061da546Spatrick               break;
153061da546Spatrick             }
154061da546Spatrick           }
155061da546Spatrick         }
156061da546Spatrick         break;
157061da546Spatrick 
158061da546Spatrick       default:
159061da546Spatrick         break;
160061da546Spatrick     }
161061da546Spatrick   }
162061da546Spatrick   return false;
163061da546Spatrick }
164061da546Spatrick 
165061da546Spatrick 
166061da546Spatrick }
167061da546Spatrick 
SetFile(llvm::StringRef pathname)168061da546Spatrick void FileSpec::SetFile(llvm::StringRef pathname) { SetFile(pathname, m_style); }
169061da546Spatrick 
170061da546Spatrick // Update the contents of this object with a new path. The path will be split
171061da546Spatrick // up into a directory and filename and stored as uniqued string values for
172061da546Spatrick // quick comparison and efficient memory usage.
SetFile(llvm::StringRef pathname,Style style)173061da546Spatrick void FileSpec::SetFile(llvm::StringRef pathname, Style style) {
174*f6aab3d8Srobert   Clear();
175061da546Spatrick   m_style = (style == Style::native) ? GetNativeStyle() : style;
176061da546Spatrick 
177061da546Spatrick   if (pathname.empty())
178061da546Spatrick     return;
179061da546Spatrick 
180061da546Spatrick   llvm::SmallString<128> resolved(pathname);
181061da546Spatrick 
182061da546Spatrick   // Normalize the path by removing ".", ".." and other redundant components.
183061da546Spatrick   if (needsNormalization(resolved))
184061da546Spatrick     llvm::sys::path::remove_dots(resolved, true, m_style);
185061da546Spatrick 
186061da546Spatrick   // Normalize back slashes to forward slashes
187061da546Spatrick   if (m_style == Style::windows)
188061da546Spatrick     std::replace(resolved.begin(), resolved.end(), '\\', '/');
189061da546Spatrick 
190061da546Spatrick   if (resolved.empty()) {
191061da546Spatrick     // If we have no path after normalization set the path to the current
192061da546Spatrick     // directory. This matches what python does and also a few other path
193061da546Spatrick     // utilities.
194061da546Spatrick     m_filename.SetString(".");
195061da546Spatrick     return;
196061da546Spatrick   }
197061da546Spatrick 
198061da546Spatrick   // Split path into filename and directory. We rely on the underlying char
199061da546Spatrick   // pointer to be nullptr when the components are empty.
200061da546Spatrick   llvm::StringRef filename = llvm::sys::path::filename(resolved, m_style);
201061da546Spatrick   if(!filename.empty())
202061da546Spatrick     m_filename.SetString(filename);
203061da546Spatrick 
204061da546Spatrick   llvm::StringRef directory = llvm::sys::path::parent_path(resolved, m_style);
205061da546Spatrick   if(!directory.empty())
206061da546Spatrick     m_directory.SetString(directory);
207061da546Spatrick }
208061da546Spatrick 
SetFile(llvm::StringRef path,const llvm::Triple & triple)209061da546Spatrick void FileSpec::SetFile(llvm::StringRef path, const llvm::Triple &triple) {
210061da546Spatrick   return SetFile(path, triple.isOSWindows() ? Style::windows : Style::posix);
211061da546Spatrick }
212061da546Spatrick 
213061da546Spatrick // Convert to pointer operator. This allows code to check any FileSpec objects
214061da546Spatrick // to see if they contain anything valid using code such as:
215061da546Spatrick //
216061da546Spatrick //  if (file_spec)
217061da546Spatrick //  {}
operator bool() const218061da546Spatrick FileSpec::operator bool() const { return m_filename || m_directory; }
219061da546Spatrick 
220061da546Spatrick // Logical NOT operator. This allows code to check any FileSpec objects to see
221061da546Spatrick // if they are invalid using code such as:
222061da546Spatrick //
223061da546Spatrick //  if (!file_spec)
224061da546Spatrick //  {}
operator !() const225061da546Spatrick bool FileSpec::operator!() const { return !m_directory && !m_filename; }
226061da546Spatrick 
DirectoryEquals(const FileSpec & rhs) const227061da546Spatrick bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
228061da546Spatrick   const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
229061da546Spatrick   return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
230061da546Spatrick }
231061da546Spatrick 
FileEquals(const FileSpec & rhs) const232061da546Spatrick bool FileSpec::FileEquals(const FileSpec &rhs) const {
233061da546Spatrick   const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
234061da546Spatrick   return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
235061da546Spatrick }
236061da546Spatrick 
237061da546Spatrick // Equal to operator
operator ==(const FileSpec & rhs) const238061da546Spatrick bool FileSpec::operator==(const FileSpec &rhs) const {
239061da546Spatrick   return FileEquals(rhs) && DirectoryEquals(rhs);
240061da546Spatrick }
241061da546Spatrick 
242061da546Spatrick // Not equal to operator
operator !=(const FileSpec & rhs) const243061da546Spatrick bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
244061da546Spatrick 
245061da546Spatrick // Less than operator
operator <(const FileSpec & rhs) const246061da546Spatrick bool FileSpec::operator<(const FileSpec &rhs) const {
247061da546Spatrick   return FileSpec::Compare(*this, rhs, true) < 0;
248061da546Spatrick }
249061da546Spatrick 
250061da546Spatrick // Dump a FileSpec object to a stream
operator <<(Stream & s,const FileSpec & f)251061da546Spatrick Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
252061da546Spatrick   f.Dump(s.AsRawOstream());
253061da546Spatrick   return s;
254061da546Spatrick }
255061da546Spatrick 
256061da546Spatrick // Clear this object by releasing both the directory and filename string values
257061da546Spatrick // and making them both the empty string.
Clear()258061da546Spatrick void FileSpec::Clear() {
259061da546Spatrick   m_directory.Clear();
260061da546Spatrick   m_filename.Clear();
261*f6aab3d8Srobert   PathWasModified();
262061da546Spatrick }
263061da546Spatrick 
264061da546Spatrick // Compare two FileSpec objects. If "full" is true, then both the directory and
265061da546Spatrick // the filename must match. If "full" is false, then the directory names for
266061da546Spatrick // "a" and "b" are only compared if they are both non-empty. This allows a
267061da546Spatrick // FileSpec object to only contain a filename and it can match FileSpec objects
268061da546Spatrick // that have matching filenames with different paths.
269061da546Spatrick //
270061da546Spatrick // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
271061da546Spatrick // "a" is greater than "b".
Compare(const FileSpec & a,const FileSpec & b,bool full)272061da546Spatrick int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
273061da546Spatrick   int result = 0;
274061da546Spatrick 
275061da546Spatrick   // case sensitivity of compare
276061da546Spatrick   const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
277061da546Spatrick 
278061da546Spatrick   // If full is true, then we must compare both the directory and filename.
279061da546Spatrick 
280061da546Spatrick   // If full is false, then if either directory is empty, then we match on the
281061da546Spatrick   // basename only, and if both directories have valid values, we still do a
282061da546Spatrick   // full compare. This allows for matching when we just have a filename in one
283061da546Spatrick   // of the FileSpec objects.
284061da546Spatrick 
285061da546Spatrick   if (full || (a.m_directory && b.m_directory)) {
286061da546Spatrick     result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
287061da546Spatrick     if (result)
288061da546Spatrick       return result;
289061da546Spatrick   }
290061da546Spatrick   return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
291061da546Spatrick }
292061da546Spatrick 
Equal(const FileSpec & a,const FileSpec & b,bool full)293061da546Spatrick bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
294061da546Spatrick   if (full || (a.GetDirectory() && b.GetDirectory()))
295061da546Spatrick     return a == b;
296061da546Spatrick 
297061da546Spatrick   return a.FileEquals(b);
298061da546Spatrick }
299061da546Spatrick 
Match(const FileSpec & pattern,const FileSpec & file)300061da546Spatrick bool FileSpec::Match(const FileSpec &pattern, const FileSpec &file) {
301061da546Spatrick   if (pattern.GetDirectory())
302061da546Spatrick     return pattern == file;
303061da546Spatrick   if (pattern.GetFilename())
304061da546Spatrick     return pattern.FileEquals(file);
305061da546Spatrick   return true;
306061da546Spatrick }
307061da546Spatrick 
308*f6aab3d8Srobert std::optional<FileSpec::Style>
GuessPathStyle(llvm::StringRef absolute_path)309*f6aab3d8Srobert FileSpec::GuessPathStyle(llvm::StringRef absolute_path) {
310061da546Spatrick   if (absolute_path.startswith("/"))
311061da546Spatrick     return Style::posix;
312061da546Spatrick   if (absolute_path.startswith(R"(\\)"))
313061da546Spatrick     return Style::windows;
314*f6aab3d8Srobert   if (absolute_path.size() >= 3 && llvm::isAlpha(absolute_path[0]) &&
315*f6aab3d8Srobert       (absolute_path.substr(1, 2) == R"(:\)" ||
316*f6aab3d8Srobert        absolute_path.substr(1, 2) == R"(:/)"))
317061da546Spatrick     return Style::windows;
318*f6aab3d8Srobert   return std::nullopt;
319061da546Spatrick }
320061da546Spatrick 
321061da546Spatrick // Dump the object to the supplied stream. If the object contains a valid
322061da546Spatrick // directory name, it will be displayed followed by a directory delimiter, and
323061da546Spatrick // the filename.
Dump(llvm::raw_ostream & s) const324061da546Spatrick void FileSpec::Dump(llvm::raw_ostream &s) const {
325061da546Spatrick   std::string path{GetPath(true)};
326061da546Spatrick   s << path;
327061da546Spatrick   char path_separator = GetPreferredPathSeparator(m_style);
328061da546Spatrick   if (!m_filename && !path.empty() && path.back() != path_separator)
329061da546Spatrick     s << path_separator;
330061da546Spatrick }
331061da546Spatrick 
GetPathStyle() const332061da546Spatrick FileSpec::Style FileSpec::GetPathStyle() const { return m_style; }
333061da546Spatrick 
SetDirectory(ConstString directory)334*f6aab3d8Srobert void FileSpec::SetDirectory(ConstString directory) {
335*f6aab3d8Srobert   m_directory = directory;
336*f6aab3d8Srobert   PathWasModified();
337*f6aab3d8Srobert }
338061da546Spatrick 
SetDirectory(llvm::StringRef directory)339*f6aab3d8Srobert void FileSpec::SetDirectory(llvm::StringRef directory) {
340*f6aab3d8Srobert   m_directory = ConstString(directory);
341*f6aab3d8Srobert   PathWasModified();
342*f6aab3d8Srobert }
343061da546Spatrick 
SetFilename(ConstString filename)344*f6aab3d8Srobert void FileSpec::SetFilename(ConstString filename) {
345*f6aab3d8Srobert   m_filename = filename;
346*f6aab3d8Srobert   PathWasModified();
347*f6aab3d8Srobert }
348061da546Spatrick 
SetFilename(llvm::StringRef filename)349*f6aab3d8Srobert void FileSpec::SetFilename(llvm::StringRef filename) {
350*f6aab3d8Srobert   m_filename = ConstString(filename);
351*f6aab3d8Srobert   PathWasModified();
352*f6aab3d8Srobert }
353*f6aab3d8Srobert 
ClearFilename()354*f6aab3d8Srobert void FileSpec::ClearFilename() {
355*f6aab3d8Srobert   m_filename.Clear();
356*f6aab3d8Srobert   PathWasModified();
357*f6aab3d8Srobert }
358*f6aab3d8Srobert 
ClearDirectory()359*f6aab3d8Srobert void FileSpec::ClearDirectory() {
360*f6aab3d8Srobert   m_directory.Clear();
361*f6aab3d8Srobert   PathWasModified();
362*f6aab3d8Srobert }
363061da546Spatrick 
364061da546Spatrick // Extract the directory and path into a fixed buffer. This is needed as the
365061da546Spatrick // directory and path are stored in separate string values.
GetPath(char * path,size_t path_max_len,bool denormalize) const366061da546Spatrick size_t FileSpec::GetPath(char *path, size_t path_max_len,
367061da546Spatrick                          bool denormalize) const {
368061da546Spatrick   if (!path)
369061da546Spatrick     return 0;
370061da546Spatrick 
371061da546Spatrick   std::string result = GetPath(denormalize);
372061da546Spatrick   ::snprintf(path, path_max_len, "%s", result.c_str());
373061da546Spatrick   return std::min(path_max_len - 1, result.length());
374061da546Spatrick }
375061da546Spatrick 
GetPath(bool denormalize) const376061da546Spatrick std::string FileSpec::GetPath(bool denormalize) const {
377061da546Spatrick   llvm::SmallString<64> result;
378061da546Spatrick   GetPath(result, denormalize);
379*f6aab3d8Srobert   return static_cast<std::string>(result);
380061da546Spatrick }
381061da546Spatrick 
GetPathAsConstString(bool denormalize) const382*f6aab3d8Srobert ConstString FileSpec::GetPathAsConstString(bool denormalize) const {
383*f6aab3d8Srobert   return ConstString{GetPath(denormalize)};
384061da546Spatrick }
385061da546Spatrick 
GetPath(llvm::SmallVectorImpl<char> & path,bool denormalize) const386061da546Spatrick void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
387061da546Spatrick                        bool denormalize) const {
388061da546Spatrick   path.append(m_directory.GetStringRef().begin(),
389061da546Spatrick               m_directory.GetStringRef().end());
390061da546Spatrick   // Since the path was normalized and all paths use '/' when stored in these
391061da546Spatrick   // objects, we don't need to look for the actual syntax specific path
392061da546Spatrick   // separator, we just look for and insert '/'.
393061da546Spatrick   if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
394061da546Spatrick       m_filename.GetStringRef().back() != '/')
395061da546Spatrick     path.insert(path.end(), '/');
396061da546Spatrick   path.append(m_filename.GetStringRef().begin(),
397061da546Spatrick               m_filename.GetStringRef().end());
398061da546Spatrick   if (denormalize && !path.empty())
399061da546Spatrick     Denormalize(path, m_style);
400061da546Spatrick }
401061da546Spatrick 
GetFileNameExtension() const402061da546Spatrick ConstString FileSpec::GetFileNameExtension() const {
403061da546Spatrick   return ConstString(
404061da546Spatrick       llvm::sys::path::extension(m_filename.GetStringRef(), m_style));
405061da546Spatrick }
406061da546Spatrick 
GetFileNameStrippingExtension() const407061da546Spatrick ConstString FileSpec::GetFileNameStrippingExtension() const {
408061da546Spatrick   return ConstString(llvm::sys::path::stem(m_filename.GetStringRef(), m_style));
409061da546Spatrick }
410061da546Spatrick 
411061da546Spatrick // Return the size in bytes that this object takes in memory. This returns the
412061da546Spatrick // size in bytes of this object, not any shared string values it may refer to.
MemorySize() const413061da546Spatrick size_t FileSpec::MemorySize() const {
414061da546Spatrick   return m_filename.MemorySize() + m_directory.MemorySize();
415061da546Spatrick }
416061da546Spatrick 
417061da546Spatrick FileSpec
CopyByAppendingPathComponent(llvm::StringRef component) const418061da546Spatrick FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
419061da546Spatrick   FileSpec ret = *this;
420061da546Spatrick   ret.AppendPathComponent(component);
421061da546Spatrick   return ret;
422061da546Spatrick }
423061da546Spatrick 
CopyByRemovingLastPathComponent() const424061da546Spatrick FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
425061da546Spatrick   llvm::SmallString<64> current_path;
426061da546Spatrick   GetPath(current_path, false);
427061da546Spatrick   if (llvm::sys::path::has_parent_path(current_path, m_style))
428061da546Spatrick     return FileSpec(llvm::sys::path::parent_path(current_path, m_style),
429061da546Spatrick                     m_style);
430061da546Spatrick   return *this;
431061da546Spatrick }
432061da546Spatrick 
GetLastPathComponent() const433061da546Spatrick ConstString FileSpec::GetLastPathComponent() const {
434061da546Spatrick   llvm::SmallString<64> current_path;
435061da546Spatrick   GetPath(current_path, false);
436061da546Spatrick   return ConstString(llvm::sys::path::filename(current_path, m_style));
437061da546Spatrick }
438061da546Spatrick 
PrependPathComponent(llvm::StringRef component)439061da546Spatrick void FileSpec::PrependPathComponent(llvm::StringRef component) {
440061da546Spatrick   llvm::SmallString<64> new_path(component);
441061da546Spatrick   llvm::SmallString<64> current_path;
442061da546Spatrick   GetPath(current_path, false);
443061da546Spatrick   llvm::sys::path::append(new_path,
444061da546Spatrick                           llvm::sys::path::begin(current_path, m_style),
445061da546Spatrick                           llvm::sys::path::end(current_path), m_style);
446061da546Spatrick   SetFile(new_path, m_style);
447061da546Spatrick }
448061da546Spatrick 
PrependPathComponent(const FileSpec & new_path)449061da546Spatrick void FileSpec::PrependPathComponent(const FileSpec &new_path) {
450061da546Spatrick   return PrependPathComponent(new_path.GetPath(false));
451061da546Spatrick }
452061da546Spatrick 
AppendPathComponent(llvm::StringRef component)453061da546Spatrick void FileSpec::AppendPathComponent(llvm::StringRef component) {
454061da546Spatrick   llvm::SmallString<64> current_path;
455061da546Spatrick   GetPath(current_path, false);
456061da546Spatrick   llvm::sys::path::append(current_path, m_style, component);
457061da546Spatrick   SetFile(current_path, m_style);
458061da546Spatrick }
459061da546Spatrick 
AppendPathComponent(const FileSpec & new_path)460061da546Spatrick void FileSpec::AppendPathComponent(const FileSpec &new_path) {
461061da546Spatrick   return AppendPathComponent(new_path.GetPath(false));
462061da546Spatrick }
463061da546Spatrick 
RemoveLastPathComponent()464061da546Spatrick bool FileSpec::RemoveLastPathComponent() {
465061da546Spatrick   llvm::SmallString<64> current_path;
466061da546Spatrick   GetPath(current_path, false);
467061da546Spatrick   if (llvm::sys::path::has_parent_path(current_path, m_style)) {
468061da546Spatrick     SetFile(llvm::sys::path::parent_path(current_path, m_style));
469061da546Spatrick     return true;
470061da546Spatrick   }
471061da546Spatrick   return false;
472061da546Spatrick }
473061da546Spatrick /// Returns true if the filespec represents an implementation source
474061da546Spatrick /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
475061da546Spatrick /// extension).
476061da546Spatrick ///
477061da546Spatrick /// \return
478061da546Spatrick ///     \b true if the filespec represents an implementation source
479061da546Spatrick ///     file, \b false otherwise.
IsSourceImplementationFile() const480061da546Spatrick bool FileSpec::IsSourceImplementationFile() const {
481061da546Spatrick   ConstString extension(GetFileNameExtension());
482061da546Spatrick   if (!extension)
483061da546Spatrick     return false;
484061da546Spatrick 
485061da546Spatrick   static RegularExpression g_source_file_regex(llvm::StringRef(
486061da546Spatrick       "^.([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
487061da546Spatrick       "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
488061da546Spatrick       "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
489061da546Spatrick       "$"));
490061da546Spatrick   return g_source_file_regex.Execute(extension.GetStringRef());
491061da546Spatrick }
492061da546Spatrick 
IsRelative() const493061da546Spatrick bool FileSpec::IsRelative() const {
494061da546Spatrick   return !IsAbsolute();
495061da546Spatrick }
496061da546Spatrick 
IsAbsolute() const497061da546Spatrick bool FileSpec::IsAbsolute() const {
498*f6aab3d8Srobert   // Check if we have cached if this path is absolute to avoid recalculating.
499*f6aab3d8Srobert   if (m_absolute != Absolute::Calculate)
500*f6aab3d8Srobert     return m_absolute == Absolute::Yes;
501061da546Spatrick 
502*f6aab3d8Srobert   m_absolute = Absolute::No;
503061da546Spatrick 
504*f6aab3d8Srobert   llvm::SmallString<64> path;
505*f6aab3d8Srobert   GetPath(path, false);
506*f6aab3d8Srobert 
507*f6aab3d8Srobert   if (!path.empty()) {
508061da546Spatrick     // We consider paths starting with ~ to be absolute.
509*f6aab3d8Srobert     if (path[0] == '~' || llvm::sys::path::is_absolute(path, m_style))
510*f6aab3d8Srobert       m_absolute = Absolute::Yes;
511*f6aab3d8Srobert   }
512061da546Spatrick 
513*f6aab3d8Srobert   return m_absolute == Absolute::Yes;
514061da546Spatrick }
515061da546Spatrick 
MakeAbsolute(const FileSpec & dir)516061da546Spatrick void FileSpec::MakeAbsolute(const FileSpec &dir) {
517061da546Spatrick   if (IsRelative())
518061da546Spatrick     PrependPathComponent(dir);
519061da546Spatrick }
520061da546Spatrick 
format(const FileSpec & F,raw_ostream & Stream,StringRef Style)521061da546Spatrick void llvm::format_provider<FileSpec>::format(const FileSpec &F,
522061da546Spatrick                                              raw_ostream &Stream,
523061da546Spatrick                                              StringRef Style) {
524be691f3bSpatrick   assert((Style.empty() || Style.equals_insensitive("F") ||
525be691f3bSpatrick           Style.equals_insensitive("D")) &&
526061da546Spatrick          "Invalid FileSpec style!");
527061da546Spatrick 
528061da546Spatrick   StringRef dir = F.GetDirectory().GetStringRef();
529061da546Spatrick   StringRef file = F.GetFilename().GetStringRef();
530061da546Spatrick 
531061da546Spatrick   if (dir.empty() && file.empty()) {
532061da546Spatrick     Stream << "(empty)";
533061da546Spatrick     return;
534061da546Spatrick   }
535061da546Spatrick 
536be691f3bSpatrick   if (Style.equals_insensitive("F")) {
537061da546Spatrick     Stream << (file.empty() ? "(empty)" : file);
538061da546Spatrick     return;
539061da546Spatrick   }
540061da546Spatrick 
541061da546Spatrick   // Style is either D or empty, either way we need to print the directory.
542061da546Spatrick   if (!dir.empty()) {
543061da546Spatrick     // Directory is stored in normalized form, which might be different than
544061da546Spatrick     // preferred form.  In order to handle this, we need to cut off the
545061da546Spatrick     // filename, then denormalize, then write the entire denorm'ed directory.
546061da546Spatrick     llvm::SmallString<64> denormalized_dir = dir;
547061da546Spatrick     Denormalize(denormalized_dir, F.GetPathStyle());
548061da546Spatrick     Stream << denormalized_dir;
549061da546Spatrick     Stream << GetPreferredPathSeparator(F.GetPathStyle());
550061da546Spatrick   }
551061da546Spatrick 
552be691f3bSpatrick   if (Style.equals_insensitive("D")) {
553061da546Spatrick     // We only want to print the directory, so now just exit.
554061da546Spatrick     if (dir.empty())
555061da546Spatrick       Stream << "(empty)";
556061da546Spatrick     return;
557061da546Spatrick   }
558061da546Spatrick 
559061da546Spatrick   if (!file.empty())
560061da546Spatrick     Stream << file;
561061da546Spatrick }
562