decl_name_stack.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/diagnostic_helpers.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/name_component.h"
  12. #include "toolchain/check/name_lookup.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/name_scope.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. auto DeclNameStack::NameContext::prev_inst_id() const -> SemIR::InstId {
  20. switch (state) {
  21. case NameContext::State::Error:
  22. // The name is malformed and a diagnostic has already been emitted.
  23. return SemIR::InstId::None;
  24. case NameContext::State::Empty:
  25. CARBON_FATAL(
  26. "Name is missing, not expected to call existing_inst_id (but that "
  27. "may change based on error handling).");
  28. case NameContext::State::Resolved:
  29. return resolved_inst_id;
  30. case NameContext::State::Unresolved:
  31. return SemIR::InstId::None;
  32. case NameContext::State::Poisoned:
  33. CARBON_FATAL("Poisoned state should not call prev_inst_id()");
  34. case NameContext::State::Finished:
  35. CARBON_FATAL("Finished state should only be used internally");
  36. }
  37. }
  38. auto DeclNameStack::MakeEmptyNameContext() -> NameContext {
  39. return NameContext{
  40. .initial_scope_index = context_->scope_stack().PeekIndex(),
  41. .parent_scope_id = context_->scope_stack().PeekNameScopeId()};
  42. }
  43. auto DeclNameStack::MakeUnqualifiedName(SemIR::LocId loc_id,
  44. SemIR::NameId name_id) -> NameContext {
  45. NameContext context = MakeEmptyNameContext();
  46. ApplyAndLookupName(context, loc_id, name_id);
  47. return context;
  48. }
  49. auto DeclNameStack::PushScopeAndStartName() -> void {
  50. decl_name_stack_.push_back(MakeEmptyNameContext());
  51. // Create a scope for any parameters introduced in this name.
  52. context_->scope_stack().PushForDeclName();
  53. }
  54. auto DeclNameStack::FinishName(const NameComponent& name) -> NameContext {
  55. CARBON_CHECK(decl_name_stack_.back().state != NameContext::State::Finished,
  56. "Finished name twice");
  57. ApplyAndLookupName(decl_name_stack_.back(), name.name_loc_id, name.name_id);
  58. NameContext result = decl_name_stack_.back();
  59. decl_name_stack_.back().state = NameContext::State::Finished;
  60. return result;
  61. }
  62. auto DeclNameStack::FinishImplName() -> NameContext {
  63. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Empty,
  64. "Impl has a name");
  65. NameContext result = decl_name_stack_.back();
  66. decl_name_stack_.back().state = NameContext::State::Finished;
  67. return result;
  68. }
  69. auto DeclNameStack::PopScope() -> void {
  70. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Finished,
  71. "Missing call to FinishName before PopScope");
  72. context_->scope_stack().PopTo(decl_name_stack_.back().initial_scope_index);
  73. decl_name_stack_.pop_back();
  74. }
  75. auto DeclNameStack::Suspend() -> SuspendedName {
  76. CARBON_CHECK(decl_name_stack_.back().state == NameContext::State::Finished,
  77. "Missing call to FinishName before Suspend");
  78. SuspendedName result = {.name_context = decl_name_stack_.pop_back_val(),
  79. .scopes = {}};
  80. auto scope_index = result.name_context.initial_scope_index;
  81. auto& scope_stack = context_->scope_stack();
  82. while (scope_stack.PeekIndex() > scope_index) {
  83. result.scopes.push_back(scope_stack.Suspend());
  84. }
  85. CARBON_CHECK(scope_stack.PeekIndex() == scope_index,
  86. "Scope index {0} does not enclose the current scope {1}",
  87. scope_index, scope_stack.PeekIndex());
  88. return result;
  89. }
  90. auto DeclNameStack::Restore(SuspendedName&& sus) -> void {
  91. // The parent state must be the same when a name is restored.
  92. CARBON_CHECK(context_->scope_stack().PeekIndex() ==
  93. sus.name_context.initial_scope_index,
  94. "Name restored at the wrong position in the name stack.");
  95. // clang-tidy warns that the `std::move` below has no effect. While that's
  96. // true, this `move` defends against `NameContext` growing more state later.
  97. // NOLINTNEXTLINE(performance-move-const-arg)
  98. decl_name_stack_.push_back(std::move(sus.name_context));
  99. for (auto& suspended_scope : llvm::reverse(sus.scopes)) {
  100. // Reattempt to resolve the definition of the specific. The generic might
  101. // have been defined after we suspended this scope.
  102. if (suspended_scope.entry.specific_id.has_value()) {
  103. ResolveSpecificDefinition(*context_, sus.name_context.loc_id,
  104. suspended_scope.entry.specific_id);
  105. }
  106. context_->scope_stack().Restore(std::move(suspended_scope));
  107. }
  108. }
  109. auto DeclNameStack::AddName(NameContext name_context, SemIR::InstId target_id,
  110. SemIR::AccessKind access_kind) -> void {
  111. switch (name_context.state) {
  112. case NameContext::State::Error:
  113. return;
  114. case NameContext::State::Unresolved:
  115. if (!name_context.parent_scope_id.has_value()) {
  116. AddNameToLookup(*context_, name_context.name_id, target_id,
  117. name_context.initial_scope_index);
  118. } else {
  119. auto& name_scope =
  120. context_->name_scopes().Get(name_context.parent_scope_id);
  121. if (name_context.has_qualifiers) {
  122. auto inst = context_->insts().Get(name_scope.inst_id());
  123. if (!inst.Is<SemIR::Namespace>()) {
  124. // TODO: Point at the declaration for the scoped entity.
  125. CARBON_DIAGNOSTIC(
  126. QualifiedDeclOutsideScopeEntity, Error,
  127. "out-of-line declaration requires a declaration in "
  128. "scoped entity");
  129. context_->emitter().Emit(name_context.loc_id,
  130. QualifiedDeclOutsideScopeEntity);
  131. }
  132. }
  133. // Exports are only tracked when the declaration is at the file-level
  134. // scope. Otherwise, it's in some other entity, such as a class.
  135. if (access_kind == SemIR::AccessKind::Public &&
  136. name_context.initial_scope_index == ScopeIndex::Package) {
  137. context_->exports().push_back(target_id);
  138. }
  139. name_scope.AddRequired({.name_id = name_context.name_id,
  140. .result = SemIR::ScopeLookupResult::MakeFound(
  141. target_id, access_kind)});
  142. }
  143. break;
  144. default:
  145. CARBON_FATAL("Should not be calling AddName");
  146. break;
  147. }
  148. }
  149. auto DeclNameStack::AddNameOrDiagnose(NameContext name_context,
  150. SemIR::InstId target_id,
  151. SemIR::AccessKind access_kind) -> void {
  152. if (name_context.state == DeclNameStack::NameContext::State::Poisoned) {
  153. DiagnosePoisonedName(*context_, name_context.name_id_for_new_inst(),
  154. name_context.poisoning_loc_id, name_context.loc_id);
  155. } else if (auto id = name_context.prev_inst_id(); id.has_value()) {
  156. DiagnoseDuplicateName(*context_, name_context.name_id, name_context.loc_id,
  157. SemIR::LocId(id));
  158. } else {
  159. AddName(name_context, target_id, access_kind);
  160. }
  161. }
  162. auto DeclNameStack::LookupOrAddName(NameContext name_context,
  163. SemIR::InstId target_id,
  164. SemIR::AccessKind access_kind)
  165. -> SemIR::ScopeLookupResult {
  166. if (name_context.state == NameContext::State::Poisoned) {
  167. return SemIR::ScopeLookupResult::MakePoisoned(
  168. name_context.poisoning_loc_id);
  169. }
  170. if (auto id = name_context.prev_inst_id(); id.has_value()) {
  171. return SemIR::ScopeLookupResult::MakeFound(id, access_kind);
  172. }
  173. AddName(name_context, target_id, access_kind);
  174. return SemIR::ScopeLookupResult::MakeNotFound();
  175. }
  176. // Get the name scope and generic to use for associated entities in `scope`.
  177. // Typically this is None, in which case the input scope should be used, but
  178. // some entities have a separate generic and inner scope used for associated
  179. // entities.
  180. static auto GetAssociatedEntityScope(Context& context,
  181. const SemIR::NameScope& scope)
  182. -> std::pair<SemIR::NameScopeId, SemIR::GenericId> {
  183. auto scope_inst = context.insts().Get(scope.inst_id());
  184. CARBON_KIND_SWITCH(scope_inst) {
  185. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  186. const auto& interface =
  187. context.interfaces().Get(interface_decl.interface_id);
  188. return {interface.scope_with_self_id, interface.generic_with_self_id};
  189. }
  190. case CARBON_KIND(SemIR::InterfaceWithSelfDecl _): {
  191. CARBON_FATAL("Expected InterfaceDecl as qualifier scope");
  192. }
  193. case CARBON_KIND(SemIR::NamedConstraintDecl _): {
  194. // ResolveAsScope() does not allow named constraints as a scope qualifier.
  195. CARBON_FATAL(
  196. "Did not expect to find named constraint as scope qualifier");
  197. }
  198. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl _): {
  199. CARBON_FATAL("Expected NamedConstraintDecl as qualifier scope");
  200. }
  201. default:
  202. return {SemIR::NameScopeId::None, SemIR::GenericId::None};
  203. }
  204. }
  205. // Push a scope corresponding to a name qualifier. For example, for
  206. // `fn Class(T:! type).F(n: i32)` we will push the scope for `Class(T:! type)`
  207. // between the scope containing the declaration of `T` and the scope
  208. // containing the declaration of `n`.
  209. //
  210. // Returns the NameScopeId to use as the parent scope of the next name.
  211. static auto PushNameQualifierScope(Context& context, SemIR::LocId loc_id,
  212. SemIR::NameScopeId scope_id,
  213. SemIR::GenericId generic_id,
  214. bool has_error = false)
  215. -> SemIR::NameScopeId {
  216. // If the qualifier has no parameters, we don't need to keep around a
  217. // parameter scope.
  218. context.scope_stack().PopIfEmpty();
  219. auto self_specific_id = SemIR::SpecificId::None;
  220. if (generic_id.has_value()) {
  221. self_specific_id = context.generics().GetSelfSpecific(generic_id);
  222. // When declaring a member of a generic, resolve the self specific.
  223. ResolveSpecificDefinition(context, loc_id, self_specific_id);
  224. }
  225. // Close the generic stack scope and open a new one for whatever comes after
  226. // the qualifier. As this is a qualifier it must not be the initial
  227. // declaration of the entity, so we treat it as a redeclaration.
  228. FinishGenericRedecl(context, generic_id);
  229. // What follows the qualifier will be a declaration. The signature of an
  230. // entity is also a declaration even if it is followed by curly braces
  231. // providing the definition.
  232. StartGenericDecl(context);
  233. const auto& scope = context.name_scopes().Get(scope_id);
  234. context.scope_stack().PushForEntity(scope.inst_id(), scope_id,
  235. self_specific_id, has_error);
  236. auto [assoc_entity_scope_id, assoc_entity_generic_id] =
  237. GetAssociatedEntityScope(context, scope);
  238. if (assoc_entity_scope_id.has_value()) {
  239. const auto& assoc_entity_scope =
  240. context.name_scopes().Get(assoc_entity_scope_id);
  241. // InterfaceDecl is the only inst that can be a scope qualifier and that has
  242. // an associated entity scope, the InterfaceWithSelfDecl.
  243. auto interface_decl = context.insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  244. assoc_entity_scope.inst_id());
  245. auto& interface = context.interfaces().Get(interface_decl.interface_id);
  246. // An interface also introduces its 'Self' parameter into the associated
  247. // entity scope, despite it not being redeclared as part of the qualifier.
  248. context.scope_stack().AddCompileTimeBinding();
  249. context.scope_stack().PushCompileTimeBinding(interface.self_param_id);
  250. // Move into the interface-with-self scope.
  251. context.scope_stack().PushForEntity(
  252. assoc_entity_scope.inst_id(), assoc_entity_scope_id,
  253. context.generics().GetSelfSpecific(assoc_entity_generic_id), has_error);
  254. }
  255. // Enter a parameter scope in case the qualified name itself has parameters.
  256. context.scope_stack().PushForSameRegion();
  257. return assoc_entity_scope_id.has_value() ? assoc_entity_scope_id : scope_id;
  258. }
  259. auto DeclNameStack::ApplyNameQualifier(const NameComponent& name) -> void {
  260. auto& name_context = decl_name_stack_.back();
  261. ApplyAndLookupName(name_context, name.name_loc_id, name.name_id);
  262. name_context.has_qualifiers = true;
  263. // Resolve the qualifier as a scope and enter the new scope.
  264. auto [scope_id, generic_id] = ResolveAsScope(name_context, name);
  265. if (scope_id.has_value()) {
  266. name_context.parent_scope_id = PushNameQualifierScope(
  267. *context_, name_context.loc_id, scope_id, generic_id,
  268. context_->name_scopes().Get(scope_id).has_error());
  269. } else {
  270. name_context.state = NameContext::State::Error;
  271. }
  272. }
  273. auto DeclNameStack::ApplyAndLookupName(NameContext& name_context,
  274. SemIR::LocId loc_id,
  275. SemIR::NameId name_id) -> void {
  276. // Update the final name component.
  277. name_context.loc_id = loc_id;
  278. name_context.name_id = name_id;
  279. // Don't perform any more lookups after we hit an error. We still track the
  280. // final name, though.
  281. if (name_context.state == NameContext::State::Error) {
  282. return;
  283. }
  284. // For identifier nodes, we need to perform a lookup on the identifier.
  285. auto lookup_result = LookupNameInDecl(*context_, name_context.loc_id, name_id,
  286. name_context.parent_scope_id,
  287. name_context.initial_scope_index);
  288. if (lookup_result.is_poisoned()) {
  289. name_context.poisoning_loc_id = lookup_result.poisoning_loc_id();
  290. name_context.state = NameContext::State::Poisoned;
  291. } else if (!lookup_result.is_found()) {
  292. // Invalid indicates an unresolved name. Store it and return.
  293. name_context.state = NameContext::State::Unresolved;
  294. } else {
  295. // Store the resolved instruction and continue for the target scope
  296. // update.
  297. name_context.resolved_inst_id = lookup_result.target_inst_id();
  298. name_context.state = NameContext::State::Resolved;
  299. }
  300. }
  301. // Checks and returns whether name_context, which is used as a name qualifier,
  302. // was successfully resolved. Issues a suitable diagnostic if not.
  303. static auto CheckQualifierIsResolved(
  304. Context& context, const DeclNameStack::NameContext& name_context) -> bool {
  305. switch (name_context.state) {
  306. case DeclNameStack::NameContext::State::Empty:
  307. CARBON_FATAL("No qualifier to resolve");
  308. case DeclNameStack::NameContext::State::Resolved:
  309. return true;
  310. case DeclNameStack::NameContext::State::Poisoned:
  311. case DeclNameStack::NameContext::State::Unresolved:
  312. // Because more qualifiers were found, we diagnose that the earlier
  313. // qualifier failed to resolve.
  314. DiagnoseNameNotFound(context, name_context.loc_id, name_context.name_id);
  315. return false;
  316. case DeclNameStack::NameContext::State::Finished:
  317. CARBON_FATAL("Added a qualifier after calling FinishName");
  318. case DeclNameStack::NameContext::State::Error:
  319. // Already in an error state, so return without examining.
  320. return false;
  321. }
  322. }
  323. // Diagnose that a qualified declaration name specifies an incomplete class as
  324. // its scope.
  325. static auto DiagnoseQualifiedDeclInIncompleteClassScope(Context& context,
  326. SemIR::LocId loc_id,
  327. SemIR::ClassId class_id)
  328. -> void {
  329. CARBON_DIAGNOSTIC(QualifiedDeclInIncompleteClassScope, Error,
  330. "cannot declare a member of incomplete class {0}",
  331. SemIR::TypeId);
  332. auto builder =
  333. context.emitter().Build(loc_id, QualifiedDeclInIncompleteClassScope,
  334. context.classes().Get(class_id).self_type_id);
  335. NoteIncompleteClass(context, class_id, builder);
  336. builder.Emit();
  337. }
  338. // Diagnose that a qualified declaration name specifies an undefined interface
  339. // as its scope.
  340. static auto DiagnoseQualifiedDeclInUndefinedInterfaceScope(
  341. Context& context, SemIR::LocId loc_id, SemIR::InterfaceId interface_id,
  342. SemIR::InstId interface_inst_id) -> void {
  343. CARBON_DIAGNOSTIC(QualifiedDeclInUndefinedInterfaceScope, Error,
  344. "cannot declare a member of undefined interface {0}",
  345. InstIdAsType);
  346. auto builder = context.emitter().Build(
  347. loc_id, QualifiedDeclInUndefinedInterfaceScope, interface_inst_id);
  348. NoteIncompleteInterface(context, interface_id, builder);
  349. builder.Emit();
  350. }
  351. // Diagnose that a qualified declaration name specifies a different package as
  352. // its scope.
  353. static auto DiagnoseQualifiedDeclInImportedPackage(Context& context,
  354. SemIR::LocId use_loc_id,
  355. SemIR::LocId import_loc_id)
  356. -> void {
  357. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackage, Error,
  358. "imported packages cannot be used for declarations");
  359. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackageSource, Note,
  360. "package imported here");
  361. context.emitter()
  362. .Build(use_loc_id, QualifiedDeclOutsidePackage)
  363. .Note(import_loc_id, QualifiedDeclOutsidePackageSource)
  364. .Emit();
  365. }
  366. // Diagnose that a qualified declaration name specifies a non-scope entity as
  367. // its scope.
  368. static auto DiagnoseQualifiedDeclInNonScope(
  369. Context& context, SemIR::LocId use_loc_id,
  370. SemIR::LocId non_scope_entity_loc_id) -> void {
  371. CARBON_DIAGNOSTIC(QualifiedNameInNonScope, Error,
  372. "name qualifiers are only allowed for entities that "
  373. "provide a scope");
  374. CARBON_DIAGNOSTIC(QualifiedNameNonScopeEntity, Note,
  375. "referenced non-scope entity declared here");
  376. context.emitter()
  377. .Build(use_loc_id, QualifiedNameInNonScope)
  378. .Note(non_scope_entity_loc_id, QualifiedNameNonScopeEntity)
  379. .Emit();
  380. }
  381. auto DeclNameStack::ResolveAsScope(const NameContext& name_context,
  382. const NameComponent& name) const
  383. -> std::pair<SemIR::NameScopeId, SemIR::GenericId> {
  384. constexpr std::pair<SemIR::NameScopeId, SemIR::GenericId> InvalidResult = {
  385. SemIR::NameScopeId::None, SemIR::GenericId::None};
  386. if (!CheckQualifierIsResolved(*context_, name_context)) {
  387. return InvalidResult;
  388. }
  389. if (name_context.state == NameContext::State::Poisoned) {
  390. return InvalidResult;
  391. }
  392. auto new_params = DeclParams(
  393. name.name_loc_id, name.first_param_node_id, name.last_param_node_id,
  394. name.implicit_param_patterns_id, name.param_patterns_id);
  395. // Find the scope corresponding to the resolved instruction.
  396. // TODO: When diagnosing qualifiers on names, print a diagnostic that talks
  397. // about qualifiers instead of redeclarations. Maybe also rename
  398. // CheckRedeclParamsMatch.
  399. CARBON_KIND_SWITCH(context_->insts().Get(name_context.resolved_inst_id)) {
  400. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  401. const auto& class_info = context_->classes().Get(class_decl.class_id);
  402. if (!CheckRedeclParamsMatch(*context_, new_params,
  403. DeclParams(class_info))) {
  404. return InvalidResult;
  405. }
  406. if (!class_info.is_complete()) {
  407. DiagnoseQualifiedDeclInIncompleteClassScope(
  408. *context_, name_context.loc_id, class_decl.class_id);
  409. return InvalidResult;
  410. }
  411. return {class_info.scope_id, class_info.generic_id};
  412. }
  413. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  414. const auto& interface_info =
  415. context_->interfaces().Get(interface_decl.interface_id);
  416. if (!CheckRedeclParamsMatch(*context_, new_params,
  417. DeclParams(interface_info))) {
  418. return InvalidResult;
  419. }
  420. if (!interface_info.is_complete()) {
  421. DiagnoseQualifiedDeclInUndefinedInterfaceScope(
  422. *context_, name_context.loc_id, interface_decl.interface_id,
  423. name_context.resolved_inst_id);
  424. return InvalidResult;
  425. }
  426. // The scope and generic of an `I(T:! type)` is the outer
  427. // interface-without-self. That is the generic where parameters appear.
  428. // However when moving to the next qualifier, we need to move to the
  429. // interface-with-self for the associated entity name.
  430. return {interface_info.scope_without_self_id, interface_info.generic_id};
  431. }
  432. case CARBON_KIND(SemIR::Namespace resolved_inst): {
  433. auto scope_id = resolved_inst.name_scope_id;
  434. auto& scope = context_->name_scopes().Get(scope_id);
  435. // This is specifically for qualified name handling.
  436. if (!CheckRedeclParamsMatch(
  437. *context_, new_params,
  438. DeclParams(SemIR::LocId(name_context.resolved_inst_id),
  439. Parse::NodeId::None, Parse::NodeId::None,
  440. SemIR::InstBlockId::None, SemIR::InstBlockId::None))) {
  441. return InvalidResult;
  442. }
  443. if (scope.is_closed_import()) {
  444. DiagnoseQualifiedDeclInImportedPackage(*context_, name_context.loc_id,
  445. SemIR::LocId(scope.inst_id()));
  446. // Only error once per package. Recover by allowing this package name to
  447. // be used as a name qualifier.
  448. scope.set_is_closed_import(false);
  449. }
  450. return {scope_id, SemIR::GenericId::None};
  451. }
  452. default: {
  453. DiagnoseQualifiedDeclInNonScope(
  454. *context_, name_context.loc_id,
  455. SemIR::LocId(name_context.resolved_inst_id));
  456. return InvalidResult;
  457. }
  458. }
  459. }
  460. } // namespace Carbon::Check