impl_scope.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 "executable_semantics/interpreter/impl_scope.h"
  5. #include "executable_semantics/common/error.h"
  6. #include "executable_semantics/interpreter/value.h"
  7. #include "llvm/Support/Casting.h"
  8. using llvm::cast;
  9. namespace Carbon {
  10. void ImplScope::Add(Nonnull<const Value*> iface, Nonnull<const Value*> type,
  11. ValueNodeView impl) {
  12. impls_.push_back({.interface = iface, .type = type, .impl = impl});
  13. }
  14. void ImplScope::AddParent(Nonnull<const ImplScope*> parent) {
  15. parent_scopes_.push_back(parent);
  16. }
  17. auto ImplScope::Resolve(Nonnull<const Value*> iface_type,
  18. Nonnull<const Value*> type,
  19. SourceLocation source_loc) const
  20. -> ErrorOr<ValueNodeView> {
  21. ASSIGN_OR_RETURN(std::optional<ValueNodeView> result,
  22. TryResolve(iface_type, type, source_loc));
  23. if (!result.has_value()) {
  24. return FATAL_COMPILATION_ERROR(source_loc)
  25. << "could not find implementation of " << *iface_type << " for "
  26. << *type;
  27. }
  28. return *result;
  29. }
  30. auto ImplScope::TryResolve(Nonnull<const Value*> iface_type,
  31. Nonnull<const Value*> type,
  32. SourceLocation source_loc) const
  33. -> ErrorOr<std::optional<ValueNodeView>> {
  34. std::optional<ValueNodeView> result =
  35. ResolveHere(iface_type, type, source_loc);
  36. if (result.has_value()) {
  37. return result;
  38. }
  39. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  40. ASSIGN_OR_RETURN(auto parent_result,
  41. parent->TryResolve(iface_type, type, source_loc));
  42. if (parent_result.has_value() && result.has_value() &&
  43. *parent_result != *result) {
  44. return FATAL_COMPILATION_ERROR(source_loc)
  45. << "ambiguous implementations of " << *iface_type << " for "
  46. << *type;
  47. }
  48. result = parent_result;
  49. }
  50. return result;
  51. }
  52. auto ImplScope::ResolveHere(Nonnull<const Value*> iface_type,
  53. Nonnull<const Value*> impl_type,
  54. SourceLocation /*source_loc*/) const
  55. -> std::optional<ValueNodeView> {
  56. switch (iface_type->kind()) {
  57. case Value::Kind::InterfaceType: {
  58. const auto& iface = cast<InterfaceType>(*iface_type);
  59. for (const Impl& impl : impls_) {
  60. if (TypeEqual(&iface, impl.interface) &&
  61. TypeEqual(impl_type, impl.type)) {
  62. return impl.impl;
  63. }
  64. }
  65. return std::nullopt;
  66. }
  67. default:
  68. FATAL() << "expected an interface, not " << *iface_type;
  69. break;
  70. }
  71. }
  72. } // namespace Carbon