source_buffer.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/source/source_buffer.h"
  5. #include <limits>
  6. #include "llvm/Support/ErrorOr.h"
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon {
  9. auto SourceBuffer::CreateFromFile(llvm::vfs::FileSystem& fs,
  10. llvm::StringRef filename)
  11. -> ErrorOr<SourceBuffer> {
  12. llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> file =
  13. fs.openFileForRead(filename);
  14. if (file.getError()) {
  15. return Error(file.getError().message());
  16. }
  17. llvm::ErrorOr<llvm::vfs::Status> status = (*file)->status();
  18. if (status.getError()) {
  19. return Error(status.getError().message());
  20. }
  21. auto size = status->getSize();
  22. if (size >= std::numeric_limits<int32_t>::max()) {
  23. return Error(
  24. llvm::formatv("`{0}` is over the 2GiB input limit.", filename));
  25. }
  26. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
  27. (*file)->getBuffer(filename, size, /*RequiresNullTerminator=*/false);
  28. if (buffer.getError()) {
  29. return Error(buffer.getError().message());
  30. }
  31. return SourceBuffer(filename.str(), std::move(buffer.get()));
  32. }
  33. } // namespace Carbon