decl_name_stack.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 CARBON_TOOLCHAIN_CHECK_DECL_NAME_STACK_H_
  5. #define CARBON_TOOLCHAIN_CHECK_DECL_NAME_STACK_H_
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/check/name_component.h"
  8. #include "toolchain/check/scope_index.h"
  9. #include "toolchain/check/scope_stack.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. namespace Carbon::Check {
  12. class Context;
  13. // Provides support and stacking for qualified declaration name handling.
  14. //
  15. // A qualified declaration name will consist of entries, which are `Name`s
  16. // optionally followed by generic parameter lists, such as `Vector(T:! type)`
  17. // in `fn Vector(T:! type).Clear();`, but parameter lists aren't supported yet.
  18. // Identifiers such as `Clear` will be resolved to a name if possible, for
  19. // example when declaring things that are in a non-generic type or namespace,
  20. // and are otherwise marked as an unresolved identifier.
  21. //
  22. // Unresolved identifiers are valid if and only if they are the last step of a
  23. // qualified name; all resolved qualifiers must resolve to an entity with
  24. // members, such as a namespace. Resolved identifiers in the last step will
  25. // occur for both out-of-line definitions and new declarations, depending on
  26. // context.
  27. //
  28. // For each name component that is processed and denotes a scope, the
  29. // corresponding scope is also entered. This is important for unqualified name
  30. // lookup both in the definition of the entity being declared, and for names
  31. // appearing later in the declaration name itself. For example, in:
  32. //
  33. // ```
  34. // fn ClassA.ClassB(T:! U).Fn() { var x: V; }
  35. // ```
  36. //
  37. // the lookup for `U` looks in `ClassA`; the lookup for `V` looks first in
  38. // `ClassA.ClassB`, then its parent scope `ClassA`. Scopes entered as part of
  39. // processing the name are exited when the name is popped from the stack.
  40. //
  41. // Example state transitions:
  42. //
  43. // ```
  44. // // Empty -> Unresolved, because `MyNamespace` is newly declared.
  45. // namespace MyNamespace;
  46. //
  47. // // Empty -> Resolved -> Unresolved, because `MyType` is newly declared.
  48. // class MyNamespace.MyType;
  49. //
  50. // // Empty -> Resolved -> Resolved, because `MyType` was forward declared.
  51. // class MyNamespace.MyType {
  52. // // Empty -> Unresolved, because `DoSomething` is newly declared.
  53. // fn DoSomething();
  54. // }
  55. //
  56. // // Empty -> Resolved -> Resolved -> ResolvedNonScope, because `DoSomething`
  57. // // is forward declared in `MyType`, but is not a scope itself.
  58. // fn MyNamespace.MyType.DoSomething() { ... }
  59. // ```
  60. class DeclNameStack {
  61. public:
  62. // Context for declaration name construction.
  63. // TODO: Add a helper for class, function, and interface to turn a NameContext
  64. // into an EntityWithParamsBase.
  65. struct NameContext {
  66. enum class State : int8_t {
  67. // A context that has not processed any parts of the qualifier.
  68. Empty,
  69. // The name has been resolved to an instruction ID.
  70. Resolved,
  71. // An identifier didn't resolve.
  72. Unresolved,
  73. // An identifier was poisoned in this scope.
  74. Poisoned,
  75. // The name has already been finished. This is not set in the name
  76. // returned by `FinishName`, but is used internally to track that
  77. // `FinishName` has already been called.
  78. Finished,
  79. // An error has occurred, such as an additional qualifier past an
  80. // unresolved name. No new diagnostics should be emitted.
  81. Error,
  82. };
  83. // Combines name information to produce a base struct for entity
  84. // construction.
  85. auto MakeEntityWithParamsBase(const NameComponent& name,
  86. SemIR::InstId decl_id, bool is_extern,
  87. SemIR::LibraryNameId extern_library) const
  88. -> SemIR::EntityWithParamsBase {
  89. return {
  90. .name_id = name.name_id,
  91. .parent_scope_id = parent_scope_id,
  92. .generic_id = SemIR::GenericId::None,
  93. .first_param_node_id = name.first_param_node_id,
  94. .last_param_node_id = name.last_param_node_id,
  95. .pattern_block_id = name.pattern_block_id,
  96. .implicit_param_patterns_id = name.implicit_param_patterns_id,
  97. .param_patterns_id = name.param_patterns_id,
  98. .is_extern = is_extern,
  99. .extern_library_id = extern_library,
  100. .non_owning_decl_id =
  101. extern_library.has_value() ? decl_id : SemIR::InstId::None,
  102. .first_owning_decl_id =
  103. extern_library.has_value() ? SemIR::InstId::None : decl_id,
  104. };
  105. }
  106. // Returns any name collision found, or `None`. Requires a non-poisoned
  107. // value.
  108. auto prev_inst_id() const -> SemIR::InstId;
  109. // Returns the name_id for a new instruction. This is `None` when the name
  110. // resolved.
  111. auto name_id_for_new_inst() const -> SemIR::NameId {
  112. switch (state) {
  113. case State::Unresolved:
  114. case State::Poisoned:
  115. return name_id;
  116. default:
  117. return SemIR::NameId::None;
  118. }
  119. }
  120. // The current scope when this name began. This is the scope that we will
  121. // return to at the end of the declaration.
  122. ScopeIndex initial_scope_index;
  123. State state = State::Empty;
  124. // Whether there have been qualifiers in the name.
  125. bool has_qualifiers = false;
  126. // The scope which qualified names are added to. For unqualified names in
  127. // an unnamed scope, this will be `None` to indicate the current scope
  128. // should be used.
  129. SemIR::NameScopeId parent_scope_id;
  130. // The location of the final name component.
  131. SemIR::LocId loc_id = SemIR::LocId::None;
  132. // The name of the final name component.
  133. SemIR::NameId name_id = SemIR::NameId::None;
  134. union {
  135. // The ID of a resolved qualifier, including both identifiers and
  136. // expressions. `None` indicates resolution failed.
  137. SemIR::InstId resolved_inst_id;
  138. // When `state` is `Poisoned` (name is unresolved due to name poisoning),
  139. // the poisoning location.
  140. SemIR::LocId poisoning_loc_id = SemIR::LocId::None;
  141. };
  142. };
  143. // Information about a declaration name that has been temporarily removed from
  144. // the stack and will later be restored. Names can only be suspended once they
  145. // are finished.
  146. //
  147. // This type is large, so moves of this type should be avoided.
  148. struct SuspendedName : public MoveOnly<SuspendedName> {
  149. // The declaration name information.
  150. NameContext name_context;
  151. // Suspended scopes. We only preallocate space for two of these, because
  152. // suspended names are usually used for classes and functions with
  153. // unqualified names, which only need at most two scopes -- one scope for
  154. // the parameter and one scope for the entity itself, and we can store quite
  155. // a few of these when processing a large class definition.
  156. llvm::SmallVector<ScopeStack::SuspendedScope, 2> scopes;
  157. };
  158. explicit DeclNameStack(Context* context) : context_(context) {}
  159. // Pushes processing of a new declaration name, which will be used
  160. // contextually, and prepares to enter scopes for that name. To pop this
  161. // state, `FinishName` and `PopScope` must be called, in that order.
  162. auto PushScopeAndStartName() -> void;
  163. // Creates and returns a name context corresponding to declaring an
  164. // unqualified name in the current context. This is suitable for adding to
  165. // name lookup in situations where a qualified name is not permitted, such as
  166. // a pattern binding.
  167. auto MakeUnqualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id)
  168. -> NameContext;
  169. // Applies a name component as a qualifier for the current name. This will
  170. // enter the scope corresponding to the name if the name describes an existing
  171. // scope, such as a namespace or a defined class.
  172. auto ApplyNameQualifier(const NameComponent& name) -> void;
  173. // Finishes the current declaration name processing, returning the final
  174. // context for adding the name to lookup. The final name component should be
  175. // popped and passed to this function, and will be added to the declaration
  176. // name.
  177. auto FinishName(const NameComponent& name) -> NameContext;
  178. // Finishes the current declaration name processing for an `impl`, returning
  179. // the final context for adding the name to lookup.
  180. //
  181. // `impl`s don't actually have names, but want the rest of the name processing
  182. // logic such as building parameter scopes, so are a special case.
  183. auto FinishImplName() -> NameContext;
  184. // Pops the declaration name from the declaration name stack, and pops all
  185. // scopes that were entered as part of handling the declaration name. These
  186. // are the scopes corresponding to name qualifiers in the name, for example
  187. // the `A.B` in `fn A.B.F()`.
  188. //
  189. // This should be called at the end of the declaration.
  190. // If check_unused is true, then performs unused bindings checks and emits
  191. // associated diagnostics.
  192. auto PopScope(bool check_unused = false) -> void;
  193. // Peeks the current parent scope of the name on top of the stack. Note
  194. // that if we're still processing the name qualifiers, this can change before
  195. // the name is completed. Also, if the name up to this point was already
  196. // declared and is a scope, this will be that scope, rather than the scope
  197. // containing it.
  198. auto PeekParentScopeId() const -> SemIR::NameScopeId {
  199. return decl_name_stack_.back().parent_scope_id;
  200. }
  201. // Peeks the resolution scope index of the name on top of the stack.
  202. auto PeekInitialScopeIndex() const -> ScopeIndex {
  203. return decl_name_stack_.back().initial_scope_index;
  204. }
  205. // Temporarily remove the current declaration name and its associated scopes
  206. // from the stack. Can only be called once the name is finished.
  207. auto Suspend() -> SuspendedName;
  208. // Restore a previously suspended name.
  209. auto Restore(SuspendedName&& sus) -> void;
  210. // Adds a name to name lookup. Assumes duplicates are already handled.
  211. auto AddName(NameContext name_context, SemIR::InstId target_id,
  212. SemIR::AccessKind access_kind) -> void;
  213. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  214. auto AddNameOrDiagnose(NameContext name_context, SemIR::InstId target_id,
  215. SemIR::AccessKind access_kind) -> void;
  216. // Adds a name to name lookup if neither already declared nor poisoned in this
  217. // scope.
  218. auto LookupOrAddName(NameContext name_context, SemIR::InstId target_id,
  219. SemIR::AccessKind access_kind)
  220. -> SemIR::ScopeLookupResult;
  221. // Runs verification that the processing cleanly finished.
  222. auto VerifyOnFinish() const -> void {
  223. CARBON_CHECK(decl_name_stack_.empty(),
  224. "decl_name_stack still has {0} entries",
  225. decl_name_stack_.size());
  226. }
  227. private:
  228. // Returns a name context corresponding to an empty name.
  229. auto MakeEmptyNameContext() -> NameContext;
  230. // Appends a name to the given name context, and performs a lookup to find
  231. // what, if anything, the name refers to.
  232. auto ApplyAndLookupName(NameContext& name_context, SemIR::LocId loc_id,
  233. SemIR::NameId name_id) -> void;
  234. // Attempts to resolve the given name context as a scope, and returns the
  235. // corresponding scope. Issues a suitable diagnostic and returns `None` if
  236. // the name doesn't resolve to a scope.
  237. auto ResolveAsScope(const NameContext& name_context,
  238. const NameComponent& name) const
  239. -> std::pair<SemIR::NameScopeId, SemIR::GenericId>;
  240. // The linked context.
  241. Context* context_;
  242. // Provides nesting for construction.
  243. llvm::SmallVector<NameContext> decl_name_stack_;
  244. };
  245. } // namespace Carbon::Check
  246. #endif // CARBON_TOOLCHAIN_CHECK_DECL_NAME_STACK_H_