blob: 63302b741e76bda50ab691c674b7816d5939e695 [file] [log] [blame]
Ben Langmuirc8130a72014-02-20 21:59:23 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This file implements the VirtualFileSystem interface.
10//===----------------------------------------------------------------------===//
11
12#include "clang/Basic/VirtualFileSystem.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000013#include "llvm/ADT/DenseMap.h"
Justin Bogner9c785292014-05-20 21:43:27 +000014#include "llvm/ADT/iterator_range.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000017#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000018#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000019#include "llvm/Support/Path.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000020#include "llvm/Support/YAMLParser.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000021#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000022#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000023
24using namespace clang;
25using namespace clang::vfs;
26using namespace llvm;
27using llvm::sys::fs::file_status;
28using llvm::sys::fs::file_type;
29using llvm::sys::fs::perms;
30using llvm::sys::fs::UniqueID;
31
32Status::Status(const file_status &Status)
33 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
34 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000035 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000036
37Status::Status(StringRef Name, StringRef ExternalName, UniqueID UID,
38 sys::TimeValue MTime, uint32_t User, uint32_t Group,
39 uint64_t Size, file_type Type, perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000040 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000041 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000042
43bool Status::equivalent(const Status &Other) const {
44 return getUniqueID() == Other.getUniqueID();
45}
46bool Status::isDirectory() const {
47 return Type == file_type::directory_file;
48}
49bool Status::isRegularFile() const {
50 return Type == file_type::regular_file;
51}
52bool Status::isOther() const {
53 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
54}
55bool Status::isSymlink() const {
56 return Type == file_type::symlink_file;
57}
58bool Status::isStatusKnown() const {
59 return Type != file_type::status_error;
60}
61bool Status::exists() const {
62 return isStatusKnown() && Type != file_type::file_not_found;
63}
64
65File::~File() {}
66
67FileSystem::~FileSystem() {}
68
Rafael Espindola8e650d72014-06-12 20:37:59 +000069std::error_code FileSystem::getBufferForFile(
70 const llvm::Twine &Name, std::unique_ptr<MemoryBuffer> &Result,
71 int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +000072 std::unique_ptr<File> F;
Rafael Espindola8e650d72014-06-12 20:37:59 +000073 if (std::error_code EC = openFileForRead(Name, F))
Ben Langmuirc8130a72014-02-20 21:59:23 +000074 return EC;
75
Rafael Espindola8e650d72014-06-12 20:37:59 +000076 std::error_code EC =
77 F->getBuffer(Name, Result, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000078 return EC;
79}
80
81//===-----------------------------------------------------------------------===/
82// RealFileSystem implementation
83//===-----------------------------------------------------------------------===/
84
Benjamin Kramer3d6220d2014-03-01 17:21:22 +000085namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +000086/// \brief Wrapper around a raw file descriptor.
87class RealFile : public File {
88 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +000089 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +000090 friend class RealFileSystem;
91 RealFile(int FD) : FD(FD) {
92 assert(FD >= 0 && "Invalid or inactive file descriptor");
93 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +000094
Ben Langmuirc8130a72014-02-20 21:59:23 +000095public:
96 ~RealFile();
Craig Toppera798a9d2014-03-02 09:32:10 +000097 ErrorOr<Status> status() override;
Rafael Espindola8e650d72014-06-12 20:37:59 +000098 std::error_code getBuffer(const Twine &Name,
99 std::unique_ptr<MemoryBuffer> &Result,
100 int64_t FileSize = -1,
101 bool RequiresNullTerminator = true,
102 bool IsVolatile = false) override;
103 std::error_code close() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000104 void setName(StringRef Name) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000105};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000106} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000107RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000108
109ErrorOr<Status> RealFile::status() {
110 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000111 if (!S.isStatusKnown()) {
112 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000113 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000114 return EC;
115 Status NewS(RealStatus);
116 NewS.setName(S.getName());
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000117 S = std::move(NewS);
Ben Langmuird066d4c2014-02-28 21:16:07 +0000118 }
119 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000120}
121
Rafael Espindola8e650d72014-06-12 20:37:59 +0000122std::error_code RealFile::getBuffer(const Twine &Name,
123 std::unique_ptr<MemoryBuffer> &Result,
124 int64_t FileSize,
125 bool RequiresNullTerminator,
126 bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127 assert(FD != -1 && "cannot get buffer for closed file");
128 return MemoryBuffer::getOpenFile(FD, Name.str().c_str(), Result, FileSize,
Argyrios Kyrtzidis26d56392014-05-05 21:57:46 +0000129 RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000130}
131
132// FIXME: This is terrible, we need this for ::close.
133#if !defined(_MSC_VER) && !defined(__MINGW32__)
134#include <unistd.h>
135#include <sys/uio.h>
136#else
137#include <io.h>
138#ifndef S_ISFIFO
139#define S_ISFIFO(x) (0)
140#endif
141#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000142std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000143 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000144 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000145 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000146 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000147}
148
Ben Langmuird066d4c2014-02-28 21:16:07 +0000149void RealFile::setName(StringRef Name) {
150 S.setName(Name);
151}
152
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000153namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000154/// \brief The file system according to your operating system.
155class RealFileSystem : public FileSystem {
156public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000157 ErrorOr<Status> status(const Twine &Path) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000158 std::error_code openFileForRead(const Twine &Path,
159 std::unique_ptr<File> &Result) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000160};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000161} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000162
163ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
164 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000165 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000166 return EC;
167 Status Result(RealStatus);
168 Result.setName(Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000169 return Result;
170}
171
Rafael Espindola8e650d72014-06-12 20:37:59 +0000172std::error_code RealFileSystem::openFileForRead(const Twine &Name,
173 std::unique_ptr<File> &Result) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000174 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000175 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000176 return EC;
177 Result.reset(new RealFile(FD));
Ben Langmuird066d4c2014-02-28 21:16:07 +0000178 Result->setName(Name.str());
Rafael Espindola8e650d72014-06-12 20:37:59 +0000179 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000180}
181
182IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
183 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
184 return FS;
185}
186
187//===-----------------------------------------------------------------------===/
188// OverlayFileSystem implementation
189//===-----------------------------------------------------------------------===/
190OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
191 pushOverlay(BaseFS);
192}
193
194void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
195 FSList.push_back(FS);
196}
197
198ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
199 // FIXME: handle symlinks that cross file systems
200 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
201 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000202 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000203 return Status;
204 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000205 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000206}
207
Rafael Espindola8e650d72014-06-12 20:37:59 +0000208std::error_code
209OverlayFileSystem::openFileForRead(const llvm::Twine &Path,
210 std::unique_ptr<File> &Result) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000211 // FIXME: handle symlinks that cross file systems
212 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Rafael Espindola8e650d72014-06-12 20:37:59 +0000213 std::error_code EC = (*I)->openFileForRead(Path, Result);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000214 if (!EC || EC != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000215 return EC;
216 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000217 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000218}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000219
220//===-----------------------------------------------------------------------===/
221// VFSFromYAML implementation
222//===-----------------------------------------------------------------------===/
223
224// Allow DenseMap<StringRef, ...>. This is useful below because we know all the
225// strings are literals and will outlive the map, and there is no reason to
226// store them.
227namespace llvm {
228 template<>
229 struct DenseMapInfo<StringRef> {
230 // This assumes that "" will never be a valid key.
231 static inline StringRef getEmptyKey() { return StringRef(""); }
232 static inline StringRef getTombstoneKey() { return StringRef(); }
233 static unsigned getHashValue(StringRef Val) { return HashString(Val); }
234 static bool isEqual(StringRef LHS, StringRef RHS) { return LHS == RHS; }
235 };
236}
237
238namespace {
239
240enum EntryKind {
241 EK_Directory,
242 EK_File
243};
244
245/// \brief A single file or directory in the VFS.
246class Entry {
247 EntryKind Kind;
248 std::string Name;
249
250public:
251 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000252 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
253 StringRef getName() const { return Name; }
254 EntryKind getKind() const { return Kind; }
255};
256
257class DirectoryEntry : public Entry {
258 std::vector<Entry *> Contents;
259 Status S;
260
261public:
262 virtual ~DirectoryEntry();
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000263 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
264 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000265 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000266 Status getStatus() { return S; }
267 typedef std::vector<Entry *>::iterator iterator;
268 iterator contents_begin() { return Contents.begin(); }
269 iterator contents_end() { return Contents.end(); }
270 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
271};
272
273class FileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000274public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000275 enum NameKind {
276 NK_NotSet,
277 NK_External,
278 NK_Virtual
279 };
280private:
281 std::string ExternalContentsPath;
282 NameKind UseName;
283public:
284 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
285 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
286 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000287 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000288 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000289 bool useExternalName(bool GlobalUseExternalName) const {
290 return UseName == NK_NotSet ? GlobalUseExternalName
291 : (UseName == NK_External);
292 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000293 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
294};
295
296/// \brief A virtual file system parsed from a YAML file.
297///
298/// Currently, this class allows creating virtual directories and mapping
299/// virtual file paths to existing external files, available in \c ExternalFS.
300///
301/// The basic structure of the parsed file is:
302/// \verbatim
303/// {
304/// 'version': <version number>,
305/// <optional configuration>
306/// 'roots': [
307/// <directory entries>
308/// ]
309/// }
310/// \endverbatim
311///
312/// All configuration options are optional.
313/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000314/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000315///
316/// Virtual directories are represented as
317/// \verbatim
318/// {
319/// 'type': 'directory',
320/// 'name': <string>,
321/// 'contents': [ <file or directory entries> ]
322/// }
323/// \endverbatim
324///
325/// The default attributes for virtual directories are:
326/// \verbatim
327/// MTime = now() when created
328/// Perms = 0777
329/// User = Group = 0
330/// Size = 0
331/// UniqueID = unspecified unique value
332/// \endverbatim
333///
334/// Re-mapped files are represented as
335/// \verbatim
336/// {
337/// 'type': 'file',
338/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000339/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000340/// 'external-contents': <path to external file>)
341/// }
342/// \endverbatim
343///
344/// and inherit their attributes from the external contents.
345///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000346/// In both cases, the 'name' field may contain multiple path components (e.g.
347/// /path/to/file). However, any directory that contains more than one child
348/// must be uniquely represented by a directory entry.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000349class VFSFromYAML : public vfs::FileSystem {
350 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
351 /// \brief The file system to use for external references.
352 IntrusiveRefCntPtr<FileSystem> ExternalFS;
353
354 /// @name Configuration
355 /// @{
356
357 /// \brief Whether to perform case-sensitive comparisons.
358 ///
359 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000360 bool CaseSensitive;
361
362 /// \brief Whether to use to use the value of 'external-contents' for the
363 /// names of files. This global value is overridable on a per-file basis.
364 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000365 /// @}
366
367 friend class VFSFromYAMLParser;
368
369private:
370 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000371 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000372
373 /// \brief Looks up \p Path in \c Roots.
374 ErrorOr<Entry *> lookupPath(const Twine &Path);
375
376 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
377 /// recursing into the contents of \p From if it is a directory.
378 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
379 sys::path::const_iterator End, Entry *From);
380
381public:
382 ~VFSFromYAML();
383
384 /// \brief Parses \p Buffer, which is expected to be in YAML format and
385 /// returns a virtual file system representing its contents.
386 ///
387 /// Takes ownership of \p Buffer.
388 static VFSFromYAML *create(MemoryBuffer *Buffer,
389 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000390 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000391 IntrusiveRefCntPtr<FileSystem> ExternalFS);
392
Craig Toppera798a9d2014-03-02 09:32:10 +0000393 ErrorOr<Status> status(const Twine &Path) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000394 std::error_code openFileForRead(const Twine &Path,
395 std::unique_ptr<File> &Result) override;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000396};
397
398/// \brief A helper class to hold the common YAML parsing state.
399class VFSFromYAMLParser {
400 yaml::Stream &Stream;
401
402 void error(yaml::Node *N, const Twine &Msg) {
403 Stream.printError(N, Msg);
404 }
405
406 // false on error
407 bool parseScalarString(yaml::Node *N, StringRef &Result,
408 SmallVectorImpl<char> &Storage) {
409 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
410 if (!S) {
411 error(N, "expected string");
412 return false;
413 }
414 Result = S->getValue(Storage);
415 return true;
416 }
417
418 // false on error
419 bool parseScalarBool(yaml::Node *N, bool &Result) {
420 SmallString<5> Storage;
421 StringRef Value;
422 if (!parseScalarString(N, Value, Storage))
423 return false;
424
425 if (Value.equals_lower("true") || Value.equals_lower("on") ||
426 Value.equals_lower("yes") || Value == "1") {
427 Result = true;
428 return true;
429 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
430 Value.equals_lower("no") || Value == "0") {
431 Result = false;
432 return true;
433 }
434
435 error(N, "expected boolean value");
436 return false;
437 }
438
439 struct KeyStatus {
440 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
441 bool Required;
442 bool Seen;
443 };
444 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
445
446 // false on error
447 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
448 DenseMap<StringRef, KeyStatus> &Keys) {
449 if (!Keys.count(Key)) {
450 error(KeyNode, "unknown key");
451 return false;
452 }
453 KeyStatus &S = Keys[Key];
454 if (S.Seen) {
455 error(KeyNode, Twine("duplicate key '") + Key + "'");
456 return false;
457 }
458 S.Seen = true;
459 return true;
460 }
461
462 // false on error
463 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
464 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
465 E = Keys.end();
466 I != E; ++I) {
467 if (I->second.Required && !I->second.Seen) {
468 error(Obj, Twine("missing key '") + I->first + "'");
469 return false;
470 }
471 }
472 return true;
473 }
474
475 Entry *parseEntry(yaml::Node *N) {
476 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
477 if (!M) {
478 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000479 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000480 }
481
482 KeyStatusPair Fields[] = {
483 KeyStatusPair("name", true),
484 KeyStatusPair("type", true),
485 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000486 KeyStatusPair("external-contents", false),
487 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000488 };
489
490 DenseMap<StringRef, KeyStatus> Keys(
491 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
492
493 bool HasContents = false; // external or otherwise
494 std::vector<Entry *> EntryArrayContents;
495 std::string ExternalContentsPath;
496 std::string Name;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000497 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000498 EntryKind Kind;
499
500 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
501 ++I) {
502 StringRef Key;
503 // Reuse the buffer for key and value, since we don't look at key after
504 // parsing value.
505 SmallString<256> Buffer;
506 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000507 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000508
509 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000510 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000511
512 StringRef Value;
513 if (Key == "name") {
514 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000515 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000516 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000517 } else if (Key == "type") {
518 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000519 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000520 if (Value == "file")
521 Kind = EK_File;
522 else if (Value == "directory")
523 Kind = EK_Directory;
524 else {
525 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +0000526 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000527 }
528 } else if (Key == "contents") {
529 if (HasContents) {
530 error(I->getKey(),
531 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000532 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000533 }
534 HasContents = true;
535 yaml::SequenceNode *Contents =
536 dyn_cast<yaml::SequenceNode>(I->getValue());
537 if (!Contents) {
538 // FIXME: this is only for directories, what about files?
539 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +0000540 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000541 }
542
543 for (yaml::SequenceNode::iterator I = Contents->begin(),
544 E = Contents->end();
545 I != E; ++I) {
546 if (Entry *E = parseEntry(&*I))
547 EntryArrayContents.push_back(E);
548 else
Craig Topperf1186c52014-05-08 06:41:40 +0000549 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000550 }
551 } else if (Key == "external-contents") {
552 if (HasContents) {
553 error(I->getKey(),
554 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000555 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000556 }
557 HasContents = true;
558 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000559 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000560 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000561 } else if (Key == "use-external-name") {
562 bool Val;
563 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +0000564 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000565 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000566 } else {
567 llvm_unreachable("key missing from Keys");
568 }
569 }
570
571 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +0000572 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000573
574 // check for missing keys
575 if (!HasContents) {
576 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000577 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000578 }
579 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000580 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000581
Ben Langmuirb59cf672014-02-27 00:25:12 +0000582 // check invalid configuration
583 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
584 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +0000585 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000586 }
587
Ben Langmuir93853232014-03-05 21:32:20 +0000588 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000589 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +0000590 size_t RootPathLen = sys::path::root_path(Trimmed).size();
591 while (Trimmed.size() > RootPathLen &&
592 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000593 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
594 // Get the last component
595 StringRef LastComponent = sys::path::filename(Trimmed);
596
Craig Topperf1186c52014-05-08 06:41:40 +0000597 Entry *Result = nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000598 switch (Kind) {
599 case EK_File:
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000600 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000601 UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000602 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000603 case EK_Directory:
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000604 Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000605 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
606 0, file_type::directory_file, sys::fs::all_all));
607 break;
608 }
609
610 StringRef Parent = sys::path::parent_path(Trimmed);
611 if (Parent.empty())
612 return Result;
613
614 // if 'name' contains multiple components, create implicit directory entries
615 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
616 E = sys::path::rend(Parent);
617 I != E; ++I) {
Benjamin Kramer3f755aa2014-03-10 17:55:02 +0000618 Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000619 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
620 0, file_type::directory_file, sys::fs::all_all));
621 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000622 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000623 }
624
625public:
626 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
627
628 // false on error
629 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
630 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
631 if (!Top) {
632 error(Root, "expected mapping node");
633 return false;
634 }
635
636 KeyStatusPair Fields[] = {
637 KeyStatusPair("version", true),
638 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000639 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000640 KeyStatusPair("roots", true),
641 };
642
643 DenseMap<StringRef, KeyStatus> Keys(
644 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
645
646 // Parse configuration and 'roots'
647 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
648 ++I) {
649 SmallString<10> KeyBuffer;
650 StringRef Key;
651 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
652 return false;
653
654 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
655 return false;
656
657 if (Key == "roots") {
658 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
659 if (!Roots) {
660 error(I->getValue(), "expected array");
661 return false;
662 }
663
664 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
665 I != E; ++I) {
666 if (Entry *E = parseEntry(&*I))
667 FS->Roots.push_back(E);
668 else
669 return false;
670 }
671 } else if (Key == "version") {
672 StringRef VersionString;
673 SmallString<4> Storage;
674 if (!parseScalarString(I->getValue(), VersionString, Storage))
675 return false;
676 int Version;
677 if (VersionString.getAsInteger<int>(10, Version)) {
678 error(I->getValue(), "expected integer");
679 return false;
680 }
681 if (Version < 0) {
682 error(I->getValue(), "invalid version number");
683 return false;
684 }
685 if (Version != 0) {
686 error(I->getValue(), "version mismatch, expected 0");
687 return false;
688 }
689 } else if (Key == "case-sensitive") {
690 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
691 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000692 } else if (Key == "use-external-names") {
693 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
694 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000695 } else {
696 llvm_unreachable("key missing from Keys");
697 }
698 }
699
700 if (Stream.failed())
701 return false;
702
703 if (!checkMissingKeys(Top, Keys))
704 return false;
705 return true;
706 }
707};
708} // end of anonymous namespace
709
710Entry::~Entry() {}
711DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
712
713VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
714
715VFSFromYAML *VFSFromYAML::create(MemoryBuffer *Buffer,
716 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000717 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000718 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
719
720 SourceMgr SM;
721 yaml::Stream Stream(Buffer, SM);
722
Ben Langmuir97882e72014-02-24 20:56:37 +0000723 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000724 yaml::document_iterator DI = Stream.begin();
725 yaml::Node *Root = DI->getRoot();
726 if (DI == Stream.end() || !Root) {
727 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +0000728 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000729 }
730
731 VFSFromYAMLParser P(Stream);
732
Ahmed Charlesb8984322014-03-07 20:03:18 +0000733 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000734 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +0000735 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000736
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000737 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000738}
739
740ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000741 SmallString<256> Path;
742 Path_.toVector(Path);
743
744 // Handle relative paths
Rafael Espindola8e650d72014-06-12 20:37:59 +0000745 if (std::error_code EC = sys::fs::make_absolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000746 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000747
748 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +0000749 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000750
751 sys::path::const_iterator Start = sys::path::begin(Path);
752 sys::path::const_iterator End = sys::path::end(Path);
753 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
754 I != E; ++I) {
755 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000756 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000757 return Result;
758 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000759 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000760}
761
762ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
763 sys::path::const_iterator End,
764 Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000765 if (Start->equals("."))
766 ++Start;
767
768 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000769 if (CaseSensitive ? !Start->equals(From->getName())
770 : !Start->equals_lower(From->getName()))
771 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +0000772 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000773
774 ++Start;
775
776 if (Start == End) {
777 // Match!
778 return From;
779 }
780
781 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
782 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +0000783 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000784
785 for (DirectoryEntry::iterator I = DE->contents_begin(),
786 E = DE->contents_end();
787 I != E; ++I) {
788 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000789 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000790 return Result;
791 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000792 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000793}
794
795ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
796 ErrorOr<Entry *> Result = lookupPath(Path);
797 if (!Result)
798 return Result.getError();
799
800 std::string PathStr(Path.str());
801 if (FileEntry *F = dyn_cast<FileEntry>(*Result)) {
802 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +0000803 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000804 if (S && !F->useExternalName(UseExternalNames))
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000805 S->setName(PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +0000806 if (S)
807 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000808 return S;
809 } else { // directory
810 DirectoryEntry *DE = cast<DirectoryEntry>(*Result);
811 Status S = DE->getStatus();
812 S.setName(PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000813 return S;
814 }
815}
816
Rafael Espindola8e650d72014-06-12 20:37:59 +0000817std::error_code
818VFSFromYAML::openFileForRead(const Twine &Path,
819 std::unique_ptr<vfs::File> &Result) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000820 ErrorOr<Entry *> E = lookupPath(Path);
821 if (!E)
822 return E.getError();
823
824 FileEntry *F = dyn_cast<FileEntry>(*E);
825 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +0000826 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000827
Rafael Espindola8e650d72014-06-12 20:37:59 +0000828 if (std::error_code EC =
829 ExternalFS->openFileForRead(F->getExternalContentsPath(), Result))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000830 return EC;
831
832 if (!F->useExternalName(UseExternalNames))
833 Result->setName(Path.str());
834
Rafael Espindola8e650d72014-06-12 20:37:59 +0000835 return std::error_code();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000836}
837
838IntrusiveRefCntPtr<FileSystem>
839vfs::getVFSFromYAML(MemoryBuffer *Buffer, SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000840 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000841 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuir97882e72014-02-24 20:56:37 +0000842 return VFSFromYAML::create(Buffer, DiagHandler, DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000843}
844
845UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000846 static std::atomic<unsigned> UID;
847 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000848 // The following assumes that uint64_t max will never collide with a real
849 // dev_t value from the OS.
850 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
851}
Justin Bogner9c785292014-05-20 21:43:27 +0000852
853#ifndef NDEBUG
854static bool pathHasTraversal(StringRef Path) {
855 using namespace llvm::sys;
856 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
857 if (Comp == "." || Comp == "..")
858 return true;
859 return false;
860}
861#endif
862
863void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
864 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
865 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
866 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
867 Mappings.emplace_back(VirtualPath, RealPath);
868}
869
Justin Bogner44fa450342014-05-21 22:46:51 +0000870namespace {
871class JSONWriter {
872 llvm::raw_ostream &OS;
873 SmallVector<StringRef, 16> DirStack;
874 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
875 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
876 bool containedIn(StringRef Parent, StringRef Path);
877 StringRef containedPart(StringRef Parent, StringRef Path);
878 void startDirectory(StringRef Path);
879 void endDirectory();
880 void writeEntry(StringRef VPath, StringRef RPath);
881
882public:
883 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
884 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
885};
Justin Bogner9c785292014-05-20 21:43:27 +0000886}
887
Justin Bogner44fa450342014-05-21 22:46:51 +0000888bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +0000889 using namespace llvm::sys;
890 // Compare each path component.
891 auto IParent = path::begin(Parent), EParent = path::end(Parent);
892 for (auto IChild = path::begin(Path), EChild = path::end(Path);
893 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
894 if (*IParent != *IChild)
895 return false;
896 }
897 // Have we exhausted the parent path?
898 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +0000899}
900
Justin Bogner44fa450342014-05-21 22:46:51 +0000901StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
902 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +0000903 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +0000904 return Path.slice(Parent.size() + 1, StringRef::npos);
905}
906
Justin Bogner44fa450342014-05-21 22:46:51 +0000907void JSONWriter::startDirectory(StringRef Path) {
908 StringRef Name =
909 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
910 DirStack.push_back(Path);
911 unsigned Indent = getDirIndent();
912 OS.indent(Indent) << "{\n";
913 OS.indent(Indent + 2) << "'type': 'directory',\n";
914 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
915 OS.indent(Indent + 2) << "'contents': [\n";
916}
917
918void JSONWriter::endDirectory() {
919 unsigned Indent = getDirIndent();
920 OS.indent(Indent + 2) << "]\n";
921 OS.indent(Indent) << "}";
922
923 DirStack.pop_back();
924}
925
926void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
927 unsigned Indent = getFileIndent();
928 OS.indent(Indent) << "{\n";
929 OS.indent(Indent + 2) << "'type': 'file',\n";
930 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
931 OS.indent(Indent + 2) << "'external-contents': \""
932 << llvm::yaml::escape(RPath) << "\"\n";
933 OS.indent(Indent) << "}";
934}
935
936void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
937 Optional<bool> IsCaseSensitive) {
938 using namespace llvm::sys;
939
940 OS << "{\n"
941 " 'version': 0,\n";
942 if (IsCaseSensitive.hasValue())
943 OS << " 'case-sensitive': '"
944 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
945 OS << " 'roots': [\n";
946
947 if (Entries.empty())
948 return;
949
950 const YAMLVFSEntry &Entry = Entries.front();
951 startDirectory(path::parent_path(Entry.VPath));
952 writeEntry(path::filename(Entry.VPath), Entry.RPath);
953
954 for (const auto &Entry : Entries.slice(1)) {
955 StringRef Dir = path::parent_path(Entry.VPath);
956 if (Dir == DirStack.back())
957 OS << ",\n";
958 else {
959 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
960 OS << "\n";
961 endDirectory();
962 }
963 OS << ",\n";
964 startDirectory(Dir);
965 }
966 writeEntry(path::filename(Entry.VPath), Entry.RPath);
967 }
968
969 while (!DirStack.empty()) {
970 OS << "\n";
971 endDirectory();
972 }
973
974 OS << "\n"
975 << " ]\n"
976 << "}\n";
977}
978
Justin Bogner9c785292014-05-20 21:43:27 +0000979void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
980 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +0000981 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +0000982 return LHS.VPath < RHS.VPath;
983 });
984
Justin Bogner44fa450342014-05-21 22:46:51 +0000985 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +0000986}