15713a05bSZachary Turner //===-- FileSpec.cpp --------------------------------------------*- C++ -*-===//
25713a05bSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65713a05bSZachary Turner //
75713a05bSZachary Turner //===----------------------------------------------------------------------===//
85713a05bSZachary Turner 
95713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
105713a05bSZachary Turner #include "lldb/Utility/RegularExpression.h"
115713a05bSZachary Turner #include "lldb/Utility/Stream.h"
125713a05bSZachary Turner 
13ad8d48f9SJonas Devlieghere #include "llvm/ADT/SmallString.h"
14ad8d48f9SJonas Devlieghere #include "llvm/ADT/SmallVector.h"
155713a05bSZachary Turner #include "llvm/ADT/StringRef.h"
16ad8d48f9SJonas Devlieghere #include "llvm/ADT/Triple.h"
17ad8d48f9SJonas Devlieghere #include "llvm/ADT/Twine.h"
18ad8d48f9SJonas Devlieghere #include "llvm/Support/ErrorOr.h"
195713a05bSZachary Turner #include "llvm/Support/FileSystem.h"
205713a05bSZachary Turner #include "llvm/Support/Program.h"
21ad8d48f9SJonas Devlieghere #include "llvm/Support/raw_ostream.h"
224479ac15SZachary Turner 
23672d2c12SJonas Devlieghere #include <algorithm>
24672d2c12SJonas Devlieghere #include <system_error>
25672d2c12SJonas Devlieghere #include <vector>
264479ac15SZachary Turner 
27672d2c12SJonas Devlieghere #include <assert.h>
28672d2c12SJonas Devlieghere #include <limits.h>
29672d2c12SJonas Devlieghere #include <stdio.h>
30672d2c12SJonas Devlieghere #include <string.h>
315713a05bSZachary Turner 
325713a05bSZachary Turner using namespace lldb;
335713a05bSZachary Turner using namespace lldb_private;
345713a05bSZachary Turner 
355713a05bSZachary Turner namespace {
365713a05bSZachary Turner 
372cb7cf8eSPavel Labath static constexpr FileSpec::Style GetNativeStyle() {
38b1cb0b79SNico Weber #if defined(_WIN32)
392cb7cf8eSPavel Labath   return FileSpec::Style::windows;
405713a05bSZachary Turner #else
412cb7cf8eSPavel Labath   return FileSpec::Style::posix;
425713a05bSZachary Turner #endif
435713a05bSZachary Turner }
445713a05bSZachary Turner 
452cb7cf8eSPavel Labath bool PathStyleIsPosix(FileSpec::Style style) {
462cb7cf8eSPavel Labath   return (style == FileSpec::Style::posix ||
472cb7cf8eSPavel Labath           (style == FileSpec::Style::native &&
482cb7cf8eSPavel Labath            GetNativeStyle() == FileSpec::Style::posix));
495713a05bSZachary Turner }
505713a05bSZachary Turner 
512cb7cf8eSPavel Labath const char *GetPathSeparators(FileSpec::Style style) {
52ad8d48f9SJonas Devlieghere   return llvm::sys::path::get_separator(style).data();
535713a05bSZachary Turner }
545713a05bSZachary Turner 
552cb7cf8eSPavel Labath char GetPreferredPathSeparator(FileSpec::Style style) {
562cb7cf8eSPavel Labath   return GetPathSeparators(style)[0];
575713a05bSZachary Turner }
585713a05bSZachary Turner 
592cb7cf8eSPavel Labath void Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::Style style) {
602cb7cf8eSPavel Labath   if (PathStyleIsPosix(style))
615713a05bSZachary Turner     return;
625713a05bSZachary Turner 
635713a05bSZachary Turner   std::replace(path.begin(), path.end(), '/', '\\');
645713a05bSZachary Turner }
6586188d8aSGreg Clayton 
665713a05bSZachary Turner } // end anonymous namespace
675713a05bSZachary Turner 
682cb7cf8eSPavel Labath FileSpec::FileSpec() : m_style(GetNativeStyle()) {}
695713a05bSZachary Turner 
7005097246SAdrian Prantl // Default constructor that can take an optional full path to a file on disk.
718f3be7a3SJonas Devlieghere FileSpec::FileSpec(llvm::StringRef path, Style style) : m_style(style) {
728f3be7a3SJonas Devlieghere   SetFile(path, style);
735713a05bSZachary Turner }
745713a05bSZachary Turner 
75a7d4cec4SJonas Devlieghere FileSpec::FileSpec(llvm::StringRef path, const llvm::Triple &triple)
76706cd705SJonas Devlieghere     : FileSpec{path, triple.isOSWindows() ? Style::windows : Style::posix} {}
775713a05bSZachary Turner 
78c1cc3173SJonas Devlieghere namespace {
79c1cc3173SJonas Devlieghere /// Safely get a character at the specified index.
80c1cc3173SJonas Devlieghere ///
81f05b42e9SAdrian Prantl /// \param[in] path
82c1cc3173SJonas Devlieghere ///     A full, partial, or relative path to a file.
83c1cc3173SJonas Devlieghere ///
84f05b42e9SAdrian Prantl /// \param[in] i
85c1cc3173SJonas Devlieghere ///     An index into path which may or may not be valid.
86c1cc3173SJonas Devlieghere ///
87f05b42e9SAdrian Prantl /// \return
88c1cc3173SJonas Devlieghere ///   The character at index \a i if the index is valid, or 0 if
89c1cc3173SJonas Devlieghere ///   the index is not valid.
90c1cc3173SJonas Devlieghere inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
91c1cc3173SJonas Devlieghere   if (i < path.size())
92c1cc3173SJonas Devlieghere     return path[i];
93c1cc3173SJonas Devlieghere   return 0;
94c1cc3173SJonas Devlieghere }
95c1cc3173SJonas Devlieghere 
96c1cc3173SJonas Devlieghere /// Check if a path needs to be normalized.
97c1cc3173SJonas Devlieghere ///
98c1cc3173SJonas Devlieghere /// Check if a path needs to be normalized. We currently consider a
99c1cc3173SJonas Devlieghere /// path to need normalization if any of the following are true
100c1cc3173SJonas Devlieghere ///  - path contains "/./"
101c1cc3173SJonas Devlieghere ///  - path contains "/../"
102c1cc3173SJonas Devlieghere ///  - path contains "//"
103c1cc3173SJonas Devlieghere ///  - path ends with "/"
104c1cc3173SJonas Devlieghere /// Paths that start with "./" or with "../" are not considered to
105c1cc3173SJonas Devlieghere /// need normalization since we aren't trying to resolve the path,
106c1cc3173SJonas Devlieghere /// we are just trying to remove redundant things from the path.
107c1cc3173SJonas Devlieghere ///
108f05b42e9SAdrian Prantl /// \param[in] path
109c1cc3173SJonas Devlieghere ///     A full, partial, or relative path to a file.
110c1cc3173SJonas Devlieghere ///
111f05b42e9SAdrian Prantl /// \return
112c1cc3173SJonas Devlieghere ///   Returns \b true if the path needs to be normalized.
113c1cc3173SJonas Devlieghere bool needsNormalization(const llvm::StringRef &path) {
114c1cc3173SJonas Devlieghere   if (path.empty())
115c1cc3173SJonas Devlieghere     return false;
116c1cc3173SJonas Devlieghere   // We strip off leading "." values so these paths need to be normalized
117c1cc3173SJonas Devlieghere   if (path[0] == '.')
118c1cc3173SJonas Devlieghere     return true;
119c1cc3173SJonas Devlieghere   for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
120c1cc3173SJonas Devlieghere        i = path.find_first_of("\\/", i + 1)) {
121c1cc3173SJonas Devlieghere     const auto next = safeCharAtIndex(path, i+1);
122c1cc3173SJonas Devlieghere     switch (next) {
123c1cc3173SJonas Devlieghere       case 0:
124c1cc3173SJonas Devlieghere         // path separator char at the end of the string which should be
125c1cc3173SJonas Devlieghere         // stripped unless it is the one and only character
126c1cc3173SJonas Devlieghere         return i > 0;
127c1cc3173SJonas Devlieghere       case '/':
128c1cc3173SJonas Devlieghere       case '\\':
129c1cc3173SJonas Devlieghere         // two path separator chars in the middle of a path needs to be
130c1cc3173SJonas Devlieghere         // normalized
131c1cc3173SJonas Devlieghere         if (i > 0)
132c1cc3173SJonas Devlieghere           return true;
133c1cc3173SJonas Devlieghere         ++i;
134c1cc3173SJonas Devlieghere         break;
135c1cc3173SJonas Devlieghere 
136c1cc3173SJonas Devlieghere       case '.': {
137c1cc3173SJonas Devlieghere           const auto next_next = safeCharAtIndex(path, i+2);
138c1cc3173SJonas Devlieghere           switch (next_next) {
139c1cc3173SJonas Devlieghere             default: break;
140c1cc3173SJonas Devlieghere             case 0: return true; // ends with "/."
141c1cc3173SJonas Devlieghere             case '/':
142c1cc3173SJonas Devlieghere             case '\\':
143c1cc3173SJonas Devlieghere               return true; // contains "/./"
144c1cc3173SJonas Devlieghere             case '.': {
145c1cc3173SJonas Devlieghere               const auto next_next_next = safeCharAtIndex(path, i+3);
146c1cc3173SJonas Devlieghere               switch (next_next_next) {
147c1cc3173SJonas Devlieghere                 default: break;
148c1cc3173SJonas Devlieghere                 case 0: return true; // ends with "/.."
149c1cc3173SJonas Devlieghere                 case '/':
150c1cc3173SJonas Devlieghere                 case '\\':
151c1cc3173SJonas Devlieghere                   return true; // contains "/../"
152c1cc3173SJonas Devlieghere               }
153c1cc3173SJonas Devlieghere               break;
154c1cc3173SJonas Devlieghere             }
155c1cc3173SJonas Devlieghere           }
156c1cc3173SJonas Devlieghere         }
157c1cc3173SJonas Devlieghere         break;
158c1cc3173SJonas Devlieghere 
159c1cc3173SJonas Devlieghere       default:
160c1cc3173SJonas Devlieghere         break;
161c1cc3173SJonas Devlieghere     }
162c1cc3173SJonas Devlieghere   }
163c1cc3173SJonas Devlieghere   return false;
164c1cc3173SJonas Devlieghere }
165c1cc3173SJonas Devlieghere 
166c1cc3173SJonas Devlieghere 
167c1cc3173SJonas Devlieghere }
1685713a05bSZachary Turner 
1698f3be7a3SJonas Devlieghere void FileSpec::SetFile(llvm::StringRef pathname) { SetFile(pathname, m_style); }
170937348cdSJonas Devlieghere 
17105097246SAdrian Prantl // Update the contents of this object with a new path. The path will be split
17205097246SAdrian Prantl // up into a directory and filename and stored as uniqued string values for
17305097246SAdrian Prantl // quick comparison and efficient memory usage.
1748f3be7a3SJonas Devlieghere void FileSpec::SetFile(llvm::StringRef pathname, Style style) {
1755713a05bSZachary Turner   m_filename.Clear();
1765713a05bSZachary Turner   m_directory.Clear();
1775713a05bSZachary Turner   m_is_resolved = false;
1782cb7cf8eSPavel Labath   m_style = (style == Style::native) ? GetNativeStyle() : style;
1795713a05bSZachary Turner 
1805713a05bSZachary Turner   if (pathname.empty())
1815713a05bSZachary Turner     return;
1825713a05bSZachary Turner 
1838f3be7a3SJonas Devlieghere   llvm::SmallString<128> resolved(pathname);
1845713a05bSZachary Turner 
185776cd7adSGreg Clayton   // Normalize the path by removing ".", ".." and other redundant components.
186c1cc3173SJonas Devlieghere   if (needsNormalization(resolved))
1872cb7cf8eSPavel Labath     llvm::sys::path::remove_dots(resolved, true, m_style);
188776cd7adSGreg Clayton 
189776cd7adSGreg Clayton   // Normalize back slashes to forward slashes
1902cb7cf8eSPavel Labath   if (m_style == Style::windows)
191776cd7adSGreg Clayton     std::replace(resolved.begin(), resolved.end(), '\\', '/');
1925713a05bSZachary Turner 
19339d50b72SGreg Clayton   if (resolved.empty()) {
19439d50b72SGreg Clayton     // If we have no path after normalization set the path to the current
19539d50b72SGreg Clayton     // directory. This matches what python does and also a few other path
19639d50b72SGreg Clayton     // utilities.
19739d50b72SGreg Clayton     m_filename.SetString(".");
19839d50b72SGreg Clayton     return;
19939d50b72SGreg Clayton   }
20039d50b72SGreg Clayton 
201ad8d48f9SJonas Devlieghere   // Split path into filename and directory. We rely on the underlying char
202ad8d48f9SJonas Devlieghere   // pointer to be nullptr when the components are empty.
203ad8d48f9SJonas Devlieghere   llvm::StringRef filename = llvm::sys::path::filename(resolved, m_style);
204ad8d48f9SJonas Devlieghere   if(!filename.empty())
205ad8d48f9SJonas Devlieghere     m_filename.SetString(filename);
2068f3be7a3SJonas Devlieghere 
207ad8d48f9SJonas Devlieghere   llvm::StringRef directory = llvm::sys::path::parent_path(resolved, m_style);
208ad8d48f9SJonas Devlieghere   if(!directory.empty())
209ad8d48f9SJonas Devlieghere     m_directory.SetString(directory);
2105713a05bSZachary Turner }
2115713a05bSZachary Turner 
212706cd705SJonas Devlieghere void FileSpec::SetFile(llvm::StringRef path, const llvm::Triple &triple) {
213706cd705SJonas Devlieghere   return SetFile(path, triple.isOSWindows() ? Style::windows : Style::posix);
2145713a05bSZachary Turner }
2155713a05bSZachary Turner 
21605097246SAdrian Prantl // Convert to pointer operator. This allows code to check any FileSpec objects
21705097246SAdrian Prantl // to see if they contain anything valid using code such as:
2185713a05bSZachary Turner //
2195713a05bSZachary Turner //  if (file_spec)
2205713a05bSZachary Turner //  {}
2215713a05bSZachary Turner FileSpec::operator bool() const { return m_filename || m_directory; }
2225713a05bSZachary Turner 
22305097246SAdrian Prantl // Logical NOT operator. This allows code to check any FileSpec objects to see
22405097246SAdrian Prantl // if they are invalid using code such as:
2255713a05bSZachary Turner //
2265713a05bSZachary Turner //  if (!file_spec)
2275713a05bSZachary Turner //  {}
2285713a05bSZachary Turner bool FileSpec::operator!() const { return !m_directory && !m_filename; }
2295713a05bSZachary Turner 
2305713a05bSZachary Turner bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
2315713a05bSZachary Turner   const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
2325713a05bSZachary Turner   return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
2335713a05bSZachary Turner }
2345713a05bSZachary Turner 
2355713a05bSZachary Turner bool FileSpec::FileEquals(const FileSpec &rhs) const {
2365713a05bSZachary Turner   const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
2375713a05bSZachary Turner   return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
2385713a05bSZachary Turner }
2395713a05bSZachary Turner 
2405713a05bSZachary Turner // Equal to operator
2415713a05bSZachary Turner bool FileSpec::operator==(const FileSpec &rhs) const {
2428f3be7a3SJonas Devlieghere   return FileEquals(rhs) && DirectoryEquals(rhs);
2435713a05bSZachary Turner }
2445713a05bSZachary Turner 
2455713a05bSZachary Turner // Not equal to operator
2465713a05bSZachary Turner bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
2475713a05bSZachary Turner 
2485713a05bSZachary Turner // Less than operator
2495713a05bSZachary Turner bool FileSpec::operator<(const FileSpec &rhs) const {
2505713a05bSZachary Turner   return FileSpec::Compare(*this, rhs, true) < 0;
2515713a05bSZachary Turner }
2525713a05bSZachary Turner 
2535713a05bSZachary Turner // Dump a FileSpec object to a stream
2545713a05bSZachary Turner Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
255*4dac97ebSRaphael Isemann   f.Dump(s.AsRawOstream());
2565713a05bSZachary Turner   return s;
2575713a05bSZachary Turner }
2585713a05bSZachary Turner 
25905097246SAdrian Prantl // Clear this object by releasing both the directory and filename string values
26005097246SAdrian Prantl // and making them both the empty string.
2615713a05bSZachary Turner void FileSpec::Clear() {
2625713a05bSZachary Turner   m_directory.Clear();
2635713a05bSZachary Turner   m_filename.Clear();
2645713a05bSZachary Turner }
2655713a05bSZachary Turner 
26605097246SAdrian Prantl // Compare two FileSpec objects. If "full" is true, then both the directory and
26705097246SAdrian Prantl // the filename must match. If "full" is false, then the directory names for
26805097246SAdrian Prantl // "a" and "b" are only compared if they are both non-empty. This allows a
26905097246SAdrian Prantl // FileSpec object to only contain a filename and it can match FileSpec objects
27005097246SAdrian Prantl // that have matching filenames with different paths.
2715713a05bSZachary Turner //
27205097246SAdrian Prantl // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
27305097246SAdrian Prantl // "a" is greater than "b".
2745713a05bSZachary Turner int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
2755713a05bSZachary Turner   int result = 0;
2765713a05bSZachary Turner 
2775713a05bSZachary Turner   // case sensitivity of compare
2785713a05bSZachary Turner   const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
2795713a05bSZachary Turner 
2805713a05bSZachary Turner   // If full is true, then we must compare both the directory and filename.
2815713a05bSZachary Turner 
28205097246SAdrian Prantl   // If full is false, then if either directory is empty, then we match on the
28305097246SAdrian Prantl   // basename only, and if both directories have valid values, we still do a
28405097246SAdrian Prantl   // full compare. This allows for matching when we just have a filename in one
28505097246SAdrian Prantl   // of the FileSpec objects.
2865713a05bSZachary Turner 
2875713a05bSZachary Turner   if (full || (a.m_directory && b.m_directory)) {
2885713a05bSZachary Turner     result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
2895713a05bSZachary Turner     if (result)
2905713a05bSZachary Turner       return result;
2915713a05bSZachary Turner   }
2925713a05bSZachary Turner   return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
2935713a05bSZachary Turner }
2945713a05bSZachary Turner 
295776cd7adSGreg Clayton bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
296b18e190bSPavel Labath   if (full || (a.GetDirectory() && b.GetDirectory()))
2975713a05bSZachary Turner     return a == b;
298b18e190bSPavel Labath 
299b18e190bSPavel Labath   return a.FileEquals(b);
3005713a05bSZachary Turner }
3015713a05bSZachary Turner 
302532290e6SPavel Labath bool FileSpec::Match(const FileSpec &pattern, const FileSpec &file) {
303532290e6SPavel Labath   if (pattern.GetDirectory())
304532290e6SPavel Labath     return pattern == file;
305532290e6SPavel Labath   if (pattern.GetFilename())
306532290e6SPavel Labath     return pattern.FileEquals(file);
307532290e6SPavel Labath   return true;
308532290e6SPavel Labath }
309532290e6SPavel Labath 
310841bea93SPavel Labath llvm::Optional<FileSpec::Style> FileSpec::GuessPathStyle(llvm::StringRef absolute_path) {
311841bea93SPavel Labath   if (absolute_path.startswith("/"))
312841bea93SPavel Labath     return Style::posix;
313841bea93SPavel Labath   if (absolute_path.startswith(R"(\\)"))
314841bea93SPavel Labath     return Style::windows;
315841bea93SPavel Labath   if (absolute_path.size() > 3 && llvm::isAlpha(absolute_path[0]) &&
316841bea93SPavel Labath       absolute_path.substr(1, 2) == R"(:\)")
317841bea93SPavel Labath     return Style::windows;
318841bea93SPavel Labath   return llvm::None;
319841bea93SPavel Labath }
320841bea93SPavel Labath 
32105097246SAdrian Prantl // Dump the object to the supplied stream. If the object contains a valid
32205097246SAdrian Prantl // directory name, it will be displayed followed by a directory delimiter, and
32305097246SAdrian Prantl // the filename.
324*4dac97ebSRaphael Isemann void FileSpec::Dump(llvm::raw_ostream &s) const {
3255713a05bSZachary Turner   std::string path{GetPath(true)};
326*4dac97ebSRaphael Isemann   s << path;
3272cb7cf8eSPavel Labath   char path_separator = GetPreferredPathSeparator(m_style);
3285713a05bSZachary Turner   if (!m_filename && !path.empty() && path.back() != path_separator)
329*4dac97ebSRaphael Isemann     s << path_separator;
3305713a05bSZachary Turner }
3315713a05bSZachary Turner 
3322cb7cf8eSPavel Labath FileSpec::Style FileSpec::GetPathStyle() const { return m_style; }
3335713a05bSZachary Turner 
3345713a05bSZachary Turner // Directory string get accessor.
3355713a05bSZachary Turner ConstString &FileSpec::GetDirectory() { return m_directory; }
3365713a05bSZachary Turner 
3375713a05bSZachary Turner // Directory string const get accessor.
3380e4c4821SAdrian Prantl ConstString FileSpec::GetDirectory() const { return m_directory; }
3395713a05bSZachary Turner 
3405713a05bSZachary Turner // Filename string get accessor.
3415713a05bSZachary Turner ConstString &FileSpec::GetFilename() { return m_filename; }
3425713a05bSZachary Turner 
3435713a05bSZachary Turner // Filename string const get accessor.
3440e4c4821SAdrian Prantl ConstString FileSpec::GetFilename() const { return m_filename; }
3455713a05bSZachary Turner 
34605097246SAdrian Prantl // Extract the directory and path into a fixed buffer. This is needed as the
34705097246SAdrian Prantl // directory and path are stored in separate string values.
3485713a05bSZachary Turner size_t FileSpec::GetPath(char *path, size_t path_max_len,
3495713a05bSZachary Turner                          bool denormalize) const {
3505713a05bSZachary Turner   if (!path)
3515713a05bSZachary Turner     return 0;
3525713a05bSZachary Turner 
3535713a05bSZachary Turner   std::string result = GetPath(denormalize);
3545713a05bSZachary Turner   ::snprintf(path, path_max_len, "%s", result.c_str());
3555713a05bSZachary Turner   return std::min(path_max_len - 1, result.length());
3565713a05bSZachary Turner }
3575713a05bSZachary Turner 
3585713a05bSZachary Turner std::string FileSpec::GetPath(bool denormalize) const {
3595713a05bSZachary Turner   llvm::SmallString<64> result;
3605713a05bSZachary Turner   GetPath(result, denormalize);
3615713a05bSZachary Turner   return std::string(result.begin(), result.end());
3625713a05bSZachary Turner }
3635713a05bSZachary Turner 
3645713a05bSZachary Turner const char *FileSpec::GetCString(bool denormalize) const {
36565e5e278SJonas Devlieghere   return ConstString{GetPath(denormalize)}.AsCString(nullptr);
3665713a05bSZachary Turner }
3675713a05bSZachary Turner 
3685713a05bSZachary Turner void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
3695713a05bSZachary Turner                        bool denormalize) const {
3705713a05bSZachary Turner   path.append(m_directory.GetStringRef().begin(),
3715713a05bSZachary Turner               m_directory.GetStringRef().end());
372776cd7adSGreg Clayton   // Since the path was normalized and all paths use '/' when stored in these
373776cd7adSGreg Clayton   // objects, we don't need to look for the actual syntax specific path
374776cd7adSGreg Clayton   // separator, we just look for and insert '/'.
375776cd7adSGreg Clayton   if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
376776cd7adSGreg Clayton       m_filename.GetStringRef().back() != '/')
377776cd7adSGreg Clayton     path.insert(path.end(), '/');
3785713a05bSZachary Turner   path.append(m_filename.GetStringRef().begin(),
3795713a05bSZachary Turner               m_filename.GetStringRef().end());
3805713a05bSZachary Turner   if (denormalize && !path.empty())
3812cb7cf8eSPavel Labath     Denormalize(path, m_style);
3825713a05bSZachary Turner }
3835713a05bSZachary Turner 
3845713a05bSZachary Turner ConstString FileSpec::GetFileNameExtension() const {
3859c1a645aSJonas Devlieghere   return ConstString(
3869c1a645aSJonas Devlieghere       llvm::sys::path::extension(m_filename.GetStringRef(), m_style));
3875713a05bSZachary Turner }
3885713a05bSZachary Turner 
3895713a05bSZachary Turner ConstString FileSpec::GetFileNameStrippingExtension() const {
3909c1a645aSJonas Devlieghere   return ConstString(llvm::sys::path::stem(m_filename.GetStringRef(), m_style));
3915713a05bSZachary Turner }
3925713a05bSZachary Turner 
39305097246SAdrian Prantl // Return the size in bytes that this object takes in memory. This returns the
39405097246SAdrian Prantl // size in bytes of this object, not any shared string values it may refer to.
3955713a05bSZachary Turner size_t FileSpec::MemorySize() const {
3965713a05bSZachary Turner   return m_filename.MemorySize() + m_directory.MemorySize();
3975713a05bSZachary Turner }
3985713a05bSZachary Turner 
3995713a05bSZachary Turner FileSpec
4005713a05bSZachary Turner FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
4015713a05bSZachary Turner   FileSpec ret = *this;
4025713a05bSZachary Turner   ret.AppendPathComponent(component);
4035713a05bSZachary Turner   return ret;
4045713a05bSZachary Turner }
4055713a05bSZachary Turner 
4065713a05bSZachary Turner FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
40724bd63c4SJonas Devlieghere   llvm::SmallString<64> current_path;
40824bd63c4SJonas Devlieghere   GetPath(current_path, false);
40924bd63c4SJonas Devlieghere   if (llvm::sys::path::has_parent_path(current_path, m_style))
4108f3be7a3SJonas Devlieghere     return FileSpec(llvm::sys::path::parent_path(current_path, m_style),
41124bd63c4SJonas Devlieghere                     m_style);
41224bd63c4SJonas Devlieghere   return *this;
4135713a05bSZachary Turner }
4145713a05bSZachary Turner 
4155713a05bSZachary Turner ConstString FileSpec::GetLastPathComponent() const {
41624bd63c4SJonas Devlieghere   llvm::SmallString<64> current_path;
41724bd63c4SJonas Devlieghere   GetPath(current_path, false);
41824bd63c4SJonas Devlieghere   return ConstString(llvm::sys::path::filename(current_path, m_style));
4195713a05bSZachary Turner }
4205713a05bSZachary Turner 
4215713a05bSZachary Turner void FileSpec::PrependPathComponent(llvm::StringRef component) {
42224bd63c4SJonas Devlieghere   llvm::SmallString<64> new_path(component);
42324bd63c4SJonas Devlieghere   llvm::SmallString<64> current_path;
42424bd63c4SJonas Devlieghere   GetPath(current_path, false);
42524bd63c4SJonas Devlieghere   llvm::sys::path::append(new_path,
42624bd63c4SJonas Devlieghere                           llvm::sys::path::begin(current_path, m_style),
42724bd63c4SJonas Devlieghere                           llvm::sys::path::end(current_path), m_style);
4288f3be7a3SJonas Devlieghere   SetFile(new_path, m_style);
4295713a05bSZachary Turner }
4305713a05bSZachary Turner 
4315713a05bSZachary Turner void FileSpec::PrependPathComponent(const FileSpec &new_path) {
4325713a05bSZachary Turner   return PrependPathComponent(new_path.GetPath(false));
4335713a05bSZachary Turner }
4345713a05bSZachary Turner 
4355713a05bSZachary Turner void FileSpec::AppendPathComponent(llvm::StringRef component) {
43624bd63c4SJonas Devlieghere   llvm::SmallString<64> current_path;
43724bd63c4SJonas Devlieghere   GetPath(current_path, false);
43824bd63c4SJonas Devlieghere   llvm::sys::path::append(current_path, m_style, component);
4398f3be7a3SJonas Devlieghere   SetFile(current_path, m_style);
4405713a05bSZachary Turner }
4415713a05bSZachary Turner 
4425713a05bSZachary Turner void FileSpec::AppendPathComponent(const FileSpec &new_path) {
4435713a05bSZachary Turner   return AppendPathComponent(new_path.GetPath(false));
4445713a05bSZachary Turner }
4455713a05bSZachary Turner 
446df8e291eSJonas Devlieghere bool FileSpec::RemoveLastPathComponent() {
447df8e291eSJonas Devlieghere   llvm::SmallString<64> current_path;
448df8e291eSJonas Devlieghere   GetPath(current_path, false);
449df8e291eSJonas Devlieghere   if (llvm::sys::path::has_parent_path(current_path, m_style)) {
4508f3be7a3SJonas Devlieghere     SetFile(llvm::sys::path::parent_path(current_path, m_style));
451df8e291eSJonas Devlieghere     return true;
4525713a05bSZachary Turner   }
453df8e291eSJonas Devlieghere   return false;
4545713a05bSZachary Turner }
4555713a05bSZachary Turner /// Returns true if the filespec represents an implementation source
4565713a05bSZachary Turner /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
4575713a05bSZachary Turner /// extension).
4585713a05bSZachary Turner ///
459f05b42e9SAdrian Prantl /// \return
4605713a05bSZachary Turner ///     \b true if the filespec represents an implementation source
4615713a05bSZachary Turner ///     file, \b false otherwise.
4625713a05bSZachary Turner bool FileSpec::IsSourceImplementationFile() const {
4635713a05bSZachary Turner   ConstString extension(GetFileNameExtension());
4645713a05bSZachary Turner   if (!extension)
4655713a05bSZachary Turner     return false;
4665713a05bSZachary Turner 
4675713a05bSZachary Turner   static RegularExpression g_source_file_regex(llvm::StringRef(
468ad8d48f9SJonas Devlieghere       "^.([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
4695713a05bSZachary Turner       "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
4705713a05bSZachary Turner       "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
4715713a05bSZachary Turner       "$"));
4725713a05bSZachary Turner   return g_source_file_regex.Execute(extension.GetStringRef());
4735713a05bSZachary Turner }
4745713a05bSZachary Turner 
475c1cc3173SJonas Devlieghere bool FileSpec::IsRelative() const {
476c1cc3173SJonas Devlieghere   return !IsAbsolute();
477c1cc3173SJonas Devlieghere }
4785713a05bSZachary Turner 
479ad8d48f9SJonas Devlieghere bool FileSpec::IsAbsolute() const {
480ad8d48f9SJonas Devlieghere   llvm::SmallString<64> current_path;
481ad8d48f9SJonas Devlieghere   GetPath(current_path, false);
482ad8d48f9SJonas Devlieghere 
483ad8d48f9SJonas Devlieghere   // Early return if the path is empty.
484ad8d48f9SJonas Devlieghere   if (current_path.empty())
485ad8d48f9SJonas Devlieghere     return false;
486ad8d48f9SJonas Devlieghere 
487ad8d48f9SJonas Devlieghere   // We consider paths starting with ~ to be absolute.
488ad8d48f9SJonas Devlieghere   if (current_path[0] == '~')
489ad8d48f9SJonas Devlieghere     return true;
490ad8d48f9SJonas Devlieghere 
491ad8d48f9SJonas Devlieghere   return llvm::sys::path::is_absolute(current_path, m_style);
492ad8d48f9SJonas Devlieghere }
4935713a05bSZachary Turner 
4947d36d723SPavel Labath void FileSpec::MakeAbsolute(const FileSpec &dir) {
4957d36d723SPavel Labath   if (IsRelative())
4967d36d723SPavel Labath     PrependPathComponent(dir);
4977d36d723SPavel Labath }
4987d36d723SPavel Labath 
4995713a05bSZachary Turner void llvm::format_provider<FileSpec>::format(const FileSpec &F,
5005713a05bSZachary Turner                                              raw_ostream &Stream,
5015713a05bSZachary Turner                                              StringRef Style) {
5025713a05bSZachary Turner   assert(
5035713a05bSZachary Turner       (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
5045713a05bSZachary Turner       "Invalid FileSpec style!");
5055713a05bSZachary Turner 
5065713a05bSZachary Turner   StringRef dir = F.GetDirectory().GetStringRef();
5075713a05bSZachary Turner   StringRef file = F.GetFilename().GetStringRef();
5085713a05bSZachary Turner 
5095713a05bSZachary Turner   if (dir.empty() && file.empty()) {
5105713a05bSZachary Turner     Stream << "(empty)";
5115713a05bSZachary Turner     return;
5125713a05bSZachary Turner   }
5135713a05bSZachary Turner 
5145713a05bSZachary Turner   if (Style.equals_lower("F")) {
5155713a05bSZachary Turner     Stream << (file.empty() ? "(empty)" : file);
5165713a05bSZachary Turner     return;
5175713a05bSZachary Turner   }
5185713a05bSZachary Turner 
5195713a05bSZachary Turner   // Style is either D or empty, either way we need to print the directory.
5205713a05bSZachary Turner   if (!dir.empty()) {
52105097246SAdrian Prantl     // Directory is stored in normalized form, which might be different than
52205097246SAdrian Prantl     // preferred form.  In order to handle this, we need to cut off the
52305097246SAdrian Prantl     // filename, then denormalize, then write the entire denorm'ed directory.
5245713a05bSZachary Turner     llvm::SmallString<64> denormalized_dir = dir;
5252cb7cf8eSPavel Labath     Denormalize(denormalized_dir, F.GetPathStyle());
5265713a05bSZachary Turner     Stream << denormalized_dir;
5272cb7cf8eSPavel Labath     Stream << GetPreferredPathSeparator(F.GetPathStyle());
5285713a05bSZachary Turner   }
5295713a05bSZachary Turner 
5305713a05bSZachary Turner   if (Style.equals_lower("D")) {
5315713a05bSZachary Turner     // We only want to print the directory, so now just exit.
5325713a05bSZachary Turner     if (dir.empty())
5335713a05bSZachary Turner       Stream << "(empty)";
5345713a05bSZachary Turner     return;
5355713a05bSZachary Turner   }
5365713a05bSZachary Turner 
5375713a05bSZachary Turner   if (!file.empty())
5385713a05bSZachary Turner     Stream << file;
5395713a05bSZachary Turner }
540