decl_name_stack.cpp 16 KB

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