decl_name_stack.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. // The name has already been finished. This is not set in the name
  74. // returned by `FinishName`, but is used internally to track that
  75. // `FinishName` has already been called.
  76. Finished,
  77. // An error has occurred, such as an additional qualifier past an
  78. // unresolved name. No new diagnostics should be emitted.
  79. Error,
  80. };
  81. // Combines name information to produce a base struct for entity
  82. // construction.
  83. auto MakeEntityWithParamsBase(SemIR::InstId decl_id,
  84. const NameComponent& name)
  85. -> SemIR::EntityWithParamsBase {
  86. return {
  87. .name_id = name_id_for_new_inst(),
  88. .parent_scope_id = parent_scope_id_for_new_inst(),
  89. .generic_id = SemIR::GenericId::Invalid,
  90. .first_param_node_id = name.first_param_node_id,
  91. .last_param_node_id = name.last_param_node_id,
  92. .implicit_param_refs_id = name.implicit_params_id,
  93. .param_refs_id = name.params_id,
  94. .decl_id = decl_id,
  95. };
  96. }
  97. // Returns any name collision found, or Invalid.
  98. auto prev_inst_id() -> SemIR::InstId;
  99. // Returns the name_id for a new instruction. This is invalid when the name
  100. // resolved.
  101. auto name_id_for_new_inst() -> SemIR::NameId {
  102. return state == State::Unresolved ? unresolved_name_id
  103. : SemIR::NameId::Invalid;
  104. }
  105. // Returns the parent_scope_id for a new instruction. This is invalid
  106. // when the name resolved.
  107. auto parent_scope_id_for_new_inst() -> SemIR::NameScopeId {
  108. return state == State::Unresolved ? parent_scope_id
  109. : SemIR::NameScopeId::Invalid;
  110. }
  111. // The current scope when this name began. This is the scope that we will
  112. // return to at the end of the declaration.
  113. ScopeIndex initial_scope_index;
  114. State state = State::Empty;
  115. // Whether there have been qualifiers in the name.
  116. bool has_qualifiers = false;
  117. // The scope which qualified names are added to. For unqualified names in
  118. // an unnamed scope, this will be Invalid to indicate the current scope
  119. // should be used.
  120. SemIR::NameScopeId parent_scope_id;
  121. // The last location ID used.
  122. SemIR::LocId loc_id = SemIR::LocId::Invalid;
  123. union {
  124. // The ID of a resolved qualifier, including both identifiers and
  125. // expressions. Invalid indicates resolution failed.
  126. SemIR::InstId resolved_inst_id;
  127. // The ID of an unresolved identifier.
  128. SemIR::NameId unresolved_name_id = SemIR::NameId::Invalid;
  129. };
  130. };
  131. // Information about a declaration name that has been temporarily removed from
  132. // the stack and will later be restored. Names can only be suspended once they
  133. // are finished.
  134. struct SuspendedName {
  135. // The declaration name information.
  136. NameContext name_context;
  137. // Suspended scopes. We only preallocate space for two of these, because
  138. // suspended names are usually used for classes and functions with
  139. // unqualified names, which only need at most two scopes -- one scope for
  140. // the parameter and one scope for the entity itself, and we can store quite
  141. // a few of these when processing a large class definition.
  142. llvm::SmallVector<ScopeStack::SuspendedScope, 2> scopes;
  143. };
  144. explicit DeclNameStack(Context* context) : context_(context) {}
  145. // Pushes processing of a new declaration name, which will be used
  146. // contextually, and prepares to enter scopes for that name. To pop this
  147. // state, `FinishName` and `PopScope` must be called, in that order.
  148. auto PushScopeAndStartName() -> void;
  149. // Creates and returns a name context corresponding to declaring an
  150. // unqualified name in the current context. This is suitable for adding to
  151. // name lookup in situations where a qualified name is not permitted, such as
  152. // a pattern binding.
  153. auto MakeUnqualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id)
  154. -> NameContext;
  155. // Applies a name component as a qualifier for the current name. This will
  156. // enter the scope corresponding to the name if the name describes an existing
  157. // scope, such as a namespace or a defined class.
  158. auto ApplyNameQualifier(const NameComponent& name) -> void;
  159. // Finishes the current declaration name processing, returning the final
  160. // context for adding the name to lookup. The final name component should be
  161. // popped and passed to this function, and will be added to the declaration
  162. // name.
  163. auto FinishName(const NameComponent& name) -> NameContext;
  164. // Finishes the current declaration name processing for an `impl`, returning
  165. // the final context for adding the name to lookup.
  166. //
  167. // `impl`s don't actually have names, but want the rest of the name processing
  168. // logic such as building parameter scopes, so are a special case.
  169. auto FinishImplName() -> NameContext;
  170. // Pops the declaration name from the declaration name stack, and pops all
  171. // scopes that were entered as part of handling the declaration name. These
  172. // are the scopes corresponding to name qualifiers in the name, for example
  173. // the `A.B` in `fn A.B.F()`.
  174. //
  175. // This should be called at the end of the declaration.
  176. auto PopScope() -> void;
  177. // Peeks the current parent scope of the name on top of the stack. Note
  178. // that if we're still processing the name qualifiers, this can change before
  179. // the name is completed. Also, if the name up to this point was already
  180. // declared and is a scope, this will be that scope, rather than the scope
  181. // containing it.
  182. auto PeekParentScopeId() const -> SemIR::NameScopeId {
  183. return decl_name_stack_.back().parent_scope_id;
  184. }
  185. // Peeks the resolution scope index of the name on top of the stack.
  186. auto PeekInitialScopeIndex() const -> ScopeIndex {
  187. return decl_name_stack_.back().initial_scope_index;
  188. }
  189. // Temporarily remove the current declaration name and its associated scopes
  190. // from the stack. Can only be called once the name is finished.
  191. auto Suspend() -> SuspendedName;
  192. // Restore a previously suspended name.
  193. auto Restore(SuspendedName sus) -> void;
  194. // Adds a name to name lookup. Assumes duplicates are already handled.
  195. auto AddName(NameContext name_context, SemIR::InstId target_id,
  196. SemIR::AccessKind access_kind) -> void;
  197. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  198. auto AddNameOrDiagnoseDuplicate(NameContext name_context,
  199. SemIR::InstId target_id,
  200. SemIR::AccessKind access_kind) -> void;
  201. // Adds a name to name lookup, or returns the existing instruction if this
  202. // name has already been declared in this scope.
  203. auto LookupOrAddName(NameContext name_context, SemIR::InstId target_id,
  204. SemIR::AccessKind access_kind) -> SemIR::InstId;
  205. private:
  206. // Returns a name context corresponding to an empty name.
  207. auto MakeEmptyNameContext() -> NameContext;
  208. // Appends a name to the given name context, and performs a lookup to find
  209. // what, if anything, the name refers to.
  210. auto ApplyAndLookupName(NameContext& name_context, SemIR::LocId loc_id,
  211. SemIR::NameId name_id) -> void;
  212. // Attempts to resolve the given name context as a scope, and returns the
  213. // corresponding scope. Issues a suitable diagnostic and returns Invalid if
  214. // the name doesn't resolve to a scope.
  215. auto ResolveAsScope(const NameContext& name_context,
  216. const NameComponent& name) const
  217. -> std::pair<SemIR::NameScopeId, SemIR::SpecificId>;
  218. // The linked context.
  219. Context* context_;
  220. // Provides nesting for construction.
  221. llvm::SmallVector<NameContext> decl_name_stack_;
  222. };
  223. } // namespace Carbon::Check
  224. #endif // CARBON_TOOLCHAIN_CHECK_DECL_NAME_STACK_H_