source_buffer.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_
  5. #define TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_
  6. #include <string>
  7. #include <utility>
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/ADT/Twine.h"
  10. #include "llvm/Support/Error.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. static auto CreateFromText(llvm::Twine text,
  32. llvm::StringRef filename = "/text")
  33. -> llvm::Expected<SourceBuffer>;
  34. static auto CreateFromFile(llvm::StringRef filename)
  35. -> llvm::Expected<SourceBuffer>;
  36. // Use one of the factory functions above to create a source buffer.
  37. SourceBuffer() = delete;
  38. // Cannot copy as there may be non-trivial owned file data; see the class
  39. // comment for details.
  40. SourceBuffer(const SourceBuffer& arg) = delete;
  41. SourceBuffer(SourceBuffer&& arg) noexcept;
  42. ~SourceBuffer();
  43. [[nodiscard]] auto filename() const -> llvm::StringRef { return filename_; }
  44. [[nodiscard]] auto text() const -> llvm::StringRef { return text_; }
  45. private:
  46. enum class ContentMode {
  47. Uninitialized,
  48. MMapped,
  49. Owned,
  50. };
  51. // Constructor for mmapped content.
  52. SourceBuffer(std::string filename, llvm::StringRef text);
  53. // Constructor for owned content.
  54. SourceBuffer(std::string filename, std::string text);
  55. ContentMode content_mode_;
  56. std::string filename_;
  57. std::string text_storage_;
  58. llvm::StringRef text_;
  59. };
  60. } // namespace Carbon
  61. #endif // TOOLCHAIN_SOURCE_SOURCE_BUFFER_H_