static_scope.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #ifndef EXECUTABLE_SEMANTICS_AST_STATIC_SCOPE_H_
  5. #define EXECUTABLE_SEMANTICS_AST_STATIC_SCOPE_H_
  6. #include <string>
  7. #include <unordered_map>
  8. #include <variant>
  9. #include <vector>
  10. #include "executable_semantics/ast/ast_node.h"
  11. #include "executable_semantics/ast/source_location.h"
  12. #include "executable_semantics/common/nonnull.h"
  13. namespace Carbon {
  14. class NamedEntity : public virtual AstNode {
  15. public:
  16. ~NamedEntity() override = 0;
  17. NamedEntity() = default;
  18. // TODO: This is unused, but is intended for casts after lookup.
  19. auto kind() const -> NamedEntityKind {
  20. return static_cast<NamedEntityKind>(root_kind());
  21. }
  22. };
  23. // Maps the names visible in a given scope to the entities they name.
  24. // A scope may have parent scopes, whose names will also be visible in the
  25. // child scope.
  26. class StaticScope {
  27. public:
  28. // Defines `name` to be `entity` in this scope, or reports a compilation error
  29. // if `name` is already defined in this scope.
  30. void Add(std::string name, Nonnull<const NamedEntity*> entity);
  31. // Make `parent` a parent of this scope.
  32. // REQUIRES: `parent` is not already a parent of this scope.
  33. void AddParent(Nonnull<StaticScope*> parent) {
  34. parent_scopes_.push_back(parent);
  35. }
  36. // Returns the nearest definition of `name` in the ancestor graph of this
  37. // scope, or reports a compilation error at `source_loc` there isn't exactly
  38. // one such definition.
  39. auto Resolve(const std::string& name, SourceLocation source_loc) const
  40. -> Nonnull<const NamedEntity*>;
  41. private:
  42. // Equivalent to Resolve, but returns `nullopt` instead of raising an error
  43. // if no definition can be found. Still raises a compilation error if more
  44. // than one definition is found.
  45. auto TryResolve(const std::string& name, SourceLocation source_loc) const
  46. -> std::optional<Nonnull<const NamedEntity*>>;
  47. // Maps locally declared names to their entities.
  48. std::unordered_map<std::string, Nonnull<const NamedEntity*>> declared_names_;
  49. // A list of scopes used for name lookup within this scope.
  50. std::vector<Nonnull<StaticScope*>> parent_scopes_;
  51. };
  52. } // namespace Carbon
  53. #endif // EXECUTABLE_SEMANTICS_AST_STATIC_SCOPE_H_