static_scope.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. namespace Carbon {
  7. void StaticScope::Add(std::string name, ValueNodeView entity) {
  8. auto [it, success] = declared_names_.insert({name, entity});
  9. if (!success && it->second != entity) {
  10. FATAL_COMPILATION_ERROR(entity.base().source_loc())
  11. << "Duplicate name `" << name << "` also found at "
  12. << it->second.base().source_loc();
  13. }
  14. }
  15. auto StaticScope::Resolve(const std::string& name,
  16. SourceLocation source_loc) const -> ValueNodeView {
  17. std::optional<ValueNodeView> result = TryResolve(name, source_loc);
  18. if (!result.has_value()) {
  19. FATAL_COMPILATION_ERROR(source_loc) << "could not resolve '" << name << "'";
  20. }
  21. return *result;
  22. }
  23. auto StaticScope::TryResolve(const std::string& name,
  24. SourceLocation source_loc) const
  25. -> std::optional<ValueNodeView> {
  26. auto it = declared_names_.find(name);
  27. if (it != declared_names_.end()) {
  28. return it->second;
  29. }
  30. std::optional<ValueNodeView> result;
  31. for (Nonnull<const StaticScope*> parent : parent_scopes_) {
  32. auto parent_result = parent->TryResolve(name, source_loc);
  33. if (parent_result.has_value() && result.has_value() &&
  34. *parent_result != *result) {
  35. FATAL_COMPILATION_ERROR(source_loc)
  36. << "'" << name << "' is ambiguous between "
  37. << result->base().source_loc() << " and "
  38. << parent_result->base().source_loc();
  39. }
  40. result = parent_result;
  41. }
  42. return result;
  43. }
  44. } // namespace Carbon