declaration_name_stack.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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/declaration_name_stack.h"
  5. #include "toolchain/check/context.h"
  6. namespace Carbon::Check {
  7. auto DeclarationNameStack::MakeEmptyNameContext() -> NameContext {
  8. return NameContext{.target_scope_id = context_->current_scope_id()};
  9. }
  10. auto DeclarationNameStack::MakeUnqualifiedName(Parse::Node parse_node,
  11. IdentifierId name_id)
  12. -> NameContext {
  13. NameContext context = MakeEmptyNameContext();
  14. ApplyNameQualifierTo(context, parse_node, name_id);
  15. return context;
  16. }
  17. auto DeclarationNameStack::Push() -> void {
  18. declaration_name_stack_.push_back(MakeEmptyNameContext());
  19. }
  20. auto DeclarationNameStack::Pop() -> NameContext {
  21. if (context_->parse_tree().node_kind(
  22. context_->node_stack().PeekParseNode()) ==
  23. Parse::NodeKind::QualifiedDeclaration) {
  24. // Any parts from a QualifiedDeclaration will already have been processed
  25. // into the name.
  26. context_->node_stack()
  27. .PopAndDiscardSoloParseNode<Parse::NodeKind::QualifiedDeclaration>();
  28. } else {
  29. // The name had no qualifiers, so we need to process the node now.
  30. auto [parse_node, name_id] =
  31. context_->node_stack().PopWithParseNode<Parse::NodeKind::Name>();
  32. ApplyNameQualifier(parse_node, name_id);
  33. }
  34. return declaration_name_stack_.pop_back_val();
  35. }
  36. auto DeclarationNameStack::LookupOrAddName(NameContext name_context,
  37. SemIR::InstId target_id)
  38. -> SemIR::InstId {
  39. switch (name_context.state) {
  40. case NameContext::State::Error:
  41. // The name is invalid and a diagnostic has already been emitted.
  42. return SemIR::InstId::Invalid;
  43. case NameContext::State::Empty:
  44. CARBON_FATAL() << "Name is missing, not expected to call AddNameToLookup "
  45. "(but that may change based on error handling).";
  46. case NameContext::State::Resolved:
  47. case NameContext::State::ResolvedNonScope:
  48. return name_context.resolved_inst_id;
  49. case NameContext::State::Unresolved:
  50. if (name_context.target_scope_id == SemIR::NameScopeId::Invalid) {
  51. context_->AddNameToLookup(name_context.parse_node,
  52. name_context.unresolved_name_id, target_id);
  53. } else {
  54. // TODO: Reject unless the scope is a namespace scope or the name is
  55. // unqualified.
  56. bool success = context_->name_scopes().AddEntry(
  57. name_context.target_scope_id, name_context.unresolved_name_id,
  58. target_id);
  59. CARBON_CHECK(success)
  60. << "Duplicate names should have been resolved previously: "
  61. << name_context.unresolved_name_id << " in "
  62. << name_context.target_scope_id;
  63. }
  64. return SemIR::InstId::Invalid;
  65. }
  66. }
  67. auto DeclarationNameStack::AddNameToLookup(NameContext name_context,
  68. SemIR::InstId target_id) -> void {
  69. auto existing_inst_id = LookupOrAddName(name_context, target_id);
  70. if (existing_inst_id.is_valid()) {
  71. context_->DiagnoseDuplicateName(name_context.parse_node, existing_inst_id);
  72. }
  73. }
  74. auto DeclarationNameStack::ApplyNameQualifier(Parse::Node parse_node,
  75. IdentifierId name_id) -> void {
  76. ApplyNameQualifierTo(declaration_name_stack_.back(), parse_node, name_id);
  77. }
  78. auto DeclarationNameStack::ApplyNameQualifierTo(NameContext& name_context,
  79. Parse::Node parse_node,
  80. IdentifierId name_id) -> void {
  81. if (CanResolveQualifier(name_context, parse_node)) {
  82. // For identifier nodes, we need to perform a lookup on the identifier.
  83. // This means the input instruction name_id is actually a string ID.
  84. //
  85. // TODO: This doesn't perform the right kind of lookup. We will find names
  86. // from enclosing lexical scopes here, in the case where `target_scope_id`
  87. // is invalid.
  88. auto resolved_inst_id = context_->LookupName(
  89. name_context.parse_node, name_id, name_context.target_scope_id,
  90. /*print_diagnostics=*/false);
  91. if (resolved_inst_id == SemIR::InstId::BuiltinError) {
  92. // Invalid indicates an unresolved instruction. Store it and return.
  93. name_context.state = NameContext::State::Unresolved;
  94. name_context.unresolved_name_id = name_id;
  95. return;
  96. } else {
  97. // Store the resolved instruction and continue for the target scope
  98. // update.
  99. name_context.resolved_inst_id = resolved_inst_id;
  100. }
  101. UpdateScopeIfNeeded(name_context);
  102. }
  103. }
  104. auto DeclarationNameStack::UpdateScopeIfNeeded(NameContext& name_context)
  105. -> void {
  106. // This will only be reached for resolved instructions. We update the target
  107. // scope based on the resolved type.
  108. auto resolved_inst = context_->insts().Get(name_context.resolved_inst_id);
  109. switch (resolved_inst.kind()) {
  110. case SemIR::ClassDeclaration::Kind: {
  111. const auto& class_info = context_->classes().Get(
  112. resolved_inst.As<SemIR::ClassDeclaration>().class_id);
  113. if (class_info.is_defined()) {
  114. name_context.state = NameContext::State::Resolved;
  115. name_context.target_scope_id = class_info.scope_id;
  116. } else {
  117. name_context.state = NameContext::State::ResolvedNonScope;
  118. }
  119. break;
  120. }
  121. case SemIR::Namespace::Kind:
  122. name_context.state = NameContext::State::Resolved;
  123. name_context.target_scope_id =
  124. resolved_inst.As<SemIR::Namespace>().name_scope_id;
  125. break;
  126. default:
  127. name_context.state = NameContext::State::ResolvedNonScope;
  128. break;
  129. }
  130. }
  131. auto DeclarationNameStack::CanResolveQualifier(NameContext& name_context,
  132. Parse::Node parse_node) -> bool {
  133. switch (name_context.state) {
  134. case NameContext::State::Error:
  135. // Already in an error state, so return without examining.
  136. return false;
  137. case NameContext::State::Unresolved:
  138. // Because more qualifiers were found, we diagnose that the earlier
  139. // qualifier failed to resolve.
  140. name_context.state = NameContext::State::Error;
  141. context_->DiagnoseNameNotFound(name_context.parse_node,
  142. name_context.unresolved_name_id);
  143. return false;
  144. case NameContext::State::ResolvedNonScope: {
  145. // Because more qualifiers were found, we diagnose that the earlier
  146. // qualifier didn't resolve to a scoped entity.
  147. if (auto class_decl = context_->insts()
  148. .Get(name_context.resolved_inst_id)
  149. .TryAs<SemIR::ClassDeclaration>()) {
  150. CARBON_DIAGNOSTIC(QualifiedDeclarationInIncompleteClassScope, Error,
  151. "Cannot declare a member of incomplete class `{0}`.",
  152. std::string);
  153. auto builder = context_->emitter().Build(
  154. name_context.parse_node, QualifiedDeclarationInIncompleteClassScope,
  155. context_->sem_ir().StringifyType(
  156. context_->classes().Get(class_decl->class_id).self_type_id,
  157. true));
  158. context_->NoteIncompleteClass(class_decl->class_id, builder);
  159. builder.Emit();
  160. } else {
  161. CARBON_DIAGNOSTIC(
  162. QualifiedDeclarationInNonScope, Error,
  163. "Declaration qualifiers are only allowed for entities "
  164. "that provide a scope.");
  165. CARBON_DIAGNOSTIC(QualifiedDeclarationNonScopeEntity, Note,
  166. "Non-scope entity referenced here.");
  167. context_->emitter()
  168. .Build(parse_node, QualifiedDeclarationInNonScope)
  169. .Note(name_context.parse_node, QualifiedDeclarationNonScopeEntity)
  170. .Emit();
  171. }
  172. name_context.state = NameContext::State::Error;
  173. return false;
  174. }
  175. case NameContext::State::Empty:
  176. case NameContext::State::Resolved: {
  177. name_context.parse_node = parse_node;
  178. return true;
  179. }
  180. }
  181. }
  182. } // namespace Carbon::Check