static_scope.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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/static_scope.h"
  5. #include "explorer/common/error_builders.h"
  6. #include "llvm/Support/Error.h"
  7. namespace Carbon {
  8. auto StaticScope::Add(const std::string& name, ValueNodeView entity,
  9. bool usable) -> ErrorOr<Success> {
  10. auto [it, inserted] = declared_names_.insert({name, {entity, usable}});
  11. if (!inserted) {
  12. if (it->second.entity != entity) {
  13. return CompilationError(entity.base().source_loc())
  14. << "Duplicate name `" << name << "` also found at "
  15. << it->second.entity.base().source_loc();
  16. }
  17. CARBON_CHECK(usable || !it->second.usable)
  18. << entity.base().source_loc() << " attempting to mark a usable name `"
  19. << name << "` as unusable";
  20. }
  21. return Success();
  22. }
  23. void StaticScope::MarkUsable(const std::string& name) {
  24. auto it = declared_names_.find(name);
  25. CARBON_CHECK(it != declared_names_.end()) << name << " not found";
  26. it->second.usable = true;
  27. }
  28. auto StaticScope::Resolve(const std::string& name,
  29. SourceLocation source_loc) const
  30. -> ErrorOr<ValueNodeView> {
  31. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> result,
  32. TryResolve(name, source_loc));
  33. if (!result) {
  34. return CompilationError(source_loc) << "could not resolve '" << name << "'";
  35. }
  36. return *result;
  37. }
  38. auto StaticScope::TryResolve(const std::string& name,
  39. SourceLocation source_loc) const
  40. -> ErrorOr<std::optional<ValueNodeView>> {
  41. auto it = declared_names_.find(name);
  42. if (it != declared_names_.end()) {
  43. if (!it->second.usable) {
  44. return CompilationError(source_loc)
  45. << "'" << name
  46. << "' is not usable until after it has been completely declared";
  47. }
  48. return std::make_optional(it->second.entity);
  49. }
  50. std::optional<ValueNodeView> result;
  51. for (Nonnull<const StaticScope*> parent : parent_scopes_) {
  52. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> parent_result,
  53. parent->TryResolve(name, source_loc));
  54. if (parent_result.has_value() && result.has_value() &&
  55. *parent_result != *result) {
  56. return CompilationError(source_loc)
  57. << "'" << name << "' is ambiguous between "
  58. << result->base().source_loc() << " and "
  59. << parent_result->base().source_loc();
  60. }
  61. result = parent_result;
  62. }
  63. return result;
  64. }
  65. } // namespace Carbon