decl_name_stack.cpp 19 KB

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