decl_name_stack.cpp 16 KB

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