name_lookup.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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/name_lookup.h"
  5. #include "toolchain/check/generic.h"
  6. #include "toolchain/check/import.h"
  7. #include "toolchain/check/import_ref.h"
  8. #include "toolchain/check/type_completion.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. namespace Carbon::Check {
  11. auto AddNameToLookup(Context& context, SemIR::NameId name_id,
  12. SemIR::InstId target_id, ScopeIndex scope_index) -> void {
  13. if (auto existing = context.scope_stack().LookupOrAddName(name_id, target_id,
  14. scope_index);
  15. existing.has_value()) {
  16. // TODO: Add coverage to this use case and use the location of the name
  17. // instead of the target.
  18. DiagnoseDuplicateName(context, name_id, target_id, existing);
  19. }
  20. }
  21. auto LookupNameInDecl(Context& context, SemIR::LocId loc_id,
  22. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  23. ScopeIndex scope_index) -> SemIR::ScopeLookupResult {
  24. if (!scope_id.has_value()) {
  25. // Look for a name in the specified scope or a scope nested within it only.
  26. // There are two cases where the name would be in an outer scope:
  27. //
  28. // - The name is the sole component of the declared name:
  29. //
  30. // class A;
  31. // fn F() {
  32. // class A;
  33. // }
  34. //
  35. // In this case, the inner A is not the same class as the outer A, so
  36. // lookup should not find the outer A.
  37. //
  38. // - The name is a qualifier of some larger declared name:
  39. //
  40. // class A { class B; }
  41. // fn F() {
  42. // class A.B {}
  43. // }
  44. //
  45. // In this case, we're not in the correct scope to define a member of
  46. // class A, so we should reject, and we achieve this by not finding the
  47. // name A from the outer scope.
  48. //
  49. // There is also one case where the name would be in an inner scope:
  50. //
  51. // - The name is redeclared by a parameter of the same entity:
  52. //
  53. // fn F() {
  54. // class C(C:! type);
  55. // }
  56. //
  57. // In this case, the class C is not a redeclaration of its parameter, but
  58. // we find the parameter in order to diagnose a redeclaration error.
  59. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  60. context.scope_stack().LookupInLexicalScopesWithin(name_id, scope_index),
  61. SemIR::AccessKind::Public);
  62. } else {
  63. // We do not look into `extend`ed scopes here. A qualified name in a
  64. // declaration must specify the exact scope in which the name was originally
  65. // introduced:
  66. //
  67. // base class A { fn F(); }
  68. // class B { extend base: A; }
  69. //
  70. // // Error, no `F` in `B`.
  71. // fn B.F() {}
  72. return LookupNameInExactScope(context, loc_id, name_id, scope_id,
  73. context.name_scopes().Get(scope_id),
  74. /*is_being_declared=*/true);
  75. }
  76. }
  77. auto LookupUnqualifiedName(Context& context, Parse::NodeId node_id,
  78. SemIR::NameId name_id, bool required)
  79. -> LookupResult {
  80. // TODO: Check for shadowed lookup results.
  81. // Find the results from ancestor lexical scopes. These will be combined with
  82. // results from non-lexical scopes such as namespaces and classes.
  83. auto [lexical_result, non_lexical_scopes] =
  84. context.scope_stack().LookupInLexicalScopes(name_id);
  85. // Walk the non-lexical scopes and perform lookups into each of them.
  86. for (auto [index, lookup_scope_id, specific_id] :
  87. llvm::reverse(non_lexical_scopes)) {
  88. if (auto non_lexical_result =
  89. LookupQualifiedName(context, node_id, name_id,
  90. LookupScope{.name_scope_id = lookup_scope_id,
  91. .specific_id = specific_id},
  92. /*required=*/false);
  93. non_lexical_result.scope_result.is_found()) {
  94. return non_lexical_result;
  95. }
  96. }
  97. if (lexical_result == SemIR::InstId::InitTombstone) {
  98. CARBON_DIAGNOSTIC(UsedBeforeInitialization, Error,
  99. "`{0}` used before initialization", SemIR::NameId);
  100. context.emitter().Emit(node_id, UsedBeforeInitialization, name_id);
  101. return {.specific_id = SemIR::SpecificId::None,
  102. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  103. }
  104. if (lexical_result.has_value()) {
  105. // A lexical scope never needs an associated specific. If there's a
  106. // lexically enclosing generic, then it also encloses the point of use of
  107. // the name.
  108. return {.specific_id = SemIR::SpecificId::None,
  109. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  110. lexical_result, SemIR::AccessKind::Public)};
  111. }
  112. // We didn't find anything at all.
  113. if (required) {
  114. DiagnoseNameNotFound(context, node_id, name_id);
  115. }
  116. return {.specific_id = SemIR::SpecificId::None,
  117. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  118. }
  119. auto LookupNameInExactScope(Context& context, SemIR::LocId loc_id,
  120. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  121. SemIR::NameScope& scope, bool is_being_declared)
  122. -> SemIR::ScopeLookupResult {
  123. if (auto entry_id = is_being_declared
  124. ? scope.Lookup(name_id)
  125. : scope.LookupOrPoison(loc_id, name_id)) {
  126. auto lookup_result = scope.GetEntry(*entry_id).result;
  127. if (!lookup_result.is_poisoned()) {
  128. LoadImportRef(context, lookup_result.target_inst_id());
  129. }
  130. return lookup_result;
  131. }
  132. if (!scope.import_ir_scopes().empty()) {
  133. // TODO: Enforce other access modifiers for imports.
  134. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  135. ImportNameFromOtherPackage(context, loc_id, scope_id,
  136. scope.import_ir_scopes(), name_id),
  137. SemIR::AccessKind::Public);
  138. }
  139. return SemIR::ScopeLookupResult::MakeNotFound();
  140. }
  141. // Prints diagnostics on invalid qualified name access.
  142. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  143. SemIR::InstId scope_result_id,
  144. SemIR::NameId name_id,
  145. SemIR::AccessKind access_kind,
  146. bool is_parent_access,
  147. AccessInfo access_info) -> void {
  148. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  149. context.constant_values().GetInstId(access_info.constant_id));
  150. if (!class_type) {
  151. return;
  152. }
  153. // TODO: Support scoped entities other than just classes.
  154. const auto& class_info = context.classes().Get(class_type->class_id);
  155. auto parent_type_id = class_info.self_type_id;
  156. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  157. if (auto base_type_id =
  158. class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
  159. base_type_id.has_value()) {
  160. parent_type_id = base_type_id;
  161. } else if (auto adapted_type_id = class_info.GetAdaptedType(
  162. context.sem_ir(), class_type->specific_id);
  163. adapted_type_id.has_value()) {
  164. parent_type_id = adapted_type_id;
  165. } else {
  166. CARBON_FATAL("Expected parent for parent access");
  167. }
  168. }
  169. CARBON_DIAGNOSTIC(
  170. ClassInvalidMemberAccess, Error,
  171. "cannot access {0:private|protected} member `{1}` of type {2}",
  172. BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  173. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  174. context.emitter()
  175. .Build(loc, ClassInvalidMemberAccess,
  176. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  177. .Note(scope_result_id, ClassMemberDeclaration)
  178. .Emit();
  179. }
  180. // Returns whether the access is prohibited by the access modifiers.
  181. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  182. SemIR::AccessKind access_kind,
  183. bool is_parent_access) -> bool {
  184. if (!access_info) {
  185. return false;
  186. }
  187. switch (access_kind) {
  188. case SemIR::AccessKind::Public:
  189. return false;
  190. case SemIR::AccessKind::Protected:
  191. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  192. case SemIR::AccessKind::Private:
  193. return access_info->highest_allowed_access !=
  194. SemIR::AccessKind::Private ||
  195. is_parent_access;
  196. }
  197. }
  198. // Information regarding a prohibited access.
  199. struct ProhibitedAccessInfo {
  200. // The resulting inst of the lookup.
  201. SemIR::InstId scope_result_id;
  202. // The access kind of the lookup.
  203. SemIR::AccessKind access_kind;
  204. // If the lookup is from an extended scope. For example, if this is a base
  205. // class member access from a class that extends it.
  206. bool is_parent_access;
  207. };
  208. auto AppendLookupScopesForConstant(Context& context, SemIR::LocId loc_id,
  209. SemIR::ConstantId base_const_id,
  210. llvm::SmallVector<LookupScope>* scopes)
  211. -> bool {
  212. auto base_id = context.constant_values().GetInstId(base_const_id);
  213. auto base = context.insts().Get(base_id);
  214. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  215. scopes->push_back(
  216. LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  217. .specific_id = SemIR::SpecificId::None});
  218. return true;
  219. }
  220. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  221. RequireCompleteType(
  222. context, context.types().GetTypeIdForTypeConstantId(base_const_id),
  223. loc_id, [&] {
  224. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  225. "member access into incomplete class {0}",
  226. InstIdAsType);
  227. return context.emitter().Build(
  228. loc_id, QualifiedExprInIncompleteClassScope, base_id);
  229. });
  230. auto& class_info = context.classes().Get(base_as_class->class_id);
  231. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  232. .specific_id = base_as_class->specific_id});
  233. return true;
  234. }
  235. if (auto base_as_facet_type = base.TryAs<SemIR::FacetType>()) {
  236. auto complete_id = RequireCompleteFacetType(
  237. context, context.types().GetTypeIdForTypeConstantId(base_const_id),
  238. loc_id, *base_as_facet_type, [&] {
  239. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteFacetTypeScope, Error,
  240. "member access into incomplete facet type {0}",
  241. InstIdAsType);
  242. return context.emitter().Build(
  243. loc_id, QualifiedExprInIncompleteFacetTypeScope, base_id);
  244. });
  245. if (complete_id.has_value()) {
  246. const auto& resolved = context.complete_facet_types().Get(complete_id);
  247. for (const auto& interface : resolved.required_interfaces) {
  248. auto& interface_info = context.interfaces().Get(interface.interface_id);
  249. scopes->push_back({.name_scope_id = interface_info.scope_id,
  250. .specific_id = interface.specific_id});
  251. }
  252. } else {
  253. // Lookup into this scope should fail without producing an error since
  254. // `RequireCompleteFacetType` has already issued a diagnostic.
  255. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  256. .specific_id = SemIR::SpecificId::None});
  257. }
  258. return true;
  259. }
  260. if (base_const_id == SemIR::ErrorInst::SingletonConstantId) {
  261. // Lookup into this scope should fail without producing an error.
  262. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  263. .specific_id = SemIR::SpecificId::None});
  264. return true;
  265. }
  266. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  267. // treat it as a name scope, even if it doesn't have members. For example,
  268. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  269. // there's no name `X` in `type`.
  270. return false;
  271. }
  272. // Prints a diagnostic for a missing qualified name.
  273. static auto DiagnoseMemberNameNotFound(
  274. Context& context, SemIRLoc loc, SemIR::NameId name_id,
  275. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  276. if (lookup_scopes.size() == 1 &&
  277. lookup_scopes.front().name_scope_id.has_value()) {
  278. auto specific_id = lookup_scopes.front().specific_id;
  279. auto scope_inst_id = specific_id.has_value()
  280. ? GetInstForSpecific(context, specific_id)
  281. : context.name_scopes()
  282. .Get(lookup_scopes.front().name_scope_id)
  283. .inst_id();
  284. CARBON_DIAGNOSTIC(MemberNameNotFoundInScope, Error,
  285. "member name `{0}` not found in {1}", SemIR::NameId,
  286. InstIdAsType);
  287. context.emitter().Emit(loc, MemberNameNotFoundInScope, name_id,
  288. scope_inst_id);
  289. return;
  290. }
  291. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  292. SemIR::NameId);
  293. context.emitter().Emit(loc, MemberNameNotFound, name_id);
  294. }
  295. auto LookupQualifiedName(Context& context, SemIR::LocId loc_id,
  296. SemIR::NameId name_id,
  297. llvm::ArrayRef<LookupScope> lookup_scopes,
  298. bool required, std::optional<AccessInfo> access_info)
  299. -> LookupResult {
  300. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  301. // TODO: Support reporting of multiple prohibited access.
  302. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  303. LookupResult result = {
  304. .specific_id = SemIR::SpecificId::None,
  305. .scope_result = SemIR::ScopeLookupResult::MakeNotFound()};
  306. bool has_error = false;
  307. bool is_parent_access = false;
  308. // Walk this scope and, if nothing is found here, the scopes it extends.
  309. while (!scopes.empty()) {
  310. auto [scope_id, specific_id] = scopes.pop_back_val();
  311. if (!scope_id.has_value()) {
  312. has_error = true;
  313. continue;
  314. }
  315. auto& name_scope = context.name_scopes().Get(scope_id);
  316. has_error |= name_scope.has_error();
  317. const SemIR::ScopeLookupResult scope_result =
  318. LookupNameInExactScope(context, loc_id, name_id, scope_id, name_scope);
  319. SemIR::AccessKind access_kind = scope_result.access_kind();
  320. auto is_access_prohibited =
  321. IsAccessProhibited(access_info, access_kind, is_parent_access);
  322. // Keep track of prohibited accesses, this will be useful for reporting
  323. // multiple prohibited accesses if we can't find a suitable lookup.
  324. if (is_access_prohibited) {
  325. prohibited_accesses.push_back({
  326. .scope_result_id = scope_result.target_inst_id(),
  327. .access_kind = access_kind,
  328. .is_parent_access = is_parent_access,
  329. });
  330. }
  331. if (!scope_result.is_found() || is_access_prohibited) {
  332. // If nothing is found in this scope or if we encountered an invalid
  333. // access, look in its extended scopes.
  334. const auto& extended = name_scope.extended_scopes();
  335. scopes.reserve(scopes.size() + extended.size());
  336. for (auto extended_id : llvm::reverse(extended)) {
  337. // Substitute into the constant describing the extended scope to
  338. // determine its corresponding specific.
  339. CARBON_CHECK(extended_id.has_value());
  340. LoadImportRef(context, extended_id);
  341. SemIR::ConstantId const_id = GetConstantValueInSpecific(
  342. context.sem_ir(), specific_id, extended_id);
  343. DiagnosticAnnotationScope annotate_diagnostics(
  344. &context.emitter(), [&](auto& builder) {
  345. CARBON_DIAGNOSTIC(FromExtendHere, Note,
  346. "declared as an extended scope here");
  347. builder.Note(extended_id, FromExtendHere);
  348. });
  349. if (!AppendLookupScopesForConstant(context, loc_id, const_id,
  350. &scopes)) {
  351. // TODO: Handle case where we have a symbolic type and instead should
  352. // look in its type.
  353. }
  354. }
  355. is_parent_access |= !extended.empty();
  356. continue;
  357. }
  358. // If this is our second lookup result, diagnose an ambiguity.
  359. if (result.scope_result.is_found()) {
  360. CARBON_DIAGNOSTIC(
  361. NameAmbiguousDueToExtend, Error,
  362. "ambiguous use of name `{0}` found in multiple extended scopes",
  363. SemIR::NameId);
  364. context.emitter().Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  365. // TODO: Add notes pointing to the scopes.
  366. return {.specific_id = SemIR::SpecificId::None,
  367. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  368. }
  369. result.scope_result = scope_result;
  370. result.specific_id = specific_id;
  371. }
  372. if (required && !result.scope_result.is_found()) {
  373. if (!has_error) {
  374. if (prohibited_accesses.empty()) {
  375. DiagnoseMemberNameNotFound(context, loc_id, name_id, lookup_scopes);
  376. } else {
  377. // TODO: We should report multiple prohibited accesses in case we don't
  378. // find a valid lookup. Reporting the last one should suffice for now.
  379. auto [scope_result_id, access_kind, is_parent_access] =
  380. prohibited_accesses.back();
  381. // Note, `access_info` is guaranteed to have a value here, since
  382. // `prohibited_accesses` is non-empty.
  383. DiagnoseInvalidQualifiedNameAccess(context, loc_id, scope_result_id,
  384. name_id, access_kind,
  385. is_parent_access, *access_info);
  386. }
  387. }
  388. CARBON_CHECK(!result.scope_result.is_poisoned());
  389. return {.specific_id = SemIR::SpecificId::None,
  390. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  391. }
  392. return result;
  393. }
  394. // Returns the scope of the Core package, or `None` if it's not found.
  395. //
  396. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  397. // name lookup to find it.
  398. static auto GetCorePackage(Context& context, SemIR::LocId loc_id,
  399. llvm::StringRef name) -> SemIR::NameScopeId {
  400. auto packaging = context.parse_tree().packaging_decl();
  401. if (packaging && packaging->names.package_id == PackageNameId::Core) {
  402. return SemIR::NameScopeId::Package;
  403. }
  404. auto core_name_id = SemIR::NameId::Core;
  405. // Look up `package.Core`.
  406. auto core_scope_result = LookupNameInExactScope(
  407. context, loc_id, core_name_id, SemIR::NameScopeId::Package,
  408. context.name_scopes().Get(SemIR::NameScopeId::Package));
  409. if (core_scope_result.is_found()) {
  410. // We expect it to be a namespace.
  411. if (auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(
  412. core_scope_result.target_inst_id())) {
  413. // TODO: Decide whether to allow the case where `Core` is not a package.
  414. return namespace_inst->name_scope_id;
  415. }
  416. }
  417. CARBON_DIAGNOSTIC(
  418. CoreNotFound, Error,
  419. "`Core.{0}` implicitly referenced here, but package `Core` not found",
  420. std::string);
  421. context.emitter().Emit(loc_id, CoreNotFound, name.str());
  422. return SemIR::NameScopeId::None;
  423. }
  424. auto LookupNameInCore(Context& context, SemIR::LocId loc_id,
  425. llvm::StringRef name) -> SemIR::InstId {
  426. auto core_package_id = GetCorePackage(context, loc_id, name);
  427. if (!core_package_id.has_value()) {
  428. return SemIR::ErrorInst::SingletonInstId;
  429. }
  430. auto name_id = SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  431. auto scope_result =
  432. LookupNameInExactScope(context, loc_id, name_id, core_package_id,
  433. context.name_scopes().Get(core_package_id));
  434. if (!scope_result.is_found()) {
  435. CARBON_DIAGNOSTIC(
  436. CoreNameNotFound, Error,
  437. "name `Core.{0}` implicitly referenced here, but not found",
  438. SemIR::NameId);
  439. context.emitter().Emit(loc_id, CoreNameNotFound, name_id);
  440. return SemIR::ErrorInst::SingletonInstId;
  441. }
  442. // Look through import_refs and aliases.
  443. return context.constant_values().GetConstantInstId(
  444. scope_result.target_inst_id());
  445. }
  446. auto DiagnoseDuplicateName(Context& context, SemIR::NameId name_id,
  447. SemIRLoc dup_def, SemIRLoc prev_def) -> void {
  448. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  449. "duplicate name `{0}` being declared in the same scope",
  450. SemIR::NameId);
  451. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  452. context.emitter()
  453. .Build(dup_def, NameDeclDuplicate, name_id)
  454. .Note(prev_def, NameDeclPrevious)
  455. .Emit();
  456. }
  457. auto DiagnosePoisonedName(Context& context, SemIR::NameId name_id,
  458. SemIR::LocId poisoning_loc_id,
  459. SemIR::LocId decl_name_loc_id) -> void {
  460. CARBON_CHECK(poisoning_loc_id.has_value(),
  461. "Trying to diagnose poisoned name with no poisoning location");
  462. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  463. "name `{0}` used before it was declared", SemIR::NameId);
  464. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  465. context.emitter()
  466. .Build(poisoning_loc_id, NameUseBeforeDecl, name_id)
  467. .Note(decl_name_loc_id, NameUseBeforeDeclNote)
  468. .Emit();
  469. }
  470. auto DiagnoseNameNotFound(Context& context, SemIRLoc loc, SemIR::NameId name_id)
  471. -> void {
  472. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  473. context.emitter().Emit(loc, NameNotFound, name_id);
  474. }
  475. } // namespace Carbon::Check