141 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8#include "TestFS.h"9#include "GlobalCompilationDatabase.h"10#include "URI.h"11#include "support/Logger.h"12#include "support/Path.h"13#include "llvm/ADT/StringRef.h"14#include "llvm/Support/Path.h"15#include <optional>16 17namespace clang {18namespace clangd {19 20namespace {21 22// Tries to strip \p Prefix from beginning of \p Path. Returns true on success.23// If \p Prefix doesn't match, leaves \p Path untouched and returns false.24bool pathConsumeFront(PathRef &Path, PathRef Prefix) {25 if (!pathStartsWith(Prefix, Path))26 return false;27 Path = Path.drop_front(Prefix.size());28 return true;29}30} // namespace31 32llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>33buildTestFS(llvm::StringMap<std::string> const &Files,34 llvm::StringMap<time_t> const &Timestamps) {35 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> MemFS(36 new llvm::vfs::InMemoryFileSystem);37 MemFS->setCurrentWorkingDirectory(testRoot());38 for (auto &FileAndContents : Files) {39 llvm::StringRef File = FileAndContents.first();40 MemFS->addFile(41 File, Timestamps.lookup(File),42 llvm::MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));43 }44 return MemFS;45}46 47MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory,48 llvm::StringRef RelPathPrefix)49 : ExtraClangFlags({"-ffreestanding"}), Directory(Directory),50 RelPathPrefix(RelPathPrefix) {51 // -ffreestanding avoids implicit stdc-predef.h.52}53 54std::optional<ProjectInfo>55MockCompilationDatabase::getProjectInfo(PathRef File) const {56 return ProjectInfo{std::string(Directory)};57}58 59std::optional<tooling::CompileCommand>60MockCompilationDatabase::getCompileCommand(PathRef File) const {61 if (ExtraClangFlags.empty())62 return std::nullopt;63 64 auto FileName = llvm::sys::path::filename(File);65 66 // Build the compile command.67 auto CommandLine = ExtraClangFlags;68 CommandLine.insert(CommandLine.begin(), "clang");69 if (RelPathPrefix.empty()) {70 // Use the absolute path in the compile command.71 CommandLine.push_back(std::string(File));72 } else {73 // Build a relative path using RelPathPrefix.74 llvm::SmallString<32> RelativeFilePath(RelPathPrefix);75 llvm::sys::path::append(RelativeFilePath, FileName);76 CommandLine.push_back(std::string(RelativeFilePath.str()));77 }78 79 return {tooling::CompileCommand(Directory != llvm::StringRef()80 ? Directory81 : llvm::sys::path::parent_path(File),82 FileName, std::move(CommandLine), "")};83}84 85const char *testRoot() {86#ifdef _WIN3287 return "C:\\clangd-test";88#else89 return "/clangd-test";90#endif91}92 93std::string testPath(PathRef File, llvm::sys::path::Style Style) {94 assert(llvm::sys::path::is_relative(File) && "FileName should be relative");95 96 llvm::SmallString<32> NativeFile = File;97 llvm::sys::path::native(NativeFile, Style);98 llvm::SmallString<32> Path;99 llvm::sys::path::append(Path, Style, testRoot(), NativeFile);100 return std::string(Path.str());101}102 103/// unittest: is a scheme that refers to files relative to testRoot().104/// URI body is a path relative to testRoot() e.g. unittest:///x.h for105/// /clangd-test/x.h.106class TestScheme : public URIScheme {107public:108 static const char *Scheme;109 110 llvm::Expected<std::string>111 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,112 llvm::StringRef HintPath) const override {113 if (!HintPath.empty() && !pathStartsWith(testRoot(), HintPath))114 return error("Hint path is not empty and doesn't start with {0}: {1}",115 testRoot(), HintPath);116 if (!Body.consume_front("/"))117 return error("Body of an unittest: URI must start with '/'");118 llvm::SmallString<16> Path(Body.begin(), Body.end());119 llvm::sys::path::native(Path);120 return testPath(Path);121 }122 123 llvm::Expected<URI>124 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {125 if (!pathConsumeFront(AbsolutePath, testRoot()))126 return error("{0} does not start with {1}", AbsolutePath, testRoot());127 128 return URI(Scheme, /*Authority=*/"",129 llvm::sys::path::convert_to_slash(AbsolutePath));130 }131};132 133const char *TestScheme::Scheme = "unittest";134 135static URISchemeRegistry::Add<TestScheme> X(TestScheme::Scheme, "Test schema");136 137volatile int UnittestSchemeAnchorSource = 0;138 139} // namespace clangd140} // namespace clang141