static_scope.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. it->second.usable |= usable;
  21. }
  22. return Success();
  23. }
  24. void StaticScope::MarkUsable(const std::string& name) {
  25. auto it = declared_names_.find(name);
  26. CARBON_CHECK(it != declared_names_.end()) << name << " not found";
  27. it->second.usable = true;
  28. }
  29. auto StaticScope::Resolve(const std::string& name,
  30. SourceLocation source_loc) const
  31. -> ErrorOr<ValueNodeView> {
  32. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> result,
  33. TryResolve(name, source_loc));
  34. if (!result) {
  35. return CompilationError(source_loc) << "could not resolve '" << name << "'";
  36. }
  37. return *result;
  38. }
  39. auto StaticScope::TryResolve(const std::string& name,
  40. SourceLocation source_loc) const
  41. -> ErrorOr<std::optional<ValueNodeView>> {
  42. auto it = declared_names_.find(name);
  43. if (it != declared_names_.end()) {
  44. if (!it->second.usable) {
  45. return CompilationError(source_loc)
  46. << "'" << name
  47. << "' is not usable until after it has been completely declared";
  48. }
  49. return std::make_optional(it->second.entity);
  50. }
  51. std::optional<ValueNodeView> result;
  52. for (Nonnull<const StaticScope*> parent : parent_scopes_) {
  53. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> parent_result,
  54. parent->TryResolve(name, source_loc));
  55. if (parent_result.has_value() && result.has_value() &&
  56. *parent_result != *result) {
  57. return CompilationError(source_loc)
  58. << "'" << name << "' is ambiguous between "
  59. << result->base().source_loc() << " and "
  60. << parent_result->base().source_loc();
  61. }
  62. result = parent_result;
  63. }
  64. return result;
  65. }
  66. } // namespace Carbon