decl_name_stack.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 node_id,
  14. SemIR::NameId name_id) -> NameContext {
  15. NameContext context = MakeEmptyNameContext();
  16. ApplyNameQualifierTo(context, node_id, 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. .PopAndDiscardSoloNodeIdIf<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 [node_id, name_id] = context_->node_stack().PopNameWithNodeId();
  34. ApplyNameQualifier(node_id, 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.node_id,
  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 node_id,
  108. SemIR::NameId name_id) -> void {
  109. ApplyNameQualifierTo(decl_name_stack_.back(), node_id, name_id,
  110. /*is_unqualified=*/false);
  111. }
  112. auto DeclNameStack::ApplyNameQualifierTo(NameContext& name_context,
  113. Parse::NodeId node_id,
  114. SemIR::NameId name_id,
  115. bool is_unqualified) -> void {
  116. if (TryResolveQualifier(name_context, node_id)) {
  117. // For identifier nodes, we need to perform a lookup on the identifier.
  118. auto resolved_inst_id = context_->LookupNameInDecl(
  119. name_context.node_id, 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. auto& scope = context_->name_scopes().Get(scope_id);
  191. if (scope.is_closed_import) {
  192. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackage, Error,
  193. "Imported packages cannot be used for declarations.");
  194. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackageSource, Note,
  195. "Package imported here.");
  196. context_->emitter()
  197. .Build(name_context.node_id, QualifiedDeclOutsidePackage)
  198. .Note(scope.inst_id, QualifiedDeclOutsidePackageSource)
  199. .Emit();
  200. // Only error once per package.
  201. scope.is_closed_import = false;
  202. }
  203. if (!is_unqualified) {
  204. PushNameQualifierScope(*context_, name_context.resolved_inst_id,
  205. scope_id,
  206. context_->name_scopes().Get(scope_id).has_error);
  207. }
  208. break;
  209. }
  210. default:
  211. name_context.state = NameContext::State::ResolvedNonScope;
  212. break;
  213. }
  214. }
  215. auto DeclNameStack::TryResolveQualifier(NameContext& name_context,
  216. Parse::NodeId node_id) -> bool {
  217. // Update has_qualifiers based on the state before any possible changes. If
  218. // this is the first qualifier, it may just be the name.
  219. name_context.has_qualifiers = name_context.state != NameContext::State::Empty;
  220. switch (name_context.state) {
  221. case NameContext::State::Error:
  222. // Already in an error state, so return without examining.
  223. return false;
  224. case NameContext::State::Unresolved:
  225. // Because more qualifiers were found, we diagnose that the earlier
  226. // qualifier failed to resolve.
  227. name_context.state = NameContext::State::Error;
  228. context_->DiagnoseNameNotFound(name_context.node_id,
  229. name_context.unresolved_name_id);
  230. return false;
  231. case NameContext::State::ResolvedNonScope: {
  232. // Because more qualifiers were found, we diagnose that the earlier
  233. // qualifier didn't resolve to a scoped entity.
  234. if (auto class_decl = context_->insts().TryGetAs<SemIR::ClassDecl>(
  235. name_context.resolved_inst_id)) {
  236. CARBON_DIAGNOSTIC(QualifiedDeclInIncompleteClassScope, Error,
  237. "Cannot declare a member of incomplete class `{0}`.",
  238. SemIR::TypeId);
  239. auto builder = context_->emitter().Build(
  240. name_context.node_id, QualifiedDeclInIncompleteClassScope,
  241. context_->classes().Get(class_decl->class_id).self_type_id);
  242. context_->NoteIncompleteClass(class_decl->class_id, builder);
  243. builder.Emit();
  244. } else if (auto interface_decl =
  245. context_->insts().TryGetAs<SemIR::InterfaceDecl>(
  246. name_context.resolved_inst_id)) {
  247. CARBON_DIAGNOSTIC(
  248. QualifiedDeclInUndefinedInterfaceScope, Error,
  249. "Cannot declare a member of undefined interface `{0}`.",
  250. std::string);
  251. auto builder = context_->emitter().Build(
  252. name_context.node_id, QualifiedDeclInUndefinedInterfaceScope,
  253. context_->sem_ir().StringifyTypeExpr(
  254. context_->sem_ir()
  255. .constant_values()
  256. .Get(name_context.resolved_inst_id)
  257. .inst_id()));
  258. context_->NoteUndefinedInterface(interface_decl->interface_id, builder);
  259. builder.Emit();
  260. } else {
  261. CARBON_DIAGNOSTIC(QualifiedNameInNonScope, Error,
  262. "Name qualifiers are only allowed for entities that "
  263. "provide a scope.");
  264. CARBON_DIAGNOSTIC(QualifiedNameNonScopeEntity, Note,
  265. "Non-scope entity referenced here.");
  266. context_->emitter()
  267. .Build(node_id, QualifiedNameInNonScope)
  268. .Note(name_context.node_id, QualifiedNameNonScopeEntity)
  269. .Emit();
  270. }
  271. name_context.state = NameContext::State::Error;
  272. return false;
  273. }
  274. case NameContext::State::Empty:
  275. case NameContext::State::Resolved: {
  276. name_context.node_id = node_id;
  277. return true;
  278. }
  279. case NameContext::State::Finished:
  280. CARBON_FATAL() << "Added a qualifier after calling FinishName";
  281. }
  282. }
  283. } // namespace Carbon::Check