decl_name_stack.cpp 18 KB

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