decl_name_stack.cpp 18 KB

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