element.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_.dyn_cast<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_.dyn_cast<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. void NamedElement::Print(llvm::raw_ostream& out) const { out << name(); }
  39. // Prints the Element
  40. void PositionalElement::Print(llvm::raw_ostream& out) const {
  41. out << "element #" << index_;
  42. }
  43. // Return whether the element's name matches `name`.
  44. auto PositionalElement::IsNamed(std::string_view /*name*/) const -> bool {
  45. return false;
  46. }
  47. void BaseElement::Print(llvm::raw_ostream& out) const { out << "base class"; }
  48. // Return whether the element's name matches `name`.
  49. auto BaseElement::IsNamed(std::string_view /*name*/) const -> bool {
  50. return false;
  51. }
  52. } // namespace Carbon