1 //===-- TestFS.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "TestFS.h"
9 #include "GlobalCompilationDatabase.h"
10 #include "Path.h"
11 #include "URI.h"
12 #include "llvm/ADT/None.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/Path.h"
17 
18 namespace clang {
19 namespace clangd {
20 
21 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
buildTestFS(llvm::StringMap<std::string> const & Files,llvm::StringMap<time_t> const & Timestamps)22 buildTestFS(llvm::StringMap<std::string> const &Files,
23             llvm::StringMap<time_t> const &Timestamps) {
24   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> MemFS(
25       new llvm::vfs::InMemoryFileSystem);
26   MemFS->setCurrentWorkingDirectory(testRoot());
27   for (auto &FileAndContents : Files) {
28     llvm::StringRef File = FileAndContents.first();
29     MemFS->addFile(
30         File, Timestamps.lookup(File),
31         llvm::MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));
32   }
33   return MemFS;
34 }
35 
MockCompilationDatabase(llvm::StringRef Directory,llvm::StringRef RelPathPrefix)36 MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory,
37                                                  llvm::StringRef RelPathPrefix)
38     : ExtraClangFlags({"-ffreestanding"}), Directory(Directory),
39       RelPathPrefix(RelPathPrefix) {
40   // -ffreestanding avoids implicit stdc-predef.h.
41 }
42 
43 llvm::Optional<ProjectInfo>
getProjectInfo(PathRef File) const44 MockCompilationDatabase::getProjectInfo(PathRef File) const {
45   return ProjectInfo{Directory};
46 }
47 
48 llvm::Optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const49 MockCompilationDatabase::getCompileCommand(PathRef File) const {
50   if (ExtraClangFlags.empty())
51     return None;
52 
53   auto FileName = llvm::sys::path::filename(File);
54 
55   // Build the compile command.
56   auto CommandLine = ExtraClangFlags;
57   CommandLine.insert(CommandLine.begin(), "clang");
58   if (RelPathPrefix.empty()) {
59     // Use the absolute path in the compile command.
60     CommandLine.push_back(File);
61   } else {
62     // Build a relative path using RelPathPrefix.
63     llvm::SmallString<32> RelativeFilePath(RelPathPrefix);
64     llvm::sys::path::append(RelativeFilePath, FileName);
65     CommandLine.push_back(RelativeFilePath.str());
66   }
67 
68   return {tooling::CompileCommand(Directory != llvm::StringRef()
69                                       ? Directory
70                                       : llvm::sys::path::parent_path(File),
71                                   FileName, std::move(CommandLine), "")};
72 }
73 
testRoot()74 const char *testRoot() {
75 #ifdef _WIN32
76   return "C:\\clangd-test";
77 #else
78   return "/clangd-test";
79 #endif
80 }
81 
testPath(PathRef File)82 std::string testPath(PathRef File) {
83   assert(llvm::sys::path::is_relative(File) && "FileName should be relative");
84 
85   llvm::SmallString<32> NativeFile = File;
86   llvm::sys::path::native(NativeFile);
87   llvm::SmallString<32> Path;
88   llvm::sys::path::append(Path, testRoot(), NativeFile);
89   return Path.str();
90 }
91 
92 /// unittest: is a scheme that refers to files relative to testRoot().
93 /// URI body is a path relative to testRoot() e.g. unittest:///x.h for
94 /// /clangd-test/x.h.
95 class TestScheme : public URIScheme {
96 public:
97   static const char *Scheme;
98 
99   llvm::Expected<std::string>
getAbsolutePath(llvm::StringRef,llvm::StringRef Body,llvm::StringRef HintPath) const100   getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
101                   llvm::StringRef HintPath) const override {
102     if (!HintPath.startswith(testRoot()))
103       return llvm::make_error<llvm::StringError>(
104           "Hint path doesn't start with test root: " + HintPath,
105           llvm::inconvertibleErrorCode());
106     if (!Body.consume_front("/"))
107       return llvm::make_error<llvm::StringError>(
108           "Body of an unittest: URI must start with '/'",
109           llvm::inconvertibleErrorCode());
110     llvm::SmallString<16> Path(Body.begin(), Body.end());
111     llvm::sys::path::native(Path);
112     return testPath(Path);
113   }
114 
115   llvm::Expected<URI>
uriFromAbsolutePath(llvm::StringRef AbsolutePath) const116   uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
117     llvm::StringRef Body = AbsolutePath;
118     if (!Body.consume_front(testRoot()))
119       return llvm::make_error<llvm::StringError>(
120           AbsolutePath + "does not start with " + testRoot(),
121           llvm::inconvertibleErrorCode());
122 
123     return URI(Scheme, /*Authority=*/"",
124                llvm::sys::path::convert_to_slash(Body));
125   }
126 };
127 
128 const char *TestScheme::Scheme = "unittest";
129 
130 static URISchemeRegistry::Add<TestScheme> X(TestScheme::Scheme, "Test schema");
131 
132 volatile int UnittestSchemeAnchorSource = 0;
133 
134 } // namespace clangd
135 } // namespace clang
136