absolute_node_ref.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 CARBON_TOOLCHAIN_SEM_IR_ABSOLUTE_NODE_REF_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_ABSOLUTE_NODE_REF_H_
  6. #include "toolchain/parse/tree_and_subtrees.h"
  7. #include "toolchain/sem_ir/file.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. namespace Carbon::SemIR {
  10. // A specific node location in a file. Usually refers to a NodeId in a Carbon
  11. // source file, but can also refer to a Clang source location within imported
  12. // C++ code.
  13. class AbsoluteNodeRef {
  14. public:
  15. // A specific node location in a file.
  16. explicit AbsoluteNodeRef(const File* file, Parse::NodeId node_id)
  17. : file_(file), is_cpp_(false), node_id_(node_id) {}
  18. // A Clang source location within imported C++ code.
  19. explicit AbsoluteNodeRef(const File* file,
  20. ClangSourceLocId clang_source_loc_id)
  21. : file_(file), is_cpp_(true), clang_source_loc_id_(clang_source_loc_id) {}
  22. // The file containing the location.
  23. auto file() const -> const File* { return file_; }
  24. // The ID of the IR.
  25. auto check_ir_id() const -> CheckIRId { return file_->check_ir_id(); }
  26. // Returns true if this is a C++ location.
  27. auto is_cpp() const -> bool { return is_cpp_; }
  28. // The specific node location in a file. Must be called only if
  29. // `is_cpp()` is false.
  30. auto node_id() const -> Parse::NodeId {
  31. CARBON_CHECK(!is_cpp());
  32. return node_id_;
  33. }
  34. // The Clang source location. Must be called only if `is_cpp()` is true.
  35. auto clang_source_loc_id() const -> ClangSourceLocId {
  36. CARBON_CHECK(is_cpp());
  37. return clang_source_loc_id_;
  38. }
  39. private:
  40. // The file containing the location.
  41. const File* file_;
  42. // True if this is a C++ location.
  43. bool is_cpp_;
  44. union {
  45. // See `node_id()`.
  46. Parse::NodeId node_id_;
  47. // See `clang_source_loc_id()`.
  48. ClangSourceLocId clang_source_loc_id_;
  49. };
  50. };
  51. // Resolves the `LocId` to a series of `AbsoluteNodeRef`s, which may be in
  52. // different files. The vector will have one entry if there were no imports, and
  53. // multiple entries when imports are traversed. The final entry is the actual
  54. // declaration.
  55. //
  56. // Note that the `LocId` here is typically not canonical, and it uses that fact
  57. // for non-canonical locations built from an `ExportDecl` instruction.
  58. auto GetAbsoluteNodeRef(const File* sem_ir, LocId loc_id)
  59. -> llvm::SmallVector<AbsoluteNodeRef>;
  60. } // namespace Carbon::SemIR
  61. #endif // CARBON_TOOLCHAIN_SEM_IR_ABSOLUTE_NODE_REF_H_