decl_name_stack.cpp 14 KB

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