clang-tools 19.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/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} // namespace
31
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
48 llvm::StringRef RelPathPrefix)
49 : ExtraClangFlags({"-ffreestanding"}), Directory(Directory),
50 RelPathPrefix(RelPathPrefix) {
51 // -ffreestanding avoids implicit stdc-predef.h.
52}
53
54std::optional<ProjectInfo>
56 return ProjectInfo{std::string(Directory)};
57}
58
59std::optional<tooling::CompileCommand>
61 if (ExtraClangFlags.empty())
62 return std::nullopt;
63
64 auto FileName = llvm::sys::path::filename(File);
65
66 // Build the compile command.
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 ? Directory
81 : llvm::sys::path::parent_path(File),
82 FileName, std::move(CommandLine), "")};
83}
84
85const char *testRoot() {
86#ifdef _WIN32
87 return "C:\\clangd-test";
88#else
89 return "/clangd-test";
90#endif
91}
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 for
105/// /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
138
139} // namespace clangd
140} // namespace clang
StringRef FileName
int X
std::vector< llvm::StringRef > CommandLine
llvm::StringRef Directory
std::optional< tooling::CompileCommand > getCompileCommand(PathRef File) const override
If there are any known-good commands for building this file, returns one.
Definition: TestFS.cpp:60
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:47
std::vector< std::string > ExtraClangFlags
Definition: TestFS.h:68
std::optional< ProjectInfo > getProjectInfo(PathRef File) const override
Finds the closest project to File.
Definition: TestFS.cpp:55
static const char * Scheme
Definition: TestFS.cpp:108
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:111
llvm::Expected< URI > uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override
Definition: TestFS.cpp:124
URIScheme is an extension point for teaching clangd to recognize a custom URI scheme.
Definition: URI.h:108
A URI describes the location of a source file.
Definition: URI.h:28
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
bool pathStartsWith(PathRef Ancestor, PathRef Path, llvm::sys::path::Style Style)
Checks if Ancestor is a proper ancestor of Path.
Definition: Path.cpp:36
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition: Logger.h:79
std::string testPath(PathRef File, llvm::sys::path::Style Style)
Definition: TestFS.cpp:93
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > buildTestFS(llvm::StringMap< std::string > const &Files, llvm::StringMap< time_t > const &Timestamps)
Definition: TestFS.cpp:33
volatile int UnittestSchemeAnchorSource
Definition: TestFS.cpp:137
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
const char * testRoot()
Definition: TestFS.cpp:85
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//