Hi akyrtzi,

Provides a way to create a virtual file system using a YAML file that
supports mapping a file to a path on an 'external' file system. The
external file system will typically be the 'real' file system, but for
testing it can be changed.

A future patch will add a clang option to allow the user to specify such
a file and overlay it, but for now this code is only exercised by the
unit tests.

http://llvm-reviews.chandlerc.com/D2835

Files:
  include/clang/Basic/VirtualFileSystem.h
  lib/Basic/VirtualFileSystem.cpp
  unittests/Basic/VirtualFileSystemTest.cpp
Index: include/clang/Basic/VirtualFileSystem.h
===================================================================
--- include/clang/Basic/VirtualFileSystem.h
+++ include/clang/Basic/VirtualFileSystem.h
@@ -17,6 +17,7 @@
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/SourceMgr.h"
 
 namespace llvm {
 class MemoryBuffer;
@@ -157,6 +158,16 @@
                                    OwningPtr<File> &Result) LLVM_OVERRIDE;
 };
 
+/// \brief Get a globally unique ID for a virtual file or directory.
+llvm::sys::fs::UniqueID getNextVirtualUniqueID();
+
+/// \brief Gets a \p FileSystem for a virtual file system described by a YAML
+/// file.
+IntrusiveRefCntPtr<FileSystem>
+getVFSFromYAMLFile(llvm::MemoryBuffer *Buffer, llvm::SourceMgr::DiagHandlerTy,
+                   IntrusiveRefCntPtr<FileSystem> ExternalFS =
+                     getRealFileSystem());
+
 } // end namespace vfs
 } // end namespace clang
 #endif // LLVM_CLANG_BASIC_VIRTUAL_FILE_SYSTEM_H
Index: lib/Basic/VirtualFileSystem.cpp
===================================================================
--- lib/Basic/VirtualFileSystem.cpp
+++ lib/Basic/VirtualFileSystem.cpp
@@ -10,10 +10,14 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Config/config.h"
+#include "llvm/Support/Atomic.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/YAMLParser.h"
 
 using namespace clang;
 using namespace clang::vfs;
@@ -191,3 +195,512 @@
   }
   return error_code(errc::no_such_file_or_directory, system_category());
 }
+
+//===-----------------------------------------------------------------------===/
+// VFSFromYAML implementation
+//===-----------------------------------------------------------------------===/
+
+namespace {
+
+/// \brief Represents the value of a 'type' field.
+enum EntryKind {
+  EK_Directory,
+  EK_File
+};
+
+/// \brief A single file or directory in the VFS.
+class Entry {
+  EntryKind Kind;
+  std::string Name;
+public:
+  virtual ~Entry();
+  Entry(EntryKind K, const std::string &Name) : Kind(K), Name(Name) {}
+  StringRef getName() const { return Name; }
+  EntryKind getKind() const { return Kind; }
+};
+
+class DirectoryEntry : public Entry {
+  std::vector<Entry *> Contents;
+  Status S;
+public:
+  virtual ~DirectoryEntry();
+  DirectoryEntry(const std::string &Name, const std::vector<Entry *> &Contents,
+                 const Status &S)
+      : Entry(EK_Directory, Name), Contents(Contents), S(S) {}
+  Status getStatus() { return S; }
+  typedef std::vector<Entry *>::iterator iterator;
+  iterator contents_begin() { return Contents.begin(); }
+  iterator contents_end() { return Contents.end(); }
+  static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
+};
+
+class FileEntry : public Entry {
+  std::string ExternalContents;
+public:
+  FileEntry(const std::string &Name, const std::string &ExternalContents)
+      : Entry(EK_File, Name), ExternalContents(ExternalContents) {}
+  StringRef getExternalContents() const { return ExternalContents; }
+  static bool classof(const Entry *E) { return E->getKind() == EK_File; }
+};
+
+/// \brief A virtual file system parsed from a YAML file.
+///
+/// Currently, this class allows creating virtual directories and mapping
+/// virtual file paths to existing external files, available in \p ExternalFS.
+///
+/// The basic structure of the parsed file is:
+/// {
+///   <optional configuration>
+///   'roots': [
+///              <directory entries>
+///            ]
+/// }
+///
+/// Possible configuration settings are
+///   'case-sensitive': <boolean>
+///
+/// Virtual directories are represented as
+/// {
+///   'type': 'directory',
+///   'name': <string>,
+///   'contents': [ <file or directory entries> ]
+/// }
+///
+/// The default attributes for virtual directories are:
+///   MTime = now() when created
+///   Perms = 0777
+///   User = Group = 0
+///   Size = 0
+///   UniqueID = unspecified unique value
+///
+/// Re-mapped files are represented as
+/// {
+///   'type': 'file',
+///   'name': <string>,
+///   'external-contents': <path to external file>)
+/// }
+///
+/// and inherit their attributes from the external contents.
+///
+/// In both cases, the 'name' field must be a single path component (containing
+/// no separators).
+class VFSFromYAML : public vfs::FileSystem {
+  std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
+  /// \brief The file system to use for 'external-contents'.
+  IntrusiveRefCntPtr<FileSystem> ExternalFS; ///< The file system to use for
+
+  /// @name Configuration
+  /// @{
+  bool CaseSensitive; ///< Whether to perform case-sensitive comparisons.
+  /// @}
+
+  friend class VFSFromYAMLParser;
+
+private:
+  VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
+      : ExternalFS(ExternalFS) {
+    llvm::Triple Triple(LLVM_HOST_TRIPLE);
+    CaseSensitive = Triple.isOSDarwin() || Triple.isOSWindows();
+  }
+
+  /// \brief Looks up \p Path in \p Roots.
+  ErrorOr<Entry *> lookupPath(const Twine &Path);
+
+  /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
+  /// recursing into the contents of \p From if it is a directory.
+  ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
+                              sys::path::const_iterator End,
+                              Entry *From);
+
+
+public:
+  ~VFSFromYAML();
+
+  /// \brief Parses \p Buffer, which is expected to be in YAML format and
+  /// returns a virtual file system representing its contents.
+  static VFSFromYAML *Create(MemoryBuffer *Buffer,
+                             SourceMgr::DiagHandlerTy DiagHandler,
+                             IntrusiveRefCntPtr<FileSystem> ExternalFS);
+
+  ErrorOr<Status> status(const Twine &Path) LLVM_OVERRIDE;
+  error_code openFileForRead(const Twine &Path,
+                             OwningPtr<File> &Result) LLVM_OVERRIDE;
+};
+
+// A helper class to hold the common YAML parsing state.
+class VFSFromYAMLParser {
+  yaml::Stream &Stream;
+
+  void error(yaml::Node *N, const Twine &Msg) {
+    Stream.printError(N, Msg);
+  }
+
+  // false on error
+  bool parseScalarString(yaml::Node *N, StringRef &Result,
+                         SmallVectorImpl<char> &Storage) {
+    yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
+    if (!S) {
+      error(N, "expected string");
+      return false;
+    }
+    Result = S->getValue(Storage);
+    return true;
+  }
+
+  // false on error
+  bool parseScalarBool(yaml::Node *N, bool &Result) {
+    SmallString<5> Storage;
+    StringRef Value;
+    if (!parseScalarString(N, Value, Storage))
+      return false;
+
+    if (Value.equals_lower("true") || Value.equals_lower("on") ||
+        Value.equals_lower("yes") || Value == "1") {
+      Result = true;
+      return true;
+    } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
+               Value.equals_lower("no") || Value == "0") {
+      Result = false;
+      return true;
+    }
+
+    error(N, "expected boolean value");
+    return false;
+  }
+
+  Entry *parseEntry(yaml::Node *N) {
+    yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
+    if (!M) {
+      error(N, "expected mapping node for file or directory entry");
+      return NULL;
+    }
+
+    bool hasName = false;
+    bool hasKind = false;
+    bool hasContents = false; // external or otherwise
+    bool hasExternalContents = false;
+    std::vector<Entry *> EntryArrayContents;
+    std::string ExternalContents;
+    std::string Name;
+    EntryKind Kind;
+
+    for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E; ++I) {
+      StringRef Key;
+      // Reuse the buffer for key and value, since we don't look at key after
+      // parsing value.
+      SmallString<256> Buffer;
+      if (!parseScalarString(I->getKey(), Key, Buffer))
+        return NULL;
+
+      StringRef Value;
+      if (Key == "name") {
+        if (!parseScalarString(I->getValue(), Value, Buffer))
+          return NULL;
+        hasName = true;
+        Name = Value;
+        if (sys::path::has_parent_path(Name)) {
+          error(I->getValue(), "unexpected path separator in name");
+          return NULL;
+        }
+      } else if (Key == "type") {
+        hasKind = true;
+        if (!parseScalarString(I->getValue(), Value, Buffer))
+          return NULL;
+        if (Value == "file")
+          Kind = EK_File;
+        else if (Value == "directory")
+          Kind = EK_Directory;
+        else {
+          error(I->getValue(), "unknown value for 'type'");
+          return NULL;
+        }
+      } else if (Key == "contents") {
+        if (hasContents) {
+          error(I->getKey(),
+                "entry already has 'contents' or 'external-contents'");
+          return NULL;
+        }
+
+        hasContents = true;
+        yaml::SequenceNode *Contents =
+          dyn_cast<yaml::SequenceNode>(I->getValue());
+        if (!Contents) {
+          // FIXME: this is only for directories, what about files?
+          error(I->getValue(), "expected array");
+          return NULL;
+        }
+
+        for (yaml::SequenceNode::iterator I = Contents->begin(),
+             E = Contents->end(); I != E; ++I) {
+          if (Entry *E = parseEntry(&*I))
+            EntryArrayContents.push_back(E);
+          else
+            return NULL;
+        }
+      } else if (Key == "external-contents") {
+        if (hasContents) {
+          error(I->getKey(),
+                "entry already has 'contents' or 'external-contents'");
+          return NULL;
+        }
+        hasExternalContents = true;
+        hasContents = true;
+        if (!parseScalarString(I->getValue(), Value, Buffer))
+          return NULL;
+        ExternalContents = Value;
+      } else {
+        Stream.printError(I->getKey(), "unknown key in file or directory entry");
+        return NULL;
+      }
+    }
+
+    if (Stream.failed())
+      return NULL;
+
+    if (!hasName) {
+      error(N, "missing key 'name'");
+      return NULL;
+    }
+    if (!hasKind) {
+      error(N, "missing key 'type'");
+      return NULL;
+    }
+    if (!hasContents) {
+      error(N, "missing key 'contents' or 'external-contents'");
+      return NULL;
+    }
+    if (Kind == EK_Directory && hasExternalContents) {
+      error(N, "'external-contents' for directory not supported");
+      return NULL;
+    }
+
+    if (Kind == EK_File) {
+      return new FileEntry(Name, ExternalContents);
+    } else { // directory
+      return new DirectoryEntry(Name, EntryArrayContents, Status("", "",
+        getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
+        file_type::directory_file, sys::fs::all_all));
+    }
+  }
+
+public:
+  VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
+
+  // false on error
+  bool parse(yaml::Node *Root, VFSFromYAML *FS) {
+    yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
+    if (!Top) {
+      error(Root, "expected mapping node");
+      return false;
+    }
+
+    // Parse configuration and 'roots'
+    yaml::SequenceNode *Roots = 0;
+    for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
+         ++I) {
+      SmallString<10> KeyBuffer;
+      StringRef Key;
+      if (!parseScalarString(I->getKey(), Key, KeyBuffer))
+        return false;
+
+      if (Key == "roots") {
+        Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
+        if (!Roots) {
+          error(I->getValue(), "expected array");
+          return false;
+        }
+
+        for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
+             I != E; ++I) {
+          if (Entry *E = parseEntry(&*I))
+            FS->Roots.push_back(E);
+          else
+            return false;
+        }
+      } else if (Key == "case-sensitive") {
+        if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
+          return false;
+      } else {
+        error(I->getKey(), "unknown key");
+        return false;
+      }
+    }
+
+    if (Stream.failed())
+      return false;
+
+    if (!Roots) {
+      error(Root, "missing key 'roots'");
+      return false;
+    }
+    return true;
+  }
+};
+} // end of anonymous namespace
+
+Entry::~Entry() {}
+DirectoryEntry::~DirectoryEntry() {
+  for (std::vector<Entry *>::iterator I = Contents.begin(), E = Contents.end();
+       I != E; ++I) {
+    delete *I;
+  }
+}
+
+VFSFromYAML::~VFSFromYAML() {
+  for (std::vector<Entry *>::iterator I = Roots.begin(), E =Roots.end(); I != E;
+       ++I) {
+    delete *I;
+  }
+}
+
+VFSFromYAML *VFSFromYAML::Create(MemoryBuffer *Buffer,
+                                 SourceMgr::DiagHandlerTy DiagHandler,
+                                 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
+
+  SourceMgr SM;
+  yaml::Stream Stream(Buffer, SM);
+
+
+  SM.setDiagHandler(DiagHandler);
+  yaml::document_iterator DI = Stream.begin();
+  yaml::Node *Root = DI->getRoot();
+
+  if (DI == Stream.end() || !Root) {
+    SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
+    return NULL;
+  }
+
+  VFSFromYAMLParser P(Stream);
+
+  OwningPtr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
+  if (!P.parse(Root, FS.get()))
+    return NULL;
+
+  return FS.take();
+}
+
+error_code normalizePath(StringRef Path, SmallVectorImpl<char> &Result) {
+  sys::path::const_iterator I = sys::path::begin(Path);
+  sys::path::const_iterator End = sys::path::end(Path);
+
+  std::vector<StringRef> Components;
+  for ( ; I != End; ++I) {
+    if (I->equals("."))
+      continue;
+    if (I->equals("..")) {
+      if (Components.empty())
+        return error_code(errc::invalid_argument, system_category());
+      Components.pop_back();
+      if (Components.empty())
+        return error_code(errc::invalid_argument, system_category());
+      continue;
+    }
+    Components.push_back(*I);
+  }
+
+  for (std::vector<StringRef>::iterator I = Components.begin(),
+       E = Components.end(); I != E; ++I)
+    sys::path::append(Result, *I);
+  return error_code::success();
+}
+
+ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
+  SmallVector<char, 256> Storage;
+  StringRef Path = Path_.toNullTerminatedStringRef(Storage);
+
+  if (Path.empty())
+    return error_code(errc::invalid_argument, system_category());
+
+  SmallString<256> NormalizedPath;
+  if (error_code EC = normalizePath(Path, NormalizedPath))
+    return EC;
+
+  sys::path::const_iterator Start = sys::path::begin(NormalizedPath);
+  sys::path::const_iterator End = sys::path::end(NormalizedPath);
+  for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
+       I != E; ++I) {
+    ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
+    if (Result || Result.getError() != errc::no_such_file_or_directory)
+      return Result;
+  }
+  return error_code(errc::no_such_file_or_directory, system_category());
+}
+
+ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
+                                         sys::path::const_iterator End,
+                                         Entry *From) {
+  if (CaseSensitive ? !Start->equals(From->getName())
+                    : !Start->equals_lower(From->getName()))
+    // failure to match
+    return error_code(errc::no_such_file_or_directory, system_category());
+
+  ++Start;
+
+  if (Start == End) {
+    // Match!
+    return From;
+  }
+
+  DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
+  if (!DE)
+    return error_code(errc::not_a_directory, system_category());
+
+  for (DirectoryEntry::iterator I = DE->contents_begin(),
+       E = DE->contents_end(); I != E; ++I) {
+    ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
+    if (Result || Result.getError() != errc::no_such_file_or_directory)
+      return Result;
+  }
+  return error_code(errc::no_such_file_or_directory, system_category());
+}
+
+ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
+  ErrorOr<Entry *> Result = lookupPath(Path);
+  if (!Result)
+    return Result.getError();
+
+  std::string PathStr(Path.str());
+  if (FileEntry *F = dyn_cast<FileEntry>(*Result)) {
+    ErrorOr<Status> S = ExternalFS->status(F->getExternalContents());
+    if (S) {
+      assert(S->getName() == S->getExternalName() &&
+             S->getName() == F->getExternalContents());
+      S->setName(PathStr);
+    }
+    return S;
+  } else { // directory
+    DirectoryEntry *DE = cast<DirectoryEntry>(*Result);
+    Status S = DE->getStatus();
+    S.setName(PathStr);
+    S.setExternalName(PathStr);
+    return S;
+  }
+}
+
+error_code VFSFromYAML::openFileForRead(const Twine &Path,
+                                        OwningPtr<vfs::File> &Result) {
+  ErrorOr<Entry *> E = lookupPath(Path);
+  if (!E)
+    return E.getError();
+
+  FileEntry *F = dyn_cast<FileEntry>(*E);
+  if (!F) // FIXME: errc::not_a_file?
+    return error_code(errc::invalid_argument, system_category());
+
+  return ExternalFS->openFileForRead(Path, Result);
+}
+
+IntrusiveRefCntPtr<FileSystem>
+vfs::getVFSFromYAMLFile(MemoryBuffer *Buffer,
+                        SourceMgr::DiagHandlerTy DiagHandler,
+                        IntrusiveRefCntPtr<FileSystem> ExternalFS){
+  return VFSFromYAML::Create(Buffer, DiagHandler, ExternalFS);
+}
+
+UniqueID vfs::getNextVirtualUniqueID() {
+  static volatile sys::cas_flag UID = 0;
+  sys::cas_flag ID = llvm::sys::AtomicIncrement(&UID);
+  // The following assumes that uint64_t max will never collide with a real
+  // dev_t value from the OS.
+  return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
+}
Index: unittests/Basic/VirtualFileSystemTest.cpp
===================================================================
--- unittests/Basic/VirtualFileSystemTest.cpp
+++ unittests/Basic/VirtualFileSystemTest.cpp
@@ -8,7 +8,9 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/SourceMgr.h"
 #include "gtest/gtest.h"
 #include <map>
 using namespace clang;
@@ -214,3 +216,213 @@
   ASSERT_EQ(errc::success, Status.getError());
   EXPECT_EQ(0200, Status->getPermissions());
 }
+
+static void NullDiagHandler(const SMDiagnostic &, void *) {}
+
+static IntrusiveRefCntPtr<vfs::FileSystem>
+getFromYAMLString(StringRef Content,
+    IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
+  MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(Content);
+  return getVFSFromYAMLFile(Buffer, NullDiagHandler, ExternalFS);
+}
+
+TEST(VirtualFileSystemTest, basicVFSFromYAML) {
+  IntrusiveRefCntPtr<vfs::FileSystem> FS;
+  FS = getFromYAMLString("");
+  EXPECT_EQ(NULL, FS.getPtr());
+  FS = getFromYAMLString("[]");
+  EXPECT_EQ(NULL, FS.getPtr());
+  FS = getFromYAMLString("'string'");
+  EXPECT_EQ(NULL, FS.getPtr());
+}
+
+TEST(VirtualFileSystemTest, mappedFiles) {
+  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+  Lower->addRegularFile("/foo/bar/a");
+  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+    "{ 'roots': [\n"
+    "{\n"
+    "  'type': 'directory',\n"
+    "  'name': '/',\n"
+    "  'contents': [ {\n"
+    "                  'type': 'file',\n"
+    "                  'name': 'file1',\n"
+    "                  'external-contents': '/foo/bar/a'\n"
+    "                },\n"
+    "                {\n"
+    "                  'type': 'file',\n"
+    "                  'name': 'file2',\n"
+    "                  'external-contents': '/foo/b'\n"
+    "                }\n"
+    "              ]\n"
+    "}\n"
+    "]\n"
+    "}", Lower);
+  ASSERT_TRUE(FS.getPtr());
+
+  IntrusiveRefCntPtr<vfs::OverlayFileSystem>
+    O(new vfs::OverlayFileSystem(Lower));
+  O->pushOverlay(FS);
+
+  // file
+  ErrorOr<vfs::Status> S = O->status("/file1");
+  ASSERT_EQ(errc::success, S.getError());
+  EXPECT_EQ("/file1", S->getName());
+  EXPECT_EQ("/foo/bar/a", S->getExternalName());
+
+  ErrorOr<vfs::Status> SLower = O->status("/foo/bar/a");
+  EXPECT_EQ("/foo/bar/a", SLower->getName());
+  EXPECT_TRUE(S->equivalent(*SLower));
+
+  // directory
+  S = O->status("/");
+  ASSERT_EQ(errc::success, S.getError());
+  EXPECT_TRUE(S->isDirectory());
+  EXPECT_TRUE(S->equivalent(*O->status("/"))); // non-volatile UniqueID
+
+  // path normalization
+  EXPECT_TRUE(S->equivalent(*O->status("/.")));
+  EXPECT_TRUE(S->equivalent(*O->status("/././.")));
+  EXPECT_TRUE(S->equivalent(*O->status("////.////.///")));
+  S = O->status("/foo/bar/../../file1");
+  EXPECT_EQ(errc::success, S.getError());
+  S = O->status("/foo/bar/../../..");
+  EXPECT_EQ(errc::invalid_argument, S.getError());
+
+  // broken mapping
+  EXPECT_EQ(errc::no_such_file_or_directory, O->status("/file2").getError());
+}
+
+TEST(VirtualFileSystemTest, caseSensitive) {
+  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+  Lower->addRegularFile("/foo/bar/a");
+  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+    "{ 'case-sensitive': 'false',\n"
+    "  'roots': [\n"
+    "{\n"
+    "  'type': 'directory',\n"
+    "  'name': '/',\n"
+    "  'contents': [ {\n"
+    "                  'type': 'file',\n"
+    "                  'name': 'XX',\n"
+    "                  'external-contents': '/foo/bar/a'\n"
+    "                }\n"
+    "              ]\n"
+    "}]}", Lower);
+  ASSERT_TRUE(FS.getPtr());
+
+  IntrusiveRefCntPtr<vfs::OverlayFileSystem>
+    O(new vfs::OverlayFileSystem(Lower));
+  O->pushOverlay(FS);
+
+  ErrorOr<vfs::Status> S = O->status("/XX");
+  ASSERT_EQ(errc::success, S.getError());
+
+  ErrorOr<vfs::Status> SS = O->status("/xx");
+  ASSERT_EQ(errc::success, SS.getError());
+  EXPECT_TRUE(S->equivalent(*SS));
+  SS = O->status("/xX");
+  EXPECT_TRUE(S->equivalent(*SS));
+  SS = O->status("/Xx");
+  EXPECT_TRUE(S->equivalent(*SS));
+}
+
+TEST(VirtualFileSystemTest, caseInsensitive) {
+  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+  Lower->addRegularFile("/foo/bar/a");
+  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+    "{ 'case-sensitive': 'true',\n"
+    "  'roots': [\n"
+    "{\n"
+    "  'type': 'directory',\n"
+    "  'name': '/',\n"
+    "  'contents': [ {\n"
+    "                  'type': 'file',\n"
+    "                  'name': 'XX',\n"
+    "                  'external-contents': '/foo/bar/a'\n"
+    "                }\n"
+    "              ]\n"
+    "}]}", Lower);
+  ASSERT_TRUE(FS.getPtr());
+
+  IntrusiveRefCntPtr<vfs::OverlayFileSystem>
+    O(new vfs::OverlayFileSystem(Lower));
+  O->pushOverlay(FS);
+
+  ErrorOr<vfs::Status> SS = O->status("/xx");
+  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
+  SS = O->status("/xX");
+  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
+  SS = O->status("/Xx");
+  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
+}
+
+TEST(VirtualFileSystemTest, illegalVFSFile) {
+  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+
+  // invalid YAML at top-level
+  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+    "{]", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  // invalid YAML in roots
+  FS = getFromYAMLString(
+    "{ 'roots':[}", Lower);
+  // invalid YAML in directory
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}", Lower);
+  ASSERT_FALSE(FS.getPtr());
+
+  // invalid configuration
+  FS = getFromYAMLString(
+    "{ 'knobular': 'true', 'roots':[] }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+
+  // invalid roots
+  FS = getFromYAMLString(
+    "{ 'roots':'' }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':{} }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+
+  // invalid entries
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'file', 'name': [], 'external-contents': 'other' }",
+    Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
+    Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
+    Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
+    Lower);
+  ASSERT_FALSE(FS.getPtr());
+
+  // missing mandatory fields
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+  FS = getFromYAMLString(
+    "{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
+  ASSERT_FALSE(FS.getPtr());
+}
_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits

Reply via email to