Add Path and Twine components from LLVM. (#10)

This commit is contained in:
Peter Johnson
2017-08-06 23:26:42 -07:00
committed by GitHub
parent 25c8e873d0
commit 8418c39120
6 changed files with 2156 additions and 0 deletions

View File

@@ -0,0 +1,684 @@
//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the operating system Path API.
//
//===----------------------------------------------------------------------===//
#include "llvm/Path.h"
#include <cctype>
#include <cstring>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include "llvm/SmallString.h"
using namespace llvm;
namespace {
using llvm::StringRef;
using llvm::sys::path::is_separator;
#ifdef _WIN32
const char *separators = "\\/";
const char preferred_separator = '\\';
#else
const char separators = '/';
const char preferred_separator = '/';
#endif
StringRef find_first_component(StringRef path) {
// Look for this first component in the following order.
// * empty (in this case we return an empty string)
// * either C: or {//,\\}net.
// * {/,\}
// * {file,directory}name
if (path.empty())
return path;
#ifdef _WIN32
// C:
if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
path[1] == ':')
return path.substr(0, 2);
#endif
// //net
if ((path.size() > 2) &&
is_separator(path[0]) &&
path[0] == path[1] &&
!is_separator(path[2])) {
// Find the next directory separator.
size_t end = path.find_first_of(separators, 2);
return path.substr(0, end);
}
// {/,\}
if (is_separator(path[0]))
return path.substr(0, 1);
// * {file,directory}name
size_t end = path.find_first_of(separators);
return path.substr(0, end);
}
size_t filename_pos(StringRef str) {
if (str.size() == 2 &&
is_separator(str[0]) &&
str[0] == str[1])
return 0;
if (str.size() > 0 && is_separator(str[str.size() - 1]))
return str.size() - 1;
size_t pos = str.find_last_of(separators, str.size() - 1);
#ifdef _WIN32
if (pos == StringRef::npos)
pos = str.find_last_of(':', str.size() - 2);
#endif
if (pos == StringRef::npos ||
(pos == 1 && is_separator(str[0])))
return 0;
return pos + 1;
}
size_t root_dir_start(StringRef str) {
// case "c:/"
#ifdef _WIN32
if (str.size() > 2 &&
str[1] == ':' &&
is_separator(str[2]))
return 2;
#endif
// case "//"
if (str.size() == 2 &&
is_separator(str[0]) &&
str[0] == str[1])
return StringRef::npos;
// case "//net"
if (str.size() > 3 &&
is_separator(str[0]) &&
str[0] == str[1] &&
!is_separator(str[2])) {
return str.find_first_of(separators, 2);
}
// case "/"
if (str.size() > 0 && is_separator(str[0]))
return 0;
return StringRef::npos;
}
size_t parent_path_end(StringRef path) {
size_t end_pos = filename_pos(path);
bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
// Skip separators except for root dir.
size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
while(end_pos > 0 &&
(end_pos - 1) != root_dir_pos &&
is_separator(path[end_pos - 1]))
--end_pos;
if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
return StringRef::npos;
return end_pos;
}
} // end unnamed namespace
namespace llvm {
namespace sys {
namespace path {
const_iterator begin(StringRef path) {
const_iterator i;
i.Path = path;
i.Component = find_first_component(path);
i.Position = 0;
return i;
}
const_iterator end(StringRef path) {
const_iterator i;
i.Path = path;
i.Position = path.size();
return i;
}
const_iterator &const_iterator::operator++() {
assert(Position < Path.size() && "Tried to increment past end!");
// Increment Position to past the current component
Position += Component.size();
// Check for end.
if (Position == Path.size()) {
Component = StringRef();
return *this;
}
// Both POSIX and Windows treat paths that begin with exactly two separators
// specially.
bool was_net = Component.size() > 2 &&
is_separator(Component[0]) &&
Component[1] == Component[0] &&
!is_separator(Component[2]);
// Handle separators.
if (is_separator(Path[Position])) {
// Root dir.
if (was_net
#ifdef _WIN32
// c:/
|| Component.endswith(":")
#endif
) {
Component = Path.substr(Position, 1);
return *this;
}
// Skip extra separators.
while (Position != Path.size() &&
is_separator(Path[Position])) {
++Position;
}
// Treat trailing '/' as a '.'.
if (Position == Path.size()) {
--Position;
Component = ".";
return *this;
}
}
// Find next component.
size_t end_pos = Path.find_first_of(separators, Position);
Component = Path.slice(Position, end_pos);
return *this;
}
bool const_iterator::operator==(const const_iterator &RHS) const {
return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
}
ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
return Position - RHS.Position;
}
reverse_iterator rbegin(StringRef Path) {
reverse_iterator I;
I.Path = Path;
I.Position = Path.size();
return ++I;
}
reverse_iterator rend(StringRef Path) {
reverse_iterator I;
I.Path = Path;
I.Component = Path.substr(0, 0);
I.Position = 0;
return I;
}
reverse_iterator &reverse_iterator::operator++() {
// If we're at the end and the previous char was a '/', return '.' unless
// we are the root path.
size_t root_dir_pos = root_dir_start(Path);
if (Position == Path.size() &&
Path.size() > root_dir_pos + 1 &&
is_separator(Path[Position - 1])) {
--Position;
Component = ".";
return *this;
}
// Skip separators unless it's the root directory.
size_t end_pos = Position;
while(end_pos > 0 &&
(end_pos - 1) != root_dir_pos &&
is_separator(Path[end_pos - 1]))
--end_pos;
// Find next separator.
size_t start_pos = filename_pos(Path.substr(0, end_pos));
Component = Path.slice(start_pos, end_pos);
Position = start_pos;
return *this;
}
bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
Position == RHS.Position;
}
ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
return Position - RHS.Position;
}
StringRef root_path(StringRef path) {
const_iterator b = begin(path),
pos = b,
e = end(path);
if (b != e) {
bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
bool has_drive =
#ifdef _WIN32
b->endswith(":");
#else
false;
#endif
if (has_net || has_drive) {
if ((++pos != e) && is_separator((*pos)[0])) {
// {C:/,//net/}, so get the first two components.
return path.substr(0, b->size() + pos->size());
} else {
// just {C:,//net}, return the first component.
return *b;
}
}
// POSIX style root directory.
if (is_separator((*b)[0])) {
return *b;
}
}
return StringRef();
}
StringRef root_name(StringRef path) {
const_iterator b = begin(path),
e = end(path);
if (b != e) {
bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
bool has_drive =
#ifdef _WIN32
b->endswith(":");
#else
false;
#endif
if (has_net || has_drive) {
// just {C:,//net}, return the first component.
return *b;
}
}
// No path or no name.
return StringRef();
}
StringRef root_directory(StringRef path) {
const_iterator b = begin(path),
pos = b,
e = end(path);
if (b != e) {
bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
bool has_drive =
#ifdef _WIN32
b->endswith(":");
#else
false;
#endif
if ((has_net || has_drive) &&
// {C:,//net}, skip to the next component.
(++pos != e) && is_separator((*pos)[0])) {
return *pos;
}
// POSIX style root directory.
if (!has_net && is_separator((*b)[0])) {
return *b;
}
}
// No path or no root.
return StringRef();
}
StringRef relative_path(StringRef path) {
StringRef root = root_path(path);
return path.substr(root.size());
}
void append(SmallVectorImpl<char> &path, const Twine &a,
const Twine &b,
const Twine &c,
const Twine &d) {
SmallString<32> a_storage;
SmallString<32> b_storage;
SmallString<32> c_storage;
SmallString<32> d_storage;
SmallVector<StringRef, 4> components;
if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
for (auto &component : components) {
bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
bool component_has_sep = !component.empty() && is_separator(component[0]);
bool is_root_name = has_root_name(component);
if (path_has_sep) {
// Strip separators from beginning of component.
size_t loc = component.find_first_not_of(separators);
StringRef c = component.substr(loc);
// Append it.
path.append(c.begin(), c.end());
continue;
}
if (!component_has_sep && !(path.empty() || is_root_name)) {
// Add a separator.
path.push_back(preferred_separator);
}
path.append(component.begin(), component.end());
}
}
void append(SmallVectorImpl<char> &path,
const_iterator begin, const_iterator end) {
for (; begin != end; ++begin)
path::append(path, *begin);
}
StringRef parent_path(StringRef path) {
size_t end_pos = parent_path_end(path);
if (end_pos == StringRef::npos)
return StringRef();
else
return path.substr(0, end_pos);
}
void remove_filename(SmallVectorImpl<char> &path) {
size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
if (end_pos != StringRef::npos)
path.set_size(end_pos);
}
void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
StringRef p(path.begin(), path.size());
SmallString<32> ext_storage;
StringRef ext = extension.toStringRef(ext_storage);
// Erase existing extension.
size_t pos = p.find_last_of('.');
if (pos != StringRef::npos && pos >= filename_pos(p))
path.set_size(pos);
// Append '.' if needed.
if (ext.size() > 0 && ext[0] != '.')
path.push_back('.');
// Append extension.
path.append(ext.begin(), ext.end());
}
void replace_path_prefix(SmallVectorImpl<char> &Path,
const StringRef &OldPrefix,
const StringRef &NewPrefix) {
if (OldPrefix.empty() && NewPrefix.empty())
return;
StringRef OrigPath(Path.begin(), Path.size());
if (!OrigPath.startswith(OldPrefix))
return;
// If prefixes have the same size we can simply copy the new one over.
if (OldPrefix.size() == NewPrefix.size()) {
std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
return;
}
StringRef RelPath = OrigPath.substr(OldPrefix.size());
SmallString<256> NewPath;
path::append(NewPath, NewPrefix);
path::append(NewPath, RelPath);
Path.swap(NewPath);
}
void native(const Twine &path, SmallVectorImpl<char> &result) {
assert((!path.isSingleStringRef() ||
path.getSingleStringRef().data() != result.data()) &&
"path and result are not allowed to overlap!");
// Clear result.
result.clear();
path.toVector(result);
native(result);
}
void native(SmallVectorImpl<char> &Path) {
#ifdef _WIN32
std::replace(Path.begin(), Path.end(), '/', '\\');
#else
for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
if (*PI == '\\') {
auto PN = PI + 1;
if (PN < PE && *PN == '\\')
++PI; // increment once, the for loop will move over the escaped slash
else
*PI = '/';
}
}
#endif
}
StringRef filename(StringRef path) {
return *rbegin(path);
}
StringRef stem(StringRef path) {
StringRef fname = filename(path);
size_t pos = fname.find_last_of('.');
if (pos == StringRef::npos)
return fname;
else
if ((fname.size() == 1 && fname == ".") ||
(fname.size() == 2 && fname == ".."))
return fname;
else
return fname.substr(0, pos);
}
StringRef extension(StringRef path) {
StringRef fname = filename(path);
size_t pos = fname.find_last_of('.');
if (pos == StringRef::npos)
return StringRef();
else
if ((fname.size() == 1 && fname == ".") ||
(fname.size() == 2 && fname == ".."))
return StringRef();
else
return fname.substr(pos);
}
bool is_separator(char value) {
switch(value) {
#ifdef _WIN32
case '\\': // fall through
#endif
case '/': return true;
default: return false;
}
}
static const char preferred_separator_string[] = { preferred_separator, '\0' };
StringRef get_separator() {
return preferred_separator_string;
}
bool has_root_name(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !root_name(p).empty();
}
bool has_root_directory(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !root_directory(p).empty();
}
bool has_root_path(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !root_path(p).empty();
}
bool has_relative_path(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !relative_path(p).empty();
}
bool has_filename(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !filename(p).empty();
}
bool has_parent_path(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !parent_path(p).empty();
}
bool has_stem(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !stem(p).empty();
}
bool has_extension(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
return !extension(p).empty();
}
bool is_absolute(const Twine &path) {
SmallString<128> path_storage;
StringRef p = path.toStringRef(path_storage);
bool rootDir = has_root_directory(p),
#ifdef _WIN32
rootName = has_root_name(p);
#else
rootName = true;
#endif
return rootDir && rootName;
}
bool is_relative(const Twine &path) { return !is_absolute(path); }
StringRef remove_leading_dotslash(StringRef Path) {
// Remove leading "./" (or ".//" or "././" etc.)
while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1])) {
Path = Path.substr(2);
while (Path.size() > 0 && is_separator(Path[0]))
Path = Path.substr(1);
}
return Path;
}
static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot) {
SmallVector<StringRef, 16> components;
// Skip the root path, then look for traversal in the components.
StringRef rel = path::relative_path(path);
for (StringRef C : llvm::make_range(path::begin(rel), path::end(rel))) {
if (C == ".")
continue;
if (remove_dot_dot) {
if (C == "..") {
if (!components.empty())
components.pop_back();
continue;
}
}
components.push_back(C);
}
SmallString<256> buffer = path::root_path(path);
for (StringRef C : components)
path::append(buffer, C);
return buffer;
}
bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot) {
StringRef p(path.data(), path.size());
SmallString<256> result = remove_dots(p, remove_dot_dot);
if (result == path)
return false;
path.swap(result);
return true;
}
} // end namespace path
} // end namespace sys
} // end namespace llvm
// Include the truly platform-specific parts.
#ifdef _WIN32
#include "Windows/Path.inc"
#else
#include "Unix/Path.inc"
#endif
namespace llvm {
namespace sys {
namespace path {
bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
const Twine &Path2, const Twine &Path3) {
if (getUserCacheDir(Result)) {
append(Result, Path1, Path2, Path3);
return true;
}
return false;
}
} // end namespace path
} // end namsspace sys
} // end namespace llvm

View File

@@ -0,0 +1,169 @@
//===-- Twine.cpp - Fast Temporary String Concatenation -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Twine.h"
#include "llvm/SmallString.h"
#include "llvm/raw_ostream.h"
using namespace llvm;
std::string Twine::str() const {
// If we're storing only a std::string, just return it.
if (LHSKind == StdStringKind && RHSKind == EmptyKind)
return *LHS.stdString;
// Otherwise, flatten and copy the contents first.
SmallString<256> Vec;
return toStringRef(Vec).str();
}
void Twine::toVector(SmallVectorImpl<char> &Out) const {
raw_svector_ostream OS(Out);
print(OS);
}
StringRef Twine::toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const {
if (isUnary()) {
switch (getLHSKind()) {
case CStringKind:
// Already null terminated, yay!
return StringRef(LHS.cString);
case StdStringKind: {
const std::string *str = LHS.stdString;
return StringRef(str->c_str(), str->size());
}
default:
break;
}
}
toVector(Out);
Out.push_back(0);
Out.pop_back();
return StringRef(Out.data(), Out.size());
}
void Twine::printOneChild(raw_ostream &OS, Child Ptr,
NodeKind Kind) const {
switch (Kind) {
case Twine::NullKind: break;
case Twine::EmptyKind: break;
case Twine::TwineKind:
Ptr.twine->print(OS);
break;
case Twine::CStringKind:
OS << Ptr.cString;
break;
case Twine::StdStringKind:
OS << *Ptr.stdString;
break;
case Twine::StringRefKind:
OS << *Ptr.stringRef;
break;
case Twine::SmallStringKind:
OS << *Ptr.smallString;
break;
case Twine::CharKind:
OS << Ptr.character;
break;
case Twine::DecUIKind:
OS << Ptr.decUI;
break;
case Twine::DecIKind:
OS << Ptr.decI;
break;
case Twine::DecULKind:
OS << *Ptr.decUL;
break;
case Twine::DecLKind:
OS << *Ptr.decL;
break;
case Twine::DecULLKind:
OS << *Ptr.decULL;
break;
case Twine::DecLLKind:
OS << *Ptr.decLL;
break;
case Twine::UHexKind:
OS.write_hex(*Ptr.uHex);
break;
}
}
void Twine::printOneChildRepr(raw_ostream &OS, Child Ptr,
NodeKind Kind) const {
switch (Kind) {
case Twine::NullKind:
OS << "null"; break;
case Twine::EmptyKind:
OS << "empty"; break;
case Twine::TwineKind:
OS << "rope:";
Ptr.twine->printRepr(OS);
break;
case Twine::CStringKind:
OS << "cstring:\""
<< Ptr.cString << "\"";
break;
case Twine::StdStringKind:
OS << "std::string:\""
<< Ptr.stdString << "\"";
break;
case Twine::StringRefKind:
OS << "stringref:\""
<< Ptr.stringRef << "\"";
break;
case Twine::SmallStringKind:
OS << "smallstring:\"" << *Ptr.smallString << "\"";
break;
case Twine::CharKind:
OS << "char:\"" << Ptr.character << "\"";
break;
case Twine::DecUIKind:
OS << "decUI:\"" << Ptr.decUI << "\"";
break;
case Twine::DecIKind:
OS << "decI:\"" << Ptr.decI << "\"";
break;
case Twine::DecULKind:
OS << "decUL:\"" << *Ptr.decUL << "\"";
break;
case Twine::DecLKind:
OS << "decL:\"" << *Ptr.decL << "\"";
break;
case Twine::DecULLKind:
OS << "decULL:\"" << *Ptr.decULL << "\"";
break;
case Twine::DecLLKind:
OS << "decLL:\"" << *Ptr.decLL << "\"";
break;
case Twine::UHexKind:
OS << "uhex:\"" << Ptr.uHex << "\"";
break;
}
}
void Twine::print(raw_ostream &OS) const {
printOneChild(OS, LHS, getLHSKind());
printOneChild(OS, RHS, getRHSKind());
}
void Twine::printRepr(raw_ostream &OS) const {
OS << "(Twine ";
printOneChildRepr(OS, LHS, getLHSKind());
OS << " ";
printOneChildRepr(OS, RHS, getRHSKind());
OS << ")";
}
void Twine::dump() const {
print(errs());
}
void Twine::dumpRepr() const {
printRepr(errs());
}

View File

@@ -0,0 +1,129 @@
//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Unix specific implementation of the Path API.
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only generic UNIX code that
//=== is guaranteed to work on *all* UNIX variants.
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
namespace llvm {
namespace sys {
namespace path {
bool home_directory(SmallVectorImpl<char> &result) {
if (char *RequestedDir = std::getenv("HOME")) {
result.clear();
result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
return true;
}
return false;
}
static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
// On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
// macros defined in <unistd.h> on darwin >= 9
int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
: _CS_DARWIN_USER_CACHE_DIR;
size_t ConfLen = confstr(ConfName, nullptr, 0);
if (ConfLen > 0) {
do {
Result.resize(ConfLen);
ConfLen = confstr(ConfName, Result.data(), Result.size());
} while (ConfLen > 0 && ConfLen != Result.size());
if (ConfLen > 0) {
assert(Result.back() == 0);
Result.pop_back();
return true;
}
Result.clear();
}
#endif
return false;
}
static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
// First try using XDG_CACHE_HOME env variable,
// as specified in XDG Base Directory Specification at
// http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
Result.clear();
Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
return true;
}
// Try Darwin configuration query
if (getDarwinConfDir(false, Result))
return true;
// Use "$HOME/.cache" if $HOME is available
if (home_directory(Result)) {
append(Result, ".cache");
return true;
}
return false;
}
static const char *getEnvTempDir() {
// Check whether the temporary directory is specified by an environment
// variable.
const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
for (const char *Env : EnvironmentVariables) {
if (const char *Dir = std::getenv(Env))
return Dir;
}
return nullptr;
}
static const char *getDefaultTempDir(bool ErasedOnReboot) {
#ifdef P_tmpdir
if ((bool)P_tmpdir)
return P_tmpdir;
#endif
if (ErasedOnReboot)
return "/tmp";
return "/var/tmp";
}
void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
Result.clear();
if (ErasedOnReboot) {
// There is no env variable for the cache directory.
if (const char *RequestedDir = getEnvTempDir()) {
Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
return;
}
}
if (getDarwinConfDir(ErasedOnReboot, Result))
return;
const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
}
} // end namespace path
} // end namespace sys
} // end namespace llvm

View File

@@ -0,0 +1,175 @@
//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Windows specific implementation of the Path API.
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only generic Windows code that
//=== is guaranteed to work on *all* Windows variants.
//===----------------------------------------------------------------------===//
#include "llvm/STLExtras.h"
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>
#include <shlobj.h>
#include "llvm/WindowsError.h"
#ifdef _MSC_VER
# pragma comment(lib, "shell32.lib")
# pragma comment(lib, "ole32.lib")
#endif
namespace llvm {
namespace sys {
namespace windows {
std::error_code UTF8ToUTF16(llvm::StringRef utf8,
llvm::SmallVectorImpl<wchar_t> &utf16) {
if (!utf8.empty()) {
int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
utf8.size(), utf16.begin(), 0);
if (len == 0)
return mapWindowsError(::GetLastError());
utf16.reserve(len + 1);
utf16.set_size(len);
len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
utf8.size(), utf16.begin(), utf16.size());
if (len == 0)
return mapWindowsError(::GetLastError());
}
// Make utf16 null terminated.
utf16.push_back(0);
utf16.pop_back();
return std::error_code();
}
static
std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
size_t utf16_len,
llvm::SmallVectorImpl<char> &utf8) {
if (utf16_len) {
// Get length.
int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
0, NULL, NULL);
if (len == 0)
return mapWindowsError(::GetLastError());
utf8.reserve(len);
utf8.set_size(len);
// Now do the actual conversion.
len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
utf8.size(), NULL, NULL);
if (len == 0)
return mapWindowsError(::GetLastError());
}
// Make utf8 null terminated.
utf8.push_back(0);
utf8.pop_back();
return std::error_code();
}
std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
llvm::SmallVectorImpl<char> &utf8) {
return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
}
std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
llvm::SmallVectorImpl<char> &utf8) {
return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
}
} // end namespace windows
using llvm::sys::windows::UTF8ToUTF16;
using llvm::sys::windows::UTF16ToUTF8;
namespace path {
static bool getKnownFolderPath(KNOWNFOLDERID folderId,
SmallVectorImpl<char> &result) {
wchar_t *path = nullptr;
if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
return false;
bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
::CoTaskMemFree(path);
return ok;
}
bool getUserCacheDir(SmallVectorImpl<char> &Result) {
return getKnownFolderPath(FOLDERID_LocalAppData, Result);
}
bool home_directory(SmallVectorImpl<char> &result) {
return getKnownFolderPath(FOLDERID_Profile, result);
}
static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
SmallVector<wchar_t, 1024> Buf;
size_t Size = 1024;
do {
Buf.reserve(Size);
Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
if (Size == 0)
return false;
// Try again with larger buffer.
} while (Size > Buf.capacity());
Buf.set_size(Size);
return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
}
static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
for (auto *Env : EnvironmentVariables) {
if (getTempDirEnvVar(Env, Res))
return true;
}
return false;
}
void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
(void)ErasedOnReboot;
Result.clear();
// Check whether the temporary directory is specified by an environment var.
// This matches GetTempPath logic to some degree. GetTempPath is not used
// directly as it cannot handle evn var longer than 130 chars on Windows 7
// (fixed on Windows 8).
if (getTempDirEnvVar(Result)) {
assert(!Result.empty() && "Unexpected empty path");
native(Result); // Some Unix-like shells use Unix path separator in $TMP.
//fs::make_absolute(Result); // Make it absolute if not already.
return;
}
// Fall back to a system default.
const char *DefaultResult = "C:\\Temp";
Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
}
} // end namespace path
} // end namespace sys
} // end namespace llvm