decl_name_stack.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. auto add_scope = [&] {
  126. int index = name_scope.names.size();
  127. name_scope.names.push_back(
  128. {.name_id = name_context.unresolved_name_id,
  129. .inst_id = target_id,
  130. .access_kind = access_kind});
  131. return index;
  132. };
  133. auto result = name_scope.name_map.Insert(
  134. name_context.unresolved_name_id, add_scope);
  135. CARBON_CHECK(result.is_inserted())
  136. << "Duplicate names should have been resolved previously: "
  137. << name_context.unresolved_name_id << " in "
  138. << name_context.parent_scope_id;
  139. }
  140. break;
  141. default:
  142. CARBON_FATAL() << "Should not be calling AddName";
  143. break;
  144. }
  145. }
  146. auto DeclNameStack::AddNameOrDiagnoseDuplicate(NameContext name_context,
  147. SemIR::InstId target_id,
  148. SemIR::AccessKind access_kind)
  149. -> void {
  150. if (auto id = name_context.prev_inst_id(); id.is_valid()) {
  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::InstId {
  160. if (auto id = name_context.prev_inst_id(); id.is_valid()) {
  161. return id;
  162. }
  163. AddName(name_context, target_id, access_kind);
  164. return SemIR::InstId::Invalid;
  165. }
  166. // Push a scope corresponding to a name qualifier. For example, for
  167. // `fn Class(T:! type).F(n: i32)` we will push the scope for `Class(T:! type)`
  168. // between the scope containing the declaration of `T` and the scope
  169. // containing the declaration of `n`.
  170. static auto PushNameQualifierScope(Context& context,
  171. SemIR::InstId scope_inst_id,
  172. SemIR::NameScopeId scope_id,
  173. bool has_error = false) -> void {
  174. // If the qualifier has no parameters, we don't need to keep around a
  175. // parameter scope.
  176. context.scope_stack().PopIfEmpty();
  177. context.scope_stack().Push(scope_inst_id, scope_id, has_error);
  178. // Enter a parameter scope in case the qualified name itself has parameters.
  179. context.scope_stack().Push();
  180. }
  181. auto DeclNameStack::ApplyNameQualifier(const NameComponent& name) -> void {
  182. auto& name_context = decl_name_stack_.back();
  183. ApplyAndLookupName(name_context, name.name_loc_id, name.name_id);
  184. name_context.has_qualifiers = true;
  185. // Resolve the qualifier as a scope and enter the new scope.
  186. auto scope_id = ResolveAsScope(name_context, name);
  187. if (scope_id.is_valid()) {
  188. PushNameQualifierScope(*context_, name_context.resolved_inst_id, scope_id,
  189. context_->name_scopes().Get(scope_id).has_error);
  190. name_context.parent_scope_id = scope_id;
  191. } else {
  192. name_context.state = NameContext::State::Error;
  193. }
  194. }
  195. auto DeclNameStack::ApplyAndLookupName(NameContext& name_context,
  196. SemIR::LocId loc_id,
  197. SemIR::NameId name_id) -> void {
  198. // The location of the name is the location of the last name token we've
  199. // processed so far.
  200. name_context.loc_id = loc_id;
  201. // Don't perform any more lookups after we hit an error. We still track the
  202. // final name, though.
  203. if (name_context.state == NameContext::State::Error) {
  204. name_context.unresolved_name_id = name_id;
  205. return;
  206. }
  207. // For identifier nodes, we need to perform a lookup on the identifier.
  208. auto resolved_inst_id = context_->LookupNameInDecl(
  209. name_context.loc_id, name_id, name_context.parent_scope_id);
  210. if (!resolved_inst_id.is_valid()) {
  211. // Invalid indicates an unresolved name. Store it and return.
  212. name_context.unresolved_name_id = name_id;
  213. name_context.state = NameContext::State::Unresolved;
  214. } else {
  215. // Store the resolved instruction and continue for the target scope
  216. // update.
  217. name_context.resolved_inst_id = resolved_inst_id;
  218. name_context.state = NameContext::State::Resolved;
  219. }
  220. }
  221. // Checks and returns whether name_context, which is used as a name qualifier,
  222. // was successfully resolved. Issues a suitable diagnostic if not.
  223. static auto CheckQualifierIsResolved(
  224. Context& context, const DeclNameStack::NameContext& name_context) -> bool {
  225. switch (name_context.state) {
  226. case DeclNameStack::NameContext::State::Empty:
  227. CARBON_FATAL() << "No qualifier to resolve";
  228. case DeclNameStack::NameContext::State::Resolved:
  229. return true;
  230. case DeclNameStack::NameContext::State::Unresolved:
  231. // Because more qualifiers were found, we diagnose that the earlier
  232. // qualifier failed to resolve.
  233. context.DiagnoseNameNotFound(name_context.loc_id,
  234. name_context.unresolved_name_id);
  235. return false;
  236. case DeclNameStack::NameContext::State::Finished:
  237. CARBON_FATAL() << "Added a qualifier after calling FinishName";
  238. case DeclNameStack::NameContext::State::Error:
  239. // Already in an error state, so return without examining.
  240. return false;
  241. }
  242. }
  243. // Diagnose that a qualified declaration name specifies an incomplete class as
  244. // its scope.
  245. static auto DiagnoseQualifiedDeclInIncompleteClassScope(Context& context,
  246. SemIRLoc loc,
  247. SemIR::ClassId class_id)
  248. -> void {
  249. CARBON_DIAGNOSTIC(QualifiedDeclInIncompleteClassScope, Error,
  250. "Cannot declare a member of incomplete class `{0}`.",
  251. SemIR::TypeId);
  252. auto builder =
  253. context.emitter().Build(loc, QualifiedDeclInIncompleteClassScope,
  254. context.classes().Get(class_id).self_type_id);
  255. context.NoteIncompleteClass(class_id, builder);
  256. builder.Emit();
  257. }
  258. // Diagnose that a qualified declaration name specifies an undefined interface
  259. // as its scope.
  260. static auto DiagnoseQualifiedDeclInUndefinedInterfaceScope(
  261. Context& context, SemIRLoc loc, SemIR::InterfaceId interface_id,
  262. SemIR::InstId interface_inst_id) -> void {
  263. CARBON_DIAGNOSTIC(QualifiedDeclInUndefinedInterfaceScope, Error,
  264. "Cannot declare a member of undefined interface `{0}`.",
  265. std::string);
  266. auto builder = context.emitter().Build(
  267. loc, QualifiedDeclInUndefinedInterfaceScope,
  268. context.sem_ir().StringifyTypeExpr(
  269. context.sem_ir().constant_values().GetConstantInstId(
  270. interface_inst_id)));
  271. context.NoteUndefinedInterface(interface_id, builder);
  272. builder.Emit();
  273. }
  274. // Diagnose that a qualified declaration name specifies a different package as
  275. // its scope.
  276. static auto DiagnoseQualifiedDeclInImportedPackage(Context& context,
  277. SemIRLoc use_loc,
  278. SemIRLoc import_loc)
  279. -> void {
  280. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackage, Error,
  281. "Imported packages cannot be used for declarations.");
  282. CARBON_DIAGNOSTIC(QualifiedDeclOutsidePackageSource, Note,
  283. "Package imported here.");
  284. context.emitter()
  285. .Build(use_loc, QualifiedDeclOutsidePackage)
  286. .Note(import_loc, QualifiedDeclOutsidePackageSource)
  287. .Emit();
  288. }
  289. // Diagnose that a qualified declaration name specifies a non-scope entity as
  290. // its scope.
  291. static auto DiagnoseQualifiedDeclInNonScope(Context& context, SemIRLoc use_loc,
  292. SemIRLoc non_scope_entity_loc)
  293. -> void {
  294. CARBON_DIAGNOSTIC(QualifiedNameInNonScope, Error,
  295. "Name qualifiers are only allowed for entities that "
  296. "provide a scope.");
  297. CARBON_DIAGNOSTIC(QualifiedNameNonScopeEntity, Note,
  298. "Referenced non-scope entity declared here.");
  299. context.emitter()
  300. .Build(use_loc, QualifiedNameInNonScope)
  301. .Note(non_scope_entity_loc, QualifiedNameNonScopeEntity)
  302. .Emit();
  303. }
  304. auto DeclNameStack::ResolveAsScope(const NameContext& name_context,
  305. const NameComponent& name) const
  306. -> SemIR::NameScopeId {
  307. if (!CheckQualifierIsResolved(*context_, name_context)) {
  308. return SemIR::NameScopeId::Invalid;
  309. }
  310. auto new_params =
  311. DeclParams(name.name_loc_id, name.implicit_params_id, name.params_id);
  312. // Find the scope corresponding to the resolved instruction.
  313. CARBON_KIND_SWITCH(context_->insts().Get(name_context.resolved_inst_id)) {
  314. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  315. const auto& class_info = context_->classes().Get(class_decl.class_id);
  316. if (!CheckRedeclParamsMatch(*context_, new_params,
  317. DeclParams(class_info))) {
  318. return SemIR::NameScopeId::Invalid;
  319. }
  320. if (!class_info.is_defined()) {
  321. DiagnoseQualifiedDeclInIncompleteClassScope(
  322. *context_, name_context.loc_id, class_decl.class_id);
  323. return SemIR::NameScopeId::Invalid;
  324. }
  325. return class_info.scope_id;
  326. }
  327. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  328. const auto& interface_info =
  329. context_->interfaces().Get(interface_decl.interface_id);
  330. if (!CheckRedeclParamsMatch(*context_, new_params,
  331. DeclParams(interface_info))) {
  332. return SemIR::NameScopeId::Invalid;
  333. }
  334. if (!interface_info.is_defined()) {
  335. DiagnoseQualifiedDeclInUndefinedInterfaceScope(
  336. *context_, name_context.loc_id, interface_decl.interface_id,
  337. name_context.resolved_inst_id);
  338. return SemIR::NameScopeId::Invalid;
  339. }
  340. return interface_info.scope_id;
  341. }
  342. case CARBON_KIND(SemIR::Namespace resolved_inst): {
  343. auto scope_id = resolved_inst.name_scope_id;
  344. auto& scope = context_->name_scopes().Get(scope_id);
  345. if (!CheckRedeclParamsMatch(*context_, new_params,
  346. DeclParams(name_context.resolved_inst_id,
  347. SemIR::InstBlockId::Invalid,
  348. SemIR::InstBlockId::Invalid))) {
  349. return SemIR::NameScopeId::Invalid;
  350. }
  351. if (scope.is_closed_import) {
  352. DiagnoseQualifiedDeclInImportedPackage(*context_, name_context.loc_id,
  353. scope.inst_id);
  354. // Only error once per package. Recover by allowing this package name to
  355. // be used as a name qualifier.
  356. scope.is_closed_import = false;
  357. }
  358. return scope_id;
  359. }
  360. default: {
  361. DiagnoseQualifiedDeclInNonScope(*context_, name_context.loc_id,
  362. name_context.resolved_inst_id);
  363. return SemIR::NameScopeId::Invalid;
  364. }
  365. }
  366. }
  367. } // namespace Carbon::Check