clang-tools  15.0.0git
TestFS.cpp
Go to the documentation of this file.
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"
10 #include "URI.h"
11 #include "support/Logger.h"
12 #include "support/Path.h"
13 #include "llvm/ADT/None.h"
14 #include "llvm/ADT/Optional.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/Path.h"
17 
18 namespace clang {
19 namespace clangd {
20 
21 namespace {
22 
23 // Tries to strip \p Prefix from beginning of \p Path. Returns true on success.
24 // If \p Prefix doesn't match, leaves \p Path untouched and returns false.
25 bool pathConsumeFront(PathRef &Path, PathRef Prefix) {
26  if (!pathStartsWith(Prefix, Path))
27  return false;
28  Path = Path.drop_front(Prefix.size());
29  return true;
30 }
31 } // namespace
32 
33 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
34 buildTestFS(llvm::StringMap<std::string> const &Files,
35  llvm::StringMap<time_t> const &Timestamps) {
36  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> MemFS(
38  MemFS->setCurrentWorkingDirectory(testRoot());
39  for (auto &FileAndContents : Files) {
40  llvm::StringRef File = FileAndContents.first();
41  MemFS->addFile(
42  File, Timestamps.lookup(File),
43  llvm::MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));
44  }
45  return MemFS;
46 }
47 
49  llvm::StringRef RelPathPrefix)
50  : ExtraClangFlags({"-ffreestanding"}), Directory(Directory),
51  RelPathPrefix(RelPathPrefix) {
52  // -ffreestanding avoids implicit stdc-predef.h.
53 }
54 
55 llvm::Optional<ProjectInfo>
57  return ProjectInfo{std::string(Directory)};
58 }
59 
60 llvm::Optional<tooling::CompileCommand>
62  if (ExtraClangFlags.empty())
63  return None;
64 
65  auto FileName = llvm::sys::path::filename(File);
66 
67  // Build the compile command.
69  CommandLine.insert(CommandLine.begin(), "clang");
70  if (RelPathPrefix.empty()) {
71  // Use the absolute path in the compile command.
72  CommandLine.push_back(std::string(File));
73  } else {
74  // Build a relative path using RelPathPrefix.
75  llvm::SmallString<32> RelativeFilePath(RelPathPrefix);
76  llvm::sys::path::append(RelativeFilePath, FileName);
77  CommandLine.push_back(std::string(RelativeFilePath.str()));
78  }
79 
80  return {tooling::CompileCommand(Directory != llvm::StringRef()
81  ? Directory
82  : llvm::sys::path::parent_path(File),
83  FileName, std::move(CommandLine), "")};
84 }
85 
86 const char *testRoot() {
87 #ifdef _WIN32
88  return "C:\\clangd-test";
89 #else
90  return "/clangd-test";
91 #endif
92 }
93 
94 std::string testPath(PathRef File, llvm::sys::path::Style Style) {
95  assert(llvm::sys::path::is_relative(File) && "FileName should be relative");
96 
97  llvm::SmallString<32> NativeFile = File;
98  llvm::sys::path::native(NativeFile, Style);
99  llvm::SmallString<32> Path;
100  llvm::sys::path::append(Path, Style, testRoot(), NativeFile);
101  return std::string(Path.str());
102 }
103 
104 /// unittest: is a scheme that refers to files relative to testRoot().
105 /// URI body is a path relative to testRoot() e.g. unittest:///x.h for
106 /// /clangd-test/x.h.
107 class TestScheme : public URIScheme {
108 public:
109  static const char *Scheme;
110 
111  llvm::Expected<std::string>
112  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
113  llvm::StringRef HintPath) const override {
114  if (!HintPath.empty() && !pathStartsWith(testRoot(), HintPath))
115  return error("Hint path is not empty and doesn't start with {0}: {1}",
116  testRoot(), HintPath);
117  if (!Body.consume_front("/"))
118  return error("Body of an unittest: URI must start with '/'");
119  llvm::SmallString<16> Path(Body.begin(), Body.end());
120  llvm::sys::path::native(Path);
121  return testPath(Path);
122  }
123 
124  llvm::Expected<URI>
125  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
126  if (!pathConsumeFront(AbsolutePath, testRoot()))
127  return error("{0} does not start with {1}", AbsolutePath, testRoot());
128 
129  return URI(Scheme, /*Authority=*/"",
130  llvm::sys::path::convert_to_slash(AbsolutePath));
131  }
132 };
133 
134 const char *TestScheme::Scheme = "unittest";
135 
136 static URISchemeRegistry::Add<TestScheme> X(TestScheme::Scheme, "Test schema");
137 
138 volatile int UnittestSchemeAnchorSource = 0;
139 
140 } // namespace clangd
141 } // namespace clang
clang::clangd::testPath
std::string testPath(PathRef File, llvm::sys::path::Style Style)
Definition: TestFS.cpp:94
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
clang::clangd::error
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition: Logger.h:79
Path.h
clang::clangd::X
static URISchemeRegistry::Add< TestScheme > X(TestScheme::Scheme, "Test schema")
clang::clangd::URIScheme
URIScheme is an extension point for teaching clangd to recognize a custom URI scheme.
Definition: URI.h:108
clang::clangd::TestScheme::getAbsolutePath
llvm::Expected< std::string > getAbsolutePath(llvm::StringRef, llvm::StringRef Body, llvm::StringRef HintPath) const override
Returns the absolute path of the file corresponding to the URI authority+body in the file system.
Definition: TestFS.cpp:112
clang::clangd::TestScheme::Scheme
static const char * Scheme
Definition: TestFS.cpp:109
clang::clangd::ProjectInfo
Definition: GlobalCompilationDatabase.h:27
clang::clangd::UnittestSchemeAnchorSource
volatile int UnittestSchemeAnchorSource
Definition: TestFS.cpp:138
clang::clangd::MockCompilationDatabase::getCompileCommand
llvm::Optional< tooling::CompileCommand > getCompileCommand(PathRef File) const override
If there are any known-good commands for building this file, returns one.
Definition: TestFS.cpp:61
clang::clangd::MockCompilationDatabase::MockCompilationDatabase
MockCompilationDatabase(StringRef Directory=StringRef(), StringRef RelPathPrefix=StringRef())
If Directory is not empty, use that as the Directory field of the CompileCommand, and as project Sour...
Definition: TestFS.cpp:48
clang::clangd::testRoot
const char * testRoot()
Definition: TestFS.cpp:86
GlobalCompilationDatabase.h
clang::clangd::buildTestFS
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > buildTestFS(llvm::StringMap< std::string > const &Files, llvm::StringMap< time_t > const &Timestamps)
Definition: TestFS.cpp:34
clang::clangd::MockCompilationDatabase::getProjectInfo
llvm::Optional< ProjectInfo > getProjectInfo(PathRef File) const override
Finds the closest project to File.
Definition: TestFS.cpp:56
Logger.h
CommandLine
std::vector< llvm::StringRef > CommandLine
Definition: Serialization.cpp:421
TestFS.h
Directory
llvm::StringRef Directory
Definition: Serialization.cpp:420
clang::clangd::pathStartsWith
bool pathStartsWith(PathRef Ancestor, PathRef Path, llvm::sys::path::Style Style)
Checks if Ancestor is a proper ancestor of Path.
Definition: Path.cpp:36
FileName
StringRef FileName
Definition: KernelNameRestrictionCheck.cpp:46
Files
llvm::DenseSet< FileID > Files
Definition: IncludeCleaner.cpp:194
InMemoryFileSystem
llvm::IntrusiveRefCntPtr< llvm::vfs::InMemoryFileSystem > InMemoryFileSystem
Definition: IndexActionTests.cpp:110
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
clang::clangd::TestScheme::uriFromAbsolutePath
llvm::Expected< URI > uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override
Definition: TestFS.cpp:125
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
URI.h
clang::clangd::MockCompilationDatabase::ExtraClangFlags
std::vector< std::string > ExtraClangFlags
Definition: TestFS.h:68
clang::clangd::URI
A URI describes the location of a source file.
Definition: URI.h:28