source_buffer.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. namespace {
  9. struct FilenameTranslator : DiagnosticLocationTranslator<llvm::StringRef> {
  10. auto GetLocation(llvm::StringRef filename) -> DiagnosticLocation override {
  11. return {.file_name = filename};
  12. }
  13. };
  14. } // namespace
  15. auto SourceBuffer::CreateFromFile(llvm::vfs::FileSystem& fs,
  16. llvm::StringRef filename,
  17. DiagnosticConsumer& consumer)
  18. -> std::optional<SourceBuffer> {
  19. FilenameTranslator translator;
  20. DiagnosticEmitter<llvm::StringRef> emitter(translator, consumer);
  21. llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> file =
  22. fs.openFileForRead(filename);
  23. if (file.getError()) {
  24. CARBON_DIAGNOSTIC(ErrorOpeningFile, Error,
  25. "Error opening file for read: {0}", std::string);
  26. emitter.Emit(filename, ErrorOpeningFile, file.getError().message());
  27. return std::nullopt;
  28. }
  29. llvm::ErrorOr<llvm::vfs::Status> status = (*file)->status();
  30. if (status.getError()) {
  31. CARBON_DIAGNOSTIC(ErrorStattingFile, Error, "Error statting file: {0}",
  32. std::string);
  33. emitter.Emit(filename, ErrorStattingFile, file.getError().message());
  34. return std::nullopt;
  35. }
  36. int64_t size = status->getSize();
  37. if (size >= std::numeric_limits<int32_t>::max()) {
  38. CARBON_DIAGNOSTIC(FileTooLarge, Error,
  39. "File is over the 2GiB input limit; size is {0} bytes.",
  40. int64_t);
  41. emitter.Emit(filename, FileTooLarge, size);
  42. return std::nullopt;
  43. }
  44. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
  45. (*file)->getBuffer(filename, size, /*RequiresNullTerminator=*/false);
  46. if (buffer.getError()) {
  47. CARBON_DIAGNOSTIC(ErrorReadingFile, Error, "Error reading file: {0}",
  48. std::string);
  49. emitter.Emit(filename, ErrorReadingFile, file.getError().message());
  50. return std::nullopt;
  51. }
  52. return SourceBuffer(filename.str(), std::move(buffer.get()));
  53. }
  54. } // namespace Carbon