static_scope.cpp 2.0 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. #include "executable_semantics/ast/static_scope.h"
  5. #include "executable_semantics/common/error.h"
  6. #include "llvm/Support/Error.h"
  7. namespace Carbon {
  8. auto StaticScope::Add(std::string name, ValueNodeView entity)
  9. -> ErrorOr<Success> {
  10. auto [it, success] = declared_names_.insert({name, entity});
  11. if (!success && it->second != entity) {
  12. return FATAL_COMPILATION_ERROR(entity.base().source_loc())
  13. << "Duplicate name `" << name << "` also found at "
  14. << it->second.base().source_loc();
  15. }
  16. return Success();
  17. }
  18. auto StaticScope::Resolve(const std::string& name,
  19. SourceLocation source_loc) const
  20. -> ErrorOr<ValueNodeView> {
  21. ASSIGN_OR_RETURN(std::optional<ValueNodeView> result,
  22. TryResolve(name, source_loc));
  23. if (!result) {
  24. return FATAL_COMPILATION_ERROR(source_loc)
  25. << "could not resolve '" << name << "'";
  26. }
  27. return *result;
  28. }
  29. auto StaticScope::TryResolve(const std::string& name,
  30. SourceLocation source_loc) const
  31. -> ErrorOr<std::optional<ValueNodeView>> {
  32. auto it = declared_names_.find(name);
  33. if (it != declared_names_.end()) {
  34. return std::make_optional(it->second);
  35. }
  36. std::optional<ValueNodeView> result;
  37. for (Nonnull<const StaticScope*> parent : parent_scopes_) {
  38. ASSIGN_OR_RETURN(std::optional<ValueNodeView> parent_result,
  39. parent->TryResolve(name, source_loc));
  40. if (parent_result.has_value() && result.has_value() &&
  41. *parent_result != *result) {
  42. return FATAL_COMPILATION_ERROR(source_loc)
  43. << "'" << name << "' is ambiguous between "
  44. << result->base().source_loc() << " and "
  45. << parent_result->base().source_loc();
  46. }
  47. result = parent_result;
  48. }
  49. return result;
  50. }
  51. } // namespace Carbon