source_location.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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_EXPLORER_BASE_SOURCE_LOCATION_H_
  5. #define CARBON_EXPLORER_BASE_SOURCE_LOCATION_H_
  6. #include <string>
  7. #include <string_view>
  8. #include "common/ostream.h"
  9. #include "explorer/base/nonnull.h"
  10. namespace Carbon {
  11. // Describes the kind of file that the source location is within.
  12. enum class FileKind { Main, Prelude, Import, Unknown, Last = Unknown };
  13. class SourceLocation : public Printable<SourceLocation> {
  14. public:
  15. // Produce a source location that is known to not be used, because it is fed
  16. // into an operation that creates no AST nodes and whose diagnostics are
  17. // discarded.
  18. static auto DiagnosticsIgnored() -> SourceLocation {
  19. return SourceLocation("", 0, FileKind::Unknown);
  20. }
  21. // The filename should be eternal or arena-allocated to eliminate copies.
  22. explicit constexpr SourceLocation(std::string_view filename, int line_num,
  23. FileKind file_kind)
  24. : filename_(filename), line_num_(line_num), file_kind_(file_kind) {}
  25. explicit SourceLocation(Nonnull<const std::string*> filename, int line_num,
  26. FileKind file_kind)
  27. : filename_(*filename), line_num_(line_num), file_kind_(file_kind) {}
  28. SourceLocation(const SourceLocation&) = default;
  29. SourceLocation(SourceLocation&&) = default;
  30. auto operator=(const SourceLocation&) -> SourceLocation& = default;
  31. auto operator=(SourceLocation&&) -> SourceLocation& = default;
  32. auto operator==(SourceLocation other) const -> bool {
  33. return filename_ == other.filename_ && line_num_ == other.line_num_ &&
  34. file_kind_ == other.file_kind_;
  35. }
  36. auto filename() const -> std::string_view { return filename_; }
  37. auto file_kind() const -> FileKind { return file_kind_; }
  38. void Print(llvm::raw_ostream& out) const {
  39. if (file_kind_ == FileKind::Prelude) {
  40. out << llvm::StringRef(filename_).rsplit("/").second << ":" << line_num_;
  41. } else {
  42. out << filename_ << ":" << line_num_;
  43. }
  44. }
  45. auto ToString() const -> std::string {
  46. std::string result;
  47. llvm::raw_string_ostream out(result);
  48. Print(out);
  49. return result;
  50. }
  51. private:
  52. std::string_view filename_;
  53. int line_num_;
  54. FileKind file_kind_;
  55. };
  56. } // namespace Carbon
  57. #endif // CARBON_EXPLORER_BASE_SOURCE_LOCATION_H_