decl_name_stack.cpp 19 KB

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