mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 20:30:14 +01:00
This adds vfs support to the toolchain, allowing Driver to take in-memory inputs in tests. As a consequence, I'm simplifying SourceBuffer: rather than allowing tests to pass in their own memory buffer, I'm using InMemoryFileSystem to push for greater consistency with production code. This does hit a quirk where I need to be careful about null terminator handling because fuzzer imports don't always have one, but that's probably more robust anyways. Co-authored-by: Richard Smith <richard@metafoo.co.uk>
43 lines
1.3 KiB
C++
43 lines
1.3 KiB
C++
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
|
// Exceptions. See /LICENSE for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
#include "toolchain/source/source_buffer.h"
|
|
|
|
#include <limits>
|
|
|
|
#include "llvm/Support/Error.h"
|
|
#include "llvm/Support/FormatVariadic.h"
|
|
|
|
namespace Carbon {
|
|
|
|
auto SourceBuffer::CreateFromFile(llvm::vfs::FileSystem& fs,
|
|
llvm::StringRef filename)
|
|
-> ErrorOr<SourceBuffer> {
|
|
llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> file =
|
|
fs.openFileForRead(filename);
|
|
if (file.getError()) {
|
|
return Error(file.getError().message());
|
|
}
|
|
|
|
llvm::ErrorOr<llvm::vfs::Status> status = (*file)->status();
|
|
if (status.getError()) {
|
|
return Error(status.getError().message());
|
|
}
|
|
auto size = status->getSize();
|
|
if (size >= std::numeric_limits<int32_t>::max()) {
|
|
return Error(
|
|
llvm::formatv("`{0}` is over the 2GiB input limit.", filename));
|
|
}
|
|
|
|
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
|
|
(*file)->getBuffer(filename, size, /*RequiresNullTerminator=*/false);
|
|
if (buffer.getError()) {
|
|
return Error(buffer.getError().message());
|
|
}
|
|
|
|
return SourceBuffer(filename.str(), std::move(buffer.get()));
|
|
}
|
|
|
|
} // namespace Carbon
|