element.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. #include "explorer/ast/element.h"
  5. #include "common/check.h"
  6. #include "explorer/ast/declaration.h"
  7. namespace Carbon {
  8. NamedElement::NamedElement(Nonnull<const Declaration*> declaration)
  9. : Element(ElementKind::NamedElement), element_(declaration) {}
  10. NamedElement::NamedElement(Nonnull<const NamedValue*> struct_member)
  11. : Element(ElementKind::NamedElement), element_(struct_member) {}
  12. auto NamedElement::IsNamed(std::string_view name) const -> bool {
  13. return this->name() == name;
  14. }
  15. auto NamedElement::name() const -> std::string_view {
  16. if (const auto* decl = element_.dyn_cast<const Declaration*>()) {
  17. return GetName(*decl).value();
  18. } else {
  19. const auto* named_value = element_.get<const NamedValue*>();
  20. return named_value->name;
  21. }
  22. }
  23. auto NamedElement::type() const -> const Value& {
  24. if (const auto* decl = element_.dyn_cast<const Declaration*>()) {
  25. return decl->static_type();
  26. } else {
  27. const auto* named_value = element_.get<const NamedValue*>();
  28. return *named_value->value;
  29. }
  30. }
  31. auto NamedElement::declaration() const
  32. -> std::optional<Nonnull<const Declaration*>> {
  33. if (const auto* decl = element_.dyn_cast<const Declaration*>()) {
  34. return decl;
  35. }
  36. return std::nullopt;
  37. }
  38. auto NamedElement::struct_member() const
  39. -> std::optional<Nonnull<const NamedValue*>> {
  40. if (const auto* member = element_.dyn_cast<const NamedValue*>()) {
  41. return member;
  42. }
  43. return std::nullopt;
  44. }
  45. void NamedElement::Print(llvm::raw_ostream& out) const { out << name(); }
  46. // Prints the Element
  47. void PositionalElement::Print(llvm::raw_ostream& out) const {
  48. out << "element #" << index_;
  49. }
  50. // Return whether the element's name matches `name`.
  51. auto PositionalElement::IsNamed(std::string_view /*name*/) const -> bool {
  52. return false;
  53. }
  54. void BaseElement::Print(llvm::raw_ostream& out) const { out << "base class"; }
  55. // Return whether the element's name matches `name`.
  56. auto BaseElement::IsNamed(std::string_view /*name*/) const -> bool {
  57. return false;
  58. }
  59. } // namespace Carbon