decl_name_stack.cpp 10 KB

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