decl_name_stack.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. #include "toolchain/check/decl_name_stack.h"
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/sem_ir/ids.h"
  7. namespace Carbon::Check {
  8. auto DeclNameStack::MakeEmptyNameContext() -> NameContext {
  9. return NameContext{
  10. .enclosing_scope = context_->scope_stack().PeekIndex(),
  11. .target_scope_id = context_->scope_stack().PeekNameScopeId()};
  12. }
  13. auto DeclNameStack::MakeUnqualifiedName(Parse::NodeId parse_node,
  14. SemIR::NameId name_id) -> NameContext {
  15. NameContext context = MakeEmptyNameContext();
  16. ApplyNameQualifierTo(context, parse_node, name_id);
  17. return context;
  18. }
  19. auto DeclNameStack::PushScopeAndStartName() -> void {
  20. decl_name_stack_.push_back(MakeEmptyNameContext());
  21. // Create a scope for any parameters introduced in this name.
  22. context_->scope_stack().Push();
  23. }
  24. auto DeclNameStack::FinishName() -> NameContext {
  25. CARBON_CHECK(decl_name_stack_.back().state != NameContext::State::Finished)
  26. << "Finished name twice";
  27. if (context_->node_stack()
  28. .PopAndDiscardSoloParseNodeIf<Parse::NodeKind::QualifiedName>()) {
  29. // Any parts from a QualifiedName will already have been processed
  30. // into the name.
  31. } else {
  32. // The name had no qualifiers, so we need to process the node now.
  33. auto [parse_node, name_id] = context_->node_stack().PopNameWithParseNode();
  34. ApplyNameQualifier(parse_node, name_id);
  35. }
  36. NameContext result = decl_name_stack_.back();
  37. decl_name_stack_.back().state = NameContext::State::Finished;
  38. return result;
  39. }
  40. auto DeclNameStack::PopScope() -> void {
  41. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Finished)
  42. << "Missing call to FinishName before PopScope";
  43. context_->scope_stack().PopTo(decl_name_stack_.back().enclosing_scope);
  44. decl_name_stack_.pop_back();
  45. }
  46. auto DeclNameStack::LookupOrAddName(NameContext name_context,
  47. SemIR::InstId target_id) -> SemIR::InstId {
  48. switch (name_context.state) {
  49. case NameContext::State::Error:
  50. // The name is invalid and a diagnostic has already been emitted.
  51. return SemIR::InstId::Invalid;
  52. case NameContext::State::Empty:
  53. CARBON_FATAL() << "Name is missing, not expected to call AddNameToLookup "
  54. "(but that may change based on error handling).";
  55. case NameContext::State::Resolved:
  56. case NameContext::State::ResolvedNonScope:
  57. return name_context.resolved_inst_id;
  58. case NameContext::State::Unresolved:
  59. if (!name_context.target_scope_id.is_valid()) {
  60. context_->AddNameToLookup(name_context.unresolved_name_id, target_id);
  61. } else {
  62. auto& name_scope =
  63. context_->name_scopes().Get(name_context.target_scope_id);
  64. if (name_context.has_qualifiers) {
  65. auto inst = context_->insts().Get(name_scope.inst_id);
  66. if (!inst.Is<SemIR::Namespace>()) {
  67. // TODO: Point at the declaration for the scoped entity.
  68. CARBON_DIAGNOSTIC(
  69. QualifiedDeclOutsideScopeEntity, Error,
  70. "Out-of-line declaration requires a declaration in "
  71. "scoped entity.");
  72. context_->emitter().Emit(name_context.parse_node,
  73. QualifiedDeclOutsideScopeEntity);
  74. }
  75. }
  76. // Exports are only tracked when the declaration is at the file-level
  77. // scope. Otherwise, it's in some other entity, such as a class.
  78. if (name_context.enclosing_scope == ScopeIndex::Package) {
  79. context_->AddExport(target_id);
  80. }
  81. auto [_, success] = name_scope.names.insert(
  82. {name_context.unresolved_name_id, target_id});
  83. CARBON_CHECK(success)
  84. << "Duplicate names should have been resolved previously: "
  85. << name_context.unresolved_name_id << " in "
  86. << name_context.target_scope_id;
  87. }
  88. return SemIR::InstId::Invalid;
  89. case NameContext::State::Finished:
  90. CARBON_FATAL() << "Finished state should only be used internally";
  91. }
  92. }
  93. auto DeclNameStack::AddNameToLookup(NameContext name_context,
  94. SemIR::InstId target_id) -> void {
  95. auto existing_inst_id = LookupOrAddName(name_context, target_id);
  96. if (existing_inst_id.is_valid()) {
  97. context_->DiagnoseDuplicateName(target_id, existing_inst_id);
  98. }
  99. }
  100. auto DeclNameStack::ApplyNameQualifier(Parse::NodeId parse_node,
  101. SemIR::NameId name_id) -> void {
  102. ApplyNameQualifierTo(decl_name_stack_.back(), parse_node, name_id);
  103. }
  104. auto DeclNameStack::ApplyNameQualifierTo(NameContext& name_context,
  105. Parse::NodeId parse_node,
  106. SemIR::NameId name_id) -> void {
  107. if (TryResolveQualifier(name_context, parse_node)) {
  108. // For identifier nodes, we need to perform a lookup on the identifier.
  109. auto resolved_inst_id = context_->LookupNameInDecl(
  110. name_context.parse_node, name_id, name_context.target_scope_id);
  111. if (!resolved_inst_id.is_valid()) {
  112. // Invalid indicates an unresolved name. Store it and return.
  113. name_context.state = NameContext::State::Unresolved;
  114. name_context.unresolved_name_id = name_id;
  115. return;
  116. } else {
  117. // Store the resolved instruction and continue for the target scope
  118. // update.
  119. name_context.resolved_inst_id = resolved_inst_id;
  120. }
  121. UpdateScopeIfNeeded(name_context);
  122. }
  123. }
  124. // Push a scope corresponding to a name qualifier. For example, for
  125. //
  126. // fn Class(T:! type).F(n: i32)
  127. //
  128. // we will push the scope for `Class(T:! type)` between the scope containing the
  129. // declaration of `T` and the scope containing the declaration of `n`.
  130. static auto PushNameQualifierScope(Context& context,
  131. SemIR::InstId scope_inst_id,
  132. SemIR::NameScopeId scope_id,
  133. bool has_error = false) -> void {
  134. // If the qualifier has no parameters, we don't need to keep around a
  135. // parameter scope.
  136. context.scope_stack().PopIfEmpty();
  137. context.scope_stack().Push(scope_inst_id, scope_id, has_error);
  138. // Enter a parameter scope in case the qualified name itself has parameters.
  139. context.scope_stack().Push();
  140. }
  141. auto DeclNameStack::UpdateScopeIfNeeded(NameContext& name_context) -> void {
  142. // This will only be reached for resolved instructions. We update the target
  143. // scope based on the resolved type.
  144. auto resolved_inst = context_->insts().Get(name_context.resolved_inst_id);
  145. switch (resolved_inst.kind()) {
  146. case SemIR::ClassDecl::Kind: {
  147. const auto& class_info = context_->classes().Get(
  148. resolved_inst.As<SemIR::ClassDecl>().class_id);
  149. if (class_info.is_defined()) {
  150. name_context.state = NameContext::State::Resolved;
  151. name_context.target_scope_id = class_info.scope_id;
  152. PushNameQualifierScope(*context_, name_context.resolved_inst_id,
  153. class_info.scope_id);
  154. } else {
  155. name_context.state = NameContext::State::ResolvedNonScope;
  156. }
  157. break;
  158. }
  159. case SemIR::Namespace::Kind: {
  160. auto scope_id = resolved_inst.As<SemIR::Namespace>().name_scope_id;
  161. name_context.state = NameContext::State::Resolved;
  162. name_context.target_scope_id = scope_id;
  163. PushNameQualifierScope(*context_, name_context.resolved_inst_id, scope_id,
  164. context_->name_scopes().Get(scope_id).has_error);
  165. break;
  166. }
  167. default:
  168. name_context.state = NameContext::State::ResolvedNonScope;
  169. break;
  170. }
  171. }
  172. auto DeclNameStack::TryResolveQualifier(NameContext& name_context,
  173. Parse::NodeId parse_node) -> bool {
  174. // Update has_qualifiers based on the state before any possible changes. If
  175. // this is the first qualifier, it may just be the name.
  176. name_context.has_qualifiers = name_context.state != NameContext::State::Empty;
  177. switch (name_context.state) {
  178. case NameContext::State::Error:
  179. // Already in an error state, so return without examining.
  180. return false;
  181. case NameContext::State::Unresolved:
  182. // Because more qualifiers were found, we diagnose that the earlier
  183. // qualifier failed to resolve.
  184. name_context.state = NameContext::State::Error;
  185. context_->DiagnoseNameNotFound(name_context.parse_node,
  186. name_context.unresolved_name_id);
  187. return false;
  188. case NameContext::State::ResolvedNonScope: {
  189. // Because more qualifiers were found, we diagnose that the earlier
  190. // qualifier didn't resolve to a scoped entity.
  191. if (auto class_decl = context_->insts()
  192. .Get(name_context.resolved_inst_id)
  193. .TryAs<SemIR::ClassDecl>()) {
  194. CARBON_DIAGNOSTIC(QualifiedDeclInIncompleteClassScope, Error,
  195. "Cannot declare a member of incomplete class `{0}`.",
  196. std::string);
  197. auto builder = context_->emitter().Build(
  198. name_context.parse_node, QualifiedDeclInIncompleteClassScope,
  199. context_->sem_ir().StringifyType(
  200. context_->classes().Get(class_decl->class_id).self_type_id));
  201. context_->NoteIncompleteClass(class_decl->class_id, builder);
  202. builder.Emit();
  203. } else {
  204. CARBON_DIAGNOSTIC(QualifiedNameInNonScope, Error,
  205. "Name qualifiers are only allowed for entities that "
  206. "provide a scope.");
  207. CARBON_DIAGNOSTIC(QualifiedNameNonScopeEntity, Note,
  208. "Non-scope entity referenced here.");
  209. context_->emitter()
  210. .Build(parse_node, QualifiedNameInNonScope)
  211. .Note(name_context.parse_node, QualifiedNameNonScopeEntity)
  212. .Emit();
  213. }
  214. name_context.state = NameContext::State::Error;
  215. return false;
  216. }
  217. case NameContext::State::Empty:
  218. case NameContext::State::Resolved: {
  219. name_context.parse_node = parse_node;
  220. return true;
  221. }
  222. case NameContext::State::Finished:
  223. CARBON_FATAL() << "Added a qualifier after calling FinishName";
  224. }
  225. }
  226. } // namespace Carbon::Check