source_location.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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_COMMON_SOURCE_LOCATION_H_
  5. #define CARBON_EXPLORER_COMMON_SOURCE_LOCATION_H_
  6. #include <string>
  7. #include <string_view>
  8. #include "common/ostream.h"
  9. #include "explorer/common/nonnull.h"
  10. namespace Carbon {
  11. class SourceLocation {
  12. public:
  13. // Produce a source location that is known to not be used, because it is fed
  14. // into an operation that creates no AST nodes and whose diagnostics are
  15. // discarded.
  16. static auto DiagnosticsIgnored() -> SourceLocation {
  17. return SourceLocation("", 0);
  18. }
  19. // The filename should be eternal or arena-allocated to eliminate copies.
  20. constexpr SourceLocation(const char* filename, int line_num)
  21. : filename_(filename), line_num_(line_num) {}
  22. SourceLocation(Nonnull<const std::string*> filename, int line_num)
  23. : filename_(filename->c_str()), line_num_(line_num) {}
  24. SourceLocation(const SourceLocation&) = default;
  25. SourceLocation(SourceLocation&&) = default;
  26. auto operator=(const SourceLocation&) -> SourceLocation& = default;
  27. auto operator=(SourceLocation&&) -> SourceLocation& = default;
  28. auto operator==(SourceLocation other) const -> bool {
  29. return filename_ == other.filename_ && line_num_ == other.line_num_;
  30. }
  31. void Print(llvm::raw_ostream& out) const {
  32. out << filename_ << ":" << line_num_;
  33. }
  34. auto ToString() const -> std::string {
  35. std::string result;
  36. llvm::raw_string_ostream out(result);
  37. Print(out);
  38. return result;
  39. }
  40. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  41. private:
  42. std::string_view filename_;
  43. int line_num_;
  44. };
  45. } // namespace Carbon
  46. #endif // CARBON_EXPLORER_COMMON_SOURCE_LOCATION_H_