decl_name_stack.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 any name collision found, or Invalid.
  84. auto prev_inst_id() -> SemIR::InstId;
  85. // Returns the name_id for a new instruction. This is invalid when the name
  86. // resolved.
  87. auto name_id_for_new_inst() -> SemIR::NameId {
  88. return state == State::Unresolved ? unresolved_name_id
  89. : SemIR::NameId::Invalid;
  90. }
  91. // Returns the enclosing_scope_id for a new instruction. This is invalid
  92. // when the name resolved.
  93. auto enclosing_scope_id_for_new_inst() -> SemIR::NameScopeId {
  94. return state == State::Unresolved ? enclosing_scope_id
  95. : SemIR::NameScopeId::Invalid;
  96. }
  97. // The current scope when this name began. This is the scope that we will
  98. // return to at the end of the declaration.
  99. ScopeIndex initial_scope_index;
  100. State state = State::Empty;
  101. // Whether there have been qualifiers in the name.
  102. bool has_qualifiers = false;
  103. // The scope which qualified names are added to. For unqualified names in
  104. // an unnamed scope, this will be Invalid to indicate the current scope
  105. // should be used.
  106. SemIR::NameScopeId enclosing_scope_id;
  107. // The last location ID used.
  108. SemIR::LocId loc_id = SemIR::LocId::Invalid;
  109. union {
  110. // The ID of a resolved qualifier, including both identifiers and
  111. // expressions. Invalid indicates resolution failed.
  112. SemIR::InstId resolved_inst_id;
  113. // The ID of an unresolved identifier.
  114. SemIR::NameId unresolved_name_id = SemIR::NameId::Invalid;
  115. };
  116. };
  117. // Information about a declaration name that has been temporarily removed from
  118. // the stack and will later be restored. Names can only be suspended once they
  119. // are finished.
  120. struct SuspendedName {
  121. // The declaration name information.
  122. NameContext name_context;
  123. // Suspended scopes. We only preallocate space for two of these, because
  124. // suspended names are usually used for classes and functions with
  125. // unqualified names, which only need at most two scopes -- one scope for
  126. // the parameter and one scope for the entity itself, and we can store quite
  127. // a few of these when processing a large class definition.
  128. llvm::SmallVector<ScopeStack::SuspendedScope, 2> scopes;
  129. };
  130. explicit DeclNameStack(Context* context) : context_(context) {}
  131. // Pushes processing of a new declaration name, which will be used
  132. // contextually, and prepares to enter scopes for that name. To pop this
  133. // state, `FinishName` and `PopScope` must be called, in that order.
  134. auto PushScopeAndStartName() -> void;
  135. // Peeks the current enclosing scope of the name on top of the stack. Note
  136. // that if we're still processing the name qualifiers, this can change before
  137. // the name is completed. Also, if the name up to this point was already
  138. // declared and is a scope, this will be that scope, rather than the scope
  139. // enclosing it.
  140. auto PeekEnclosingScopeId() const -> SemIR::NameScopeId {
  141. return decl_name_stack_.back().enclosing_scope_id;
  142. }
  143. // Peeks the resolution scope index of the name on top of the stack.
  144. auto PeekInitialScopeIndex() const -> ScopeIndex {
  145. return decl_name_stack_.back().initial_scope_index;
  146. }
  147. // Finishes the current declaration name processing, returning the final
  148. // context for adding the name to lookup.
  149. //
  150. // This also pops the final name instruction from the instruction stack,
  151. // which will be applied to the declaration name if appropriate.
  152. auto FinishName() -> NameContext;
  153. // Finishes the current declaration name processing for an `impl`, returning
  154. // the final context for adding the name to lookup.
  155. //
  156. // `impl`s don't actually have names, but want the rest of the name processing
  157. // logic such as building parameter scopes, so are a special case.
  158. auto FinishImplName() -> NameContext;
  159. // Pops the declaration name from the declaration name stack, and pops all
  160. // scopes that were entered as part of handling the declaration name. These
  161. // are the scopes corresponding to name qualifiers in the name, for example
  162. // the `A.B` in `fn A.B.F()`.
  163. //
  164. // This should be called at the end of the declaration.
  165. auto PopScope() -> void;
  166. // Temporarily remove the current declaration name and its associated scopes
  167. // from the stack. Can only be called once the name is finished.
  168. auto Suspend() -> SuspendedName;
  169. // Restore a previously suspended name.
  170. auto Restore(SuspendedName sus) -> void;
  171. // Creates and returns a name context corresponding to declaring an
  172. // unqualified name in the current context. This is suitable for adding to
  173. // name lookup in situations where a qualified name is not permitted, such as
  174. // a pattern binding.
  175. auto MakeUnqualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id)
  176. -> NameContext;
  177. // Applies a Name from the name stack to the top of the declaration name
  178. // stack. This will enter the scope corresponding to the name if the name
  179. // describes an existing scope, such as a namespace or a defined class.
  180. auto ApplyNameQualifier(SemIR::LocId loc_id, SemIR::NameId name_id) -> void;
  181. // Adds a name to name lookup. Assumes duplicates are already handled.
  182. auto AddName(NameContext name_context, SemIR::InstId target_id) -> void;
  183. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  184. auto AddNameOrDiagnoseDuplicate(NameContext name_context,
  185. SemIR::InstId target_id) -> 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_