decl_name_stack.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/scope_index.h"
  8. #include "toolchain/check/scope_stack.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::Check {
  11. class Context;
  12. // Provides support and stacking for qualified declaration name handling.
  13. //
  14. // A qualified declaration name will consist of entries, which are `Name`s
  15. // optionally followed by generic parameter lists, such as `Vector(T:! type)`
  16. // in `fn Vector(T:! type).Clear();`, but parameter lists aren't supported yet.
  17. // Identifiers such as `Clear` will be resolved to a name if possible, for
  18. // example when declaring things that are in a non-generic type or namespace,
  19. // and are otherwise marked as an unresolved identifier.
  20. //
  21. // Unresolved identifiers are valid if and only if they are the last step of a
  22. // qualified name; all resolved qualifiers must resolve to an entity with
  23. // members, such as a namespace. Resolved identifiers in the last step will
  24. // occur for both out-of-line definitions and new declarations, depending on
  25. // context.
  26. //
  27. // For each name component that is processed and denotes a scope, the
  28. // corresponding scope is also entered. This is important for unqualified name
  29. // lookup both in the definition of the entity being declared, and for names
  30. // appearing later in the declaration name itself. For example, in:
  31. //
  32. // ```
  33. // fn ClassA.ClassB(T:! U).Fn() { var x: V; }
  34. // ```
  35. //
  36. // the lookup for `U` looks in `ClassA`, and the lookup for `V` looks in
  37. // `ClassA.ClassB` then in its enclosing scope `ClassA`. Scopes entered as part
  38. // of processing the name are exited when the name is popped from the stack.
  39. //
  40. // Example state transitions:
  41. //
  42. // ```
  43. // // Empty -> Unresolved, because `MyNamespace` is newly declared.
  44. // namespace MyNamespace;
  45. //
  46. // // Empty -> Resolved -> Unresolved, because `MyType` is newly declared.
  47. // class MyNamespace.MyType;
  48. //
  49. // // Empty -> Resolved -> Resolved, because `MyType` was forward declared.
  50. // class MyNamespace.MyType {
  51. // // Empty -> Unresolved, because `DoSomething` is newly declared.
  52. // fn DoSomething();
  53. // }
  54. //
  55. // // Empty -> Resolved -> Resolved -> ResolvedNonScope, because `DoSomething`
  56. // // is forward declared in `MyType`, but is not a scope itself.
  57. // fn MyNamespace.MyType.DoSomething() { ... }
  58. // ```
  59. class DeclNameStack {
  60. public:
  61. // Context for declaration name construction.
  62. struct NameContext {
  63. enum class State : int8_t {
  64. // A context that has not processed any parts of the qualifier.
  65. Empty,
  66. // An instruction ID has been resolved, whether through an identifier or
  67. // expression. This provided a new scope, such as a type.
  68. Resolved,
  69. // An instruction ID has been resolved, whether through an identifier or
  70. // expression. It did not provide a new scope, so must be the final part,
  71. // such as an out-of-line function definition.
  72. ResolvedNonScope,
  73. // An identifier didn't resolve.
  74. Unresolved,
  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. // Returns whether the name resolved to an existing entity.
  84. auto is_resolved() -> bool {
  85. return state != State::Unresolved && state != State::Empty;
  86. }
  87. // Returns the name_id for a new instruction. This is invalid when the name
  88. // resolved.
  89. auto name_id_for_new_inst() -> SemIR::NameId {
  90. return !is_resolved() ? unresolved_name_id : SemIR::NameId::Invalid;
  91. }
  92. // Returns the enclosing_scope_id for a new instruction. This is invalid
  93. // when the name resolved. Note this is distinct from the enclosing_scope of
  94. // the NameContext, which refers to the scope of the introducer rather than
  95. // the scope of the name.
  96. auto enclosing_scope_id_for_new_inst() -> SemIR::NameScopeId {
  97. return !is_resolved() ? target_scope_id : SemIR::NameScopeId::Invalid;
  98. }
  99. // The current scope when this name began. This is the scope that we will
  100. // return to at the end of the declaration.
  101. ScopeIndex enclosing_scope;
  102. State state = State::Empty;
  103. // Whether there have been qualifiers in the name.
  104. bool has_qualifiers = false;
  105. // The scope which qualified names are added to. For unqualified names in
  106. // an unnamed scope, this will be Invalid to indicate the current scope
  107. // should be used.
  108. SemIR::NameScopeId target_scope_id;
  109. // The last location ID used.
  110. SemIR::LocId loc_id = SemIR::LocId::Invalid;
  111. union {
  112. // The ID of a resolved qualifier, including both identifiers and
  113. // expressions. Invalid indicates resolution failed.
  114. SemIR::InstId resolved_inst_id = SemIR::InstId::Invalid;
  115. // The ID of an unresolved identifier.
  116. SemIR::NameId unresolved_name_id;
  117. };
  118. };
  119. // Information about a declaration name that has been temporarily removed from
  120. // the stack and will later be restored. Names can only be suspended once they
  121. // are finished.
  122. struct SuspendedName {
  123. // The declaration name information.
  124. NameContext name_context;
  125. // Suspended scopes. We only preallocate space for two of these, because
  126. // suspended names are usually used for classes and functions with
  127. // unqualified names, which only need at most two scopes -- one scope for
  128. // the parameter and one scope for the entity itself, and we can store quite
  129. // a few of these when processing a large class definition.
  130. llvm::SmallVector<ScopeStack::SuspendedScope, 2> scopes;
  131. };
  132. explicit DeclNameStack(Context* context) : context_(context) {}
  133. // Pushes processing of a new declaration name, which will be used
  134. // contextually, and prepares to enter scopes for that name. To pop this
  135. // state, `FinishName` and `PopScope` must be called, in that order.
  136. auto PushScopeAndStartName() -> void;
  137. // Peeks the current target scope of the name on top of the stack. Note that
  138. // if we're still processing the name qualifiers, this can change before the
  139. // name is completed. Also, if the name up to this point was already declared
  140. // and is a scope, this will be that scope, rather than the scope enclosing
  141. // it.
  142. auto PeekTargetScope() const -> SemIR::NameScopeId {
  143. return decl_name_stack_.back().target_scope_id;
  144. }
  145. // Peeks the enclosing scope index of the name on top of the stack.
  146. auto PeekEnclosingScope() const -> ScopeIndex {
  147. return decl_name_stack_.back().enclosing_scope;
  148. }
  149. // Finishes the current declaration name processing, returning the final
  150. // context for adding the name to lookup.
  151. //
  152. // This also pops the final name instruction from the instruction stack,
  153. // which will be applied to the declaration name if appropriate.
  154. auto FinishName() -> NameContext;
  155. // Finishes the current declaration name processing for an `impl`, returning
  156. // the final context for adding the name to lookup.
  157. //
  158. // `impl`s don't actually have names, but want the rest of the name processing
  159. // logic such as building parameter scopes, so are a special case.
  160. auto FinishImplName() -> NameContext;
  161. // Pops the declaration name from the declaration name stack, and pops all
  162. // scopes that were entered as part of handling the declaration name. These
  163. // are the scopes corresponding to name qualifiers in the name, for example
  164. // the `A.B` in `fn A.B.F()`.
  165. //
  166. // This should be called at the end of the declaration.
  167. auto PopScope() -> void;
  168. // Temporarily remove the current declaration name and its associated scopes
  169. // from the stack. Can only be called once the name is finished.
  170. auto Suspend() -> SuspendedName;
  171. // Restore a previously suspended name.
  172. auto Restore(SuspendedName sus) -> void;
  173. // Creates and returns a name context corresponding to declaring an
  174. // unqualified name in the current context. This is suitable for adding to
  175. // name lookup in situations where a qualified name is not permitted, such as
  176. // a pattern binding.
  177. auto MakeUnqualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id)
  178. -> NameContext;
  179. // Applies a Name from the name stack to the top of the declaration name
  180. // stack. This will enter the scope corresponding to the name if the name
  181. // describes an existing scope, such as a namespace or a defined class.
  182. auto ApplyNameQualifier(SemIR::LocId loc_id, SemIR::NameId name_id) -> void;
  183. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  184. auto AddNameToLookup(NameContext name_context, SemIR::InstId target_id)
  185. -> void;
  186. // Adds a name to name lookup, or returns the existing instruction if this
  187. // name has already been declared in this scope.
  188. auto LookupOrAddName(NameContext name_context, SemIR::InstId target_id)
  189. -> SemIR::InstId;
  190. private:
  191. // Returns a name context corresponding to an empty name.
  192. auto MakeEmptyNameContext() -> NameContext;
  193. // Applies a Name from the name stack to given name context.
  194. auto ApplyNameQualifierTo(NameContext& name_context, SemIR::LocId loc_id,
  195. SemIR::NameId name_id, bool is_unqualified) -> void;
  196. // Returns true if the context is in a state where it can resolve qualifiers.
  197. // Updates name_context as needed.
  198. auto TryResolveQualifier(NameContext& name_context, SemIR::LocId loc_id)
  199. -> bool;
  200. // Updates the scope on name_context as needed. This is called after
  201. // resolution is complete, whether for Name or expression. When updating for
  202. // an unqualified name, the resolution is noted without pushing scopes; it's
  203. // instead expected this will become a name conflict.
  204. auto UpdateScopeIfNeeded(NameContext& name_context, bool is_unqualified)
  205. -> void;
  206. // The linked context.
  207. Context* context_;
  208. // Provides nesting for construction.
  209. llvm::SmallVector<NameContext> decl_name_stack_;
  210. };
  211. } // namespace Carbon::Check
  212. #endif // CARBON_TOOLCHAIN_CHECK_DECL_NAME_STACK_H_