source_buffer.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. namespace Carbon {
  8. auto SourceBuffer::CreateFromFile(llvm::vfs::FileSystem& fs,
  9. llvm::raw_ostream& error_stream,
  10. llvm::StringRef filename)
  11. -> std::optional<SourceBuffer> {
  12. llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> file =
  13. fs.openFileForRead(filename);
  14. if (file.getError()) {
  15. error_stream << "Error opening `" << filename
  16. << "`: " << file.getError().message();
  17. return std::nullopt;
  18. }
  19. llvm::ErrorOr<llvm::vfs::Status> status = (*file)->status();
  20. if (status.getError()) {
  21. error_stream << "Error getting status for `" << filename
  22. << "`: " << file.getError().message();
  23. return std::nullopt;
  24. }
  25. auto size = status->getSize();
  26. if (size >= std::numeric_limits<int32_t>::max()) {
  27. error_stream << "Cannot load `" << filename
  28. << "`: file is over the 2GiB input limit.";
  29. return std::nullopt;
  30. }
  31. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
  32. (*file)->getBuffer(filename, size, /*RequiresNullTerminator=*/false);
  33. if (buffer.getError()) {
  34. error_stream << "Error reading `" << filename
  35. << "`: " << file.getError().message();
  36. return std::nullopt;
  37. }
  38. return SourceBuffer(filename.str(), std::move(buffer.get()));
  39. }
  40. } // namespace Carbon