decl_name_stack.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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, /*is_unqualified=*/true);
  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::FinishImplName() -> NameContext {
  41. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Empty)
  42. << "Impl has a name";
  43. NameContext result = decl_name_stack_.back();
  44. decl_name_stack_.back().state = NameContext::State::Finished;
  45. return result;
  46. }
  47. auto DeclNameStack::PopScope() -> void {
  48. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Finished)
  49. << "Missing call to FinishName before PopScope";
  50. context_->scope_stack().PopTo(decl_name_stack_.back().enclosing_scope);
  51. decl_name_stack_.pop_back();
  52. }
  53. auto DeclNameStack::LookupOrAddName(NameContext name_context,
  54. SemIR::InstId target_id) -> SemIR::InstId {
  55. switch (name_context.state) {
  56. case NameContext::State::Error:
  57. // The name is invalid and a diagnostic has already been emitted.
  58. return SemIR::InstId::Invalid;
  59. case NameContext::State::Empty:
  60. CARBON_FATAL() << "Name is missing, not expected to call AddNameToLookup "
  61. "(but that may change based on error handling).";
  62. case NameContext::State::Resolved:
  63. case NameContext::State::ResolvedNonScope:
  64. return name_context.resolved_inst_id;
  65. case NameContext::State::Unresolved:
  66. if (!name_context.target_scope_id.is_valid()) {
  67. context_->AddNameToLookup(name_context.unresolved_name_id, target_id);
  68. } else {
  69. auto& name_scope =
  70. context_->name_scopes().Get(name_context.target_scope_id);
  71. if (name_context.has_qualifiers) {
  72. auto inst = context_->insts().Get(name_scope.inst_id);
  73. if (!inst.Is<SemIR::Namespace>()) {
  74. // TODO: Point at the declaration for the scoped entity.
  75. CARBON_DIAGNOSTIC(
  76. QualifiedDeclOutsideScopeEntity, Error,
  77. "Out-of-line declaration requires a declaration in "
  78. "scoped entity.");
  79. context_->emitter().Emit(name_context.parse_node,
  80. QualifiedDeclOutsideScopeEntity);
  81. }
  82. }
  83. // Exports are only tracked when the declaration is at the file-level
  84. // scope. Otherwise, it's in some other entity, such as a class.
  85. if (name_context.enclosing_scope == ScopeIndex::Package) {
  86. context_->AddExport(target_id);
  87. }
  88. auto [_, success] = name_scope.names.insert(
  89. {name_context.unresolved_name_id, target_id});
  90. CARBON_CHECK(success)
  91. << "Duplicate names should have been resolved previously: "
  92. << name_context.unresolved_name_id << " in "
  93. << name_context.target_scope_id;
  94. }
  95. return SemIR::InstId::Invalid;
  96. case NameContext::State::Finished:
  97. CARBON_FATAL() << "Finished state should only be used internally";
  98. }
  99. }
  100. auto DeclNameStack::AddNameToLookup(NameContext name_context,
  101. SemIR::InstId target_id) -> void {
  102. auto existing_inst_id = LookupOrAddName(name_context, target_id);
  103. if (existing_inst_id.is_valid()) {
  104. context_->DiagnoseDuplicateName(target_id, existing_inst_id);
  105. }
  106. }
  107. auto DeclNameStack::ApplyNameQualifier(Parse::NodeId parse_node,
  108. SemIR::NameId name_id) -> void {
  109. ApplyNameQualifierTo(decl_name_stack_.back(), parse_node, name_id,
  110. /*is_unqualified=*/false);
  111. }
  112. auto DeclNameStack::ApplyNameQualifierTo(NameContext& name_context,
  113. Parse::NodeId parse_node,
  114. SemIR::NameId name_id,
  115. bool is_unqualified) -> void {
  116. if (TryResolveQualifier(name_context, parse_node)) {
  117. // For identifier nodes, we need to perform a lookup on the identifier.
  118. auto resolved_inst_id = context_->LookupNameInDecl(
  119. name_context.parse_node, name_id, name_context.target_scope_id);
  120. if (!resolved_inst_id.is_valid()) {
  121. // Invalid indicates an unresolved name. Store it and return.
  122. name_context.state = NameContext::State::Unresolved;
  123. name_context.unresolved_name_id = name_id;
  124. return;
  125. } else {
  126. // Store the resolved instruction and continue for the target scope
  127. // update.
  128. name_context.resolved_inst_id = resolved_inst_id;
  129. }
  130. UpdateScopeIfNeeded(name_context, is_unqualified);
  131. }
  132. }
  133. // Push a scope corresponding to a name qualifier. For example, for
  134. //
  135. // fn Class(T:! type).F(n: i32)
  136. //
  137. // we will push the scope for `Class(T:! type)` between the scope containing the
  138. // declaration of `T` and the scope containing the declaration of `n`.
  139. static auto PushNameQualifierScope(Context& context,
  140. SemIR::InstId scope_inst_id,
  141. SemIR::NameScopeId scope_id,
  142. bool has_error = false) -> void {
  143. // If the qualifier has no parameters, we don't need to keep around a
  144. // parameter scope.
  145. context.scope_stack().PopIfEmpty();
  146. context.scope_stack().Push(scope_inst_id, scope_id, has_error);
  147. // Enter a parameter scope in case the qualified name itself has parameters.
  148. context.scope_stack().Push();
  149. }
  150. auto DeclNameStack::UpdateScopeIfNeeded(NameContext& name_context,
  151. bool is_unqualified) -> void {
  152. // This will only be reached for resolved instructions. We update the target
  153. // scope based on the resolved type.
  154. auto resolved_inst = context_->insts().Get(name_context.resolved_inst_id);
  155. switch (resolved_inst.kind()) {
  156. case SemIR::ClassDecl::Kind: {
  157. const auto& class_info = context_->classes().Get(
  158. resolved_inst.As<SemIR::ClassDecl>().class_id);
  159. if (class_info.is_defined()) {
  160. name_context.state = NameContext::State::Resolved;
  161. name_context.target_scope_id = class_info.scope_id;
  162. if (!is_unqualified) {
  163. PushNameQualifierScope(*context_, name_context.resolved_inst_id,
  164. class_info.scope_id);
  165. }
  166. } else {
  167. name_context.state = NameContext::State::ResolvedNonScope;
  168. }
  169. break;
  170. }
  171. case SemIR::InterfaceDecl::Kind: {
  172. const auto& interface_info = context_->interfaces().Get(
  173. resolved_inst.As<SemIR::InterfaceDecl>().interface_id);
  174. if (interface_info.is_defined()) {
  175. name_context.state = NameContext::State::Resolved;
  176. name_context.target_scope_id = interface_info.scope_id;
  177. if (!is_unqualified) {
  178. PushNameQualifierScope(*context_, name_context.resolved_inst_id,
  179. interface_info.scope_id);
  180. }
  181. } else {
  182. name_context.state = NameContext::State::ResolvedNonScope;
  183. }
  184. break;
  185. }
  186. case SemIR::Namespace::Kind: {
  187. auto scope_id = resolved_inst.As<SemIR::Namespace>().name_scope_id;
  188. name_context.state = NameContext::State::Resolved;
  189. name_context.target_scope_id = scope_id;
  190. if (!is_unqualified) {
  191. PushNameQualifierScope(*context_, name_context.resolved_inst_id,
  192. scope_id,
  193. context_->name_scopes().Get(scope_id).has_error);
  194. }
  195. break;
  196. }
  197. default:
  198. name_context.state = NameContext::State::ResolvedNonScope;
  199. break;
  200. }
  201. }
  202. auto DeclNameStack::TryResolveQualifier(NameContext& name_context,
  203. Parse::NodeId parse_node) -> bool {
  204. // Update has_qualifiers based on the state before any possible changes. If
  205. // this is the first qualifier, it may just be the name.
  206. name_context.has_qualifiers = name_context.state != NameContext::State::Empty;
  207. switch (name_context.state) {
  208. case NameContext::State::Error:
  209. // Already in an error state, so return without examining.
  210. return false;
  211. case NameContext::State::Unresolved:
  212. // Because more qualifiers were found, we diagnose that the earlier
  213. // qualifier failed to resolve.
  214. name_context.state = NameContext::State::Error;
  215. context_->DiagnoseNameNotFound(name_context.parse_node,
  216. name_context.unresolved_name_id);
  217. return false;
  218. case NameContext::State::ResolvedNonScope: {
  219. // Because more qualifiers were found, we diagnose that the earlier
  220. // qualifier didn't resolve to a scoped entity.
  221. if (auto class_decl = context_->insts().TryGetAs<SemIR::ClassDecl>(
  222. name_context.resolved_inst_id)) {
  223. CARBON_DIAGNOSTIC(QualifiedDeclInIncompleteClassScope, Error,
  224. "Cannot declare a member of incomplete class `{0}`.",
  225. SemIR::TypeId);
  226. auto builder = context_->emitter().Build(
  227. name_context.parse_node, QualifiedDeclInIncompleteClassScope,
  228. context_->classes().Get(class_decl->class_id).self_type_id);
  229. context_->NoteIncompleteClass(class_decl->class_id, builder);
  230. builder.Emit();
  231. } else if (auto interface_decl =
  232. context_->insts().TryGetAs<SemIR::InterfaceDecl>(
  233. name_context.resolved_inst_id)) {
  234. CARBON_DIAGNOSTIC(
  235. QualifiedDeclInUndefinedInterfaceScope, Error,
  236. "Cannot declare a member of undefined interface `{0}`.",
  237. std::string);
  238. auto builder = context_->emitter().Build(
  239. name_context.parse_node, QualifiedDeclInUndefinedInterfaceScope,
  240. context_->sem_ir().StringifyTypeExpr(
  241. context_->sem_ir()
  242. .constant_values()
  243. .Get(name_context.resolved_inst_id)
  244. .inst_id()));
  245. context_->NoteUndefinedInterface(interface_decl->interface_id, builder);
  246. builder.Emit();
  247. } else {
  248. CARBON_DIAGNOSTIC(QualifiedNameInNonScope, Error,
  249. "Name qualifiers are only allowed for entities that "
  250. "provide a scope.");
  251. CARBON_DIAGNOSTIC(QualifiedNameNonScopeEntity, Note,
  252. "Non-scope entity referenced here.");
  253. context_->emitter()
  254. .Build(parse_node, QualifiedNameInNonScope)
  255. .Note(name_context.parse_node, QualifiedNameNonScopeEntity)
  256. .Emit();
  257. }
  258. name_context.state = NameContext::State::Error;
  259. return false;
  260. }
  261. case NameContext::State::Empty:
  262. case NameContext::State::Resolved: {
  263. name_context.parse_node = parse_node;
  264. return true;
  265. }
  266. case NameContext::State::Finished:
  267. CARBON_FATAL() << "Added a qualifier after calling FinishName";
  268. }
  269. }
  270. } // namespace Carbon::Check