source_buffer.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef CARBON_TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_
  5. #define CARBON_TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_
  6. #include <memory>
  7. #include <string>
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/MemoryBuffer.h"
  10. #include "llvm/Support/VirtualFileSystem.h"
  11. namespace Carbon {
  12. // A buffer of Carbon source code.
  13. //
  14. // This class holds a buffer of Carbon source code as text and makes it
  15. // available for use in the rest of the Carbon compiler. It owns the memory for
  16. // the underlying source code text and ensures it lives as long as the buffer
  17. // objects.
  18. //
  19. // Every buffer of source code text is notionally loaded from a Carbon source
  20. // file, even if provided directly when constructing the buffer. The name that
  21. // should be used for that Carbon source file is also retained and made
  22. // available.
  23. //
  24. // Because the underlying memory for the source code text may have been read
  25. // from a file, and we may want to use facilities like `mmap` to simply map that
  26. // file into memory, the buffer itself is not copyable to avoid needing to
  27. // define copy semantics for a mapped file. We can relax this restriction with
  28. // some implementation complexity in the future if needed.
  29. class SourceBuffer {
  30. public:
  31. // Opens the requested file. Returns a SourceBuffer on success. Prints an
  32. // error and returns nullopt on failure.
  33. // TODO: Switch to using diagnostics.
  34. static auto CreateFromFile(llvm::vfs::FileSystem& fs,
  35. llvm::raw_ostream& error_stream,
  36. llvm::StringRef filename)
  37. -> std::optional<SourceBuffer>;
  38. // Use one of the factory functions above to create a source buffer.
  39. SourceBuffer() = delete;
  40. [[nodiscard]] auto filename() const -> llvm::StringRef { return filename_; }
  41. [[nodiscard]] auto text() const -> llvm::StringRef {
  42. return text_->getBuffer();
  43. }
  44. private:
  45. explicit SourceBuffer(std::string filename,
  46. std::unique_ptr<llvm::MemoryBuffer> text)
  47. : filename_(std::move(filename)), text_(std::move(text)) {}
  48. std::string filename_;
  49. std::unique_ptr<llvm::MemoryBuffer> text_;
  50. };
  51. } // namespace Carbon
  52. #endif // CARBON_TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_