name_lookup.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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 <optional>
  6. #include "common/raw_string_ostream.h"
  7. #include "toolchain/check/control_flow.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/member_access.h"
  15. #include "toolchain/check/subst.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/diagnostics/format_providers.h"
  19. #include "toolchain/sem_ir/generic.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/name_scope.h"
  22. namespace Carbon::Check {
  23. auto AddNameToLookup(Context& context, SemIR::NameId name_id,
  24. SemIR::InstId target_id, ScopeIndex scope_index) -> void {
  25. if (auto existing = context.scope_stack().LookupOrAddName(
  26. name_id, target_id, scope_index, IsCurrentPositionReachable(context));
  27. existing.has_value()) {
  28. // TODO: Add coverage to this use case and use the location of the name
  29. // instead of the target.
  30. DiagnoseDuplicateName(context, name_id, SemIR::LocId(target_id),
  31. SemIR::LocId(existing));
  32. }
  33. }
  34. auto LookupNameInDecl(Context& context, SemIR::LocId loc_id,
  35. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  36. ScopeIndex scope_index) -> SemIR::ScopeLookupResult {
  37. if (!scope_id.has_value()) {
  38. // Look for a name in the specified scope or a scope nested within it only.
  39. // There are two cases where the name would be in an outer scope:
  40. //
  41. // - The name is the sole component of the declared name:
  42. //
  43. // class A;
  44. // fn F() {
  45. // class A;
  46. // }
  47. //
  48. // In this case, the inner A is not the same class as the outer A, so
  49. // lookup should not find the outer A.
  50. //
  51. // - The name is a qualifier of some larger declared name:
  52. //
  53. // class A { class B; }
  54. // fn F() {
  55. // class A.B {}
  56. // }
  57. //
  58. // In this case, we're not in the correct scope to define a member of
  59. // class A, so we should reject, and we achieve this by not finding the
  60. // name A from the outer scope.
  61. //
  62. // There is also one case where the name would be in an inner scope:
  63. //
  64. // - The name is redeclared by a parameter of the same entity:
  65. //
  66. // fn F() {
  67. // class C(C:! type);
  68. // }
  69. //
  70. // In this case, the class C is not a redeclaration of its parameter, but
  71. // we find the parameter in order to diagnose a redeclaration error.
  72. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  73. context.scope_stack().LookupInLexicalScopesWithin(
  74. name_id, scope_index, /*use_loc_id=*/SemIR::LocId::None,
  75. /*is_reachable=*/true),
  76. SemIR::AccessKind::Public);
  77. } else {
  78. // We do not look into `extend`ed scopes here. A qualified name in a
  79. // declaration must specify the exact scope in which the name was originally
  80. // introduced:
  81. //
  82. // base class A { fn F(); }
  83. // class B { extend base: A; }
  84. //
  85. // // Error, no `F` in `B`.
  86. // fn B.F() {}
  87. return LookupNameInExactScope(context, loc_id, name_id, scope_id,
  88. context.name_scopes().Get(scope_id),
  89. /*is_being_declared=*/true);
  90. }
  91. }
  92. auto LookupUnqualifiedName(Context& context, SemIR::LocId loc_id,
  93. SemIR::NameId name_id, bool required)
  94. -> LookupResult {
  95. // TODO: Check for shadowed lookup results.
  96. // Find the results from ancestor lexical scopes. These will be combined with
  97. // results from non-lexical scopes such as namespaces and classes.
  98. auto [lexical_result, non_lexical_scopes] =
  99. context.scope_stack().LookupInLexicalScopes(
  100. name_id, loc_id, IsCurrentPositionReachable(context));
  101. // Walk the non-lexical scopes and perform lookups into each of them.
  102. for (auto [index, lookup_scope_id, specific_id] :
  103. llvm::reverse(non_lexical_scopes)) {
  104. if (auto non_lexical_result = LookupQualifiedName(
  105. context, loc_id, name_id,
  106. LookupScope{.name_scope_id = lookup_scope_id,
  107. .specific_id = specific_id,
  108. // A non-lexical lookup does not know what `Self` will
  109. // be; it remains symbolic if needed.
  110. .self_const_id = SemIR::ConstantId::None},
  111. /*required=*/false);
  112. non_lexical_result.scope_result.is_found()) {
  113. // In an interface definition, replace associated entity `M` with
  114. // `Self.M` (where the `Self` is the `Self` of the interface).
  115. const auto& scope = context.name_scopes().Get(lookup_scope_id);
  116. if (scope.is_interface_definition()) {
  117. SemIR::InstId target_inst_id =
  118. non_lexical_result.scope_result.target_inst_id();
  119. if (auto assoc_type =
  120. context.types().TryGetAs<SemIR::AssociatedEntityType>(
  121. SemIR::GetTypeOfInstInSpecific(
  122. context.sem_ir(), non_lexical_result.specific_id,
  123. target_inst_id))) {
  124. auto interface_decl =
  125. context.insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  126. scope.inst_id());
  127. const auto& interface =
  128. context.interfaces().Get(interface_decl.interface_id);
  129. SemIR::InstId result_inst_id = GetAssociatedValue(
  130. context, loc_id, interface.self_param_id,
  131. SemIR::GetConstantValueInSpecific(context.sem_ir(),
  132. non_lexical_result.specific_id,
  133. target_inst_id),
  134. assoc_type->GetSpecificInterface());
  135. non_lexical_result = {
  136. .specific_id = SemIR::SpecificId::None,
  137. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  138. result_inst_id,
  139. non_lexical_result.scope_result.access_kind())};
  140. }
  141. }
  142. return non_lexical_result;
  143. }
  144. }
  145. if (lexical_result == SemIR::InstId::InitTombstone) {
  146. CARBON_DIAGNOSTIC(UsedBeforeInitialization, Error,
  147. "`{0}` used before initialization", SemIR::NameId);
  148. context.emitter().Emit(loc_id, UsedBeforeInitialization, name_id);
  149. return {.specific_id = SemIR::SpecificId::None,
  150. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  151. }
  152. if (lexical_result.has_value()) {
  153. // A lexical scope never needs an associated specific. If there's a
  154. // lexically enclosing generic, then it also encloses the point of use of
  155. // the name.
  156. return {.specific_id = SemIR::SpecificId::None,
  157. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  158. lexical_result, SemIR::AccessKind::Public)};
  159. }
  160. // We didn't find anything at all.
  161. if (required) {
  162. DiagnoseNameNotFound(context, loc_id, name_id);
  163. }
  164. // TODO: Should this return MakeNotFound if `required` is false, so that
  165. // `is_found()` would be false?
  166. return {.specific_id = SemIR::SpecificId::None,
  167. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  168. }
  169. auto LookupNameInExactScope(Context& context, SemIR::LocId loc_id,
  170. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  171. SemIR::NameScope& scope, bool is_being_declared)
  172. -> SemIR::ScopeLookupResult {
  173. if (auto entry_id = is_being_declared
  174. ? scope.Lookup(name_id)
  175. : scope.LookupOrPoison(loc_id, name_id)) {
  176. auto lookup_result = scope.GetEntry(*entry_id).result;
  177. if (!lookup_result.is_poisoned()) {
  178. LoadImportRef(context, lookup_result.target_inst_id());
  179. }
  180. return lookup_result;
  181. }
  182. if (!scope.import_ir_scopes().empty()) {
  183. // TODO: Enforce other access modifiers for imports.
  184. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  185. ImportNameFromOtherPackage(context, loc_id, scope_id,
  186. scope.import_ir_scopes(), name_id),
  187. SemIR::AccessKind::Public);
  188. }
  189. if (scope.is_cpp_scope()) {
  190. return ImportNameFromCpp(context, loc_id, scope_id, name_id);
  191. }
  192. return SemIR::ScopeLookupResult::MakeNotFound();
  193. }
  194. // Prints diagnostics on invalid qualified name access.
  195. static auto DiagnoseInvalidQualifiedNameAccess(
  196. Context& context, SemIR::LocId loc_id, SemIR::LocId member_loc_id,
  197. SemIR::NameId name_id, SemIR::AccessKind access_kind, bool is_parent_access,
  198. AccessInfo access_info) -> void {
  199. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  200. context.constant_values().GetInstId(access_info.constant_id));
  201. if (!class_type) {
  202. return;
  203. }
  204. // TODO: Support scoped entities other than just classes.
  205. const auto& class_info = context.classes().Get(class_type->class_id);
  206. auto parent_type_id = class_info.self_type_id;
  207. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  208. if (auto base_type_id =
  209. class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
  210. base_type_id.has_value()) {
  211. parent_type_id = base_type_id;
  212. } else if (auto adapted_type_id = class_info.GetAdaptedType(
  213. context.sem_ir(), class_type->specific_id);
  214. adapted_type_id.has_value()) {
  215. parent_type_id = adapted_type_id;
  216. } else {
  217. CARBON_FATAL("Expected parent for parent access");
  218. }
  219. }
  220. CARBON_DIAGNOSTIC(
  221. ClassInvalidMemberAccess, Error,
  222. "cannot access {0:private|protected} member `{1}` of type {2}",
  223. Diagnostics::BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  224. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  225. context.emitter()
  226. .Build(loc_id, ClassInvalidMemberAccess,
  227. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  228. .Note(member_loc_id, ClassMemberDeclaration)
  229. .Emit();
  230. }
  231. // Returns whether the access is prohibited by the access modifiers.
  232. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  233. SemIR::AccessKind access_kind,
  234. bool is_parent_access) -> bool {
  235. if (!access_info) {
  236. return false;
  237. }
  238. switch (access_kind) {
  239. case SemIR::AccessKind::Public:
  240. return false;
  241. case SemIR::AccessKind::Protected:
  242. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  243. case SemIR::AccessKind::Private:
  244. return access_info->highest_allowed_access !=
  245. SemIR::AccessKind::Private ||
  246. is_parent_access;
  247. }
  248. }
  249. auto CheckAccess(Context& context, SemIR::LocId loc_id,
  250. SemIR::LocId member_loc_id, SemIR::NameId name_id,
  251. SemIR::AccessKind access_kind, bool is_parent_access,
  252. AccessInfo access_info) -> void {
  253. if (IsAccessProhibited(access_info, access_kind, is_parent_access)) {
  254. DiagnoseInvalidQualifiedNameAccess(context, loc_id, member_loc_id, name_id,
  255. access_kind, is_parent_access,
  256. access_info);
  257. }
  258. }
  259. // Information regarding a prohibited access.
  260. struct ProhibitedAccessInfo {
  261. // The resulting inst of the lookup.
  262. SemIR::InstId scope_result_id;
  263. // The access kind of the lookup.
  264. SemIR::AccessKind access_kind;
  265. // If the lookup is from an extended scope. For example, if this is a base
  266. // class member access from a class that extends it.
  267. bool is_parent_access;
  268. };
  269. static auto GetSelfFacetForInterfaceFromLookupSelfType(
  270. Context& context, const SemIR::GenericId generic_with_self_id,
  271. SemIR::ConstantId self_type_const_id) -> SemIR::ConstantId {
  272. if (!self_type_const_id.has_value()) {
  273. // In a lookup into a non-lexical scope, there is no self-type from the
  274. // lookup for the interface-with-self specific. So the self-type we use is
  275. // the abstract symbolic Self from the self specific of the
  276. // interface-with-self.
  277. auto self_specific_args_id = context.specifics().GetArgsOrEmpty(
  278. context.generics().GetSelfSpecific(generic_with_self_id));
  279. auto self_specific_args = context.inst_blocks().Get(self_specific_args_id);
  280. return context.constant_values().Get(self_specific_args.back());
  281. }
  282. if (context.insts().Is<SemIR::FacetType>(
  283. context.constant_values().GetInstId(self_type_const_id))) {
  284. // We are looking directly in a facet type, like `I.F` for an interface `I`,
  285. // which means there is no self-type from the lookup for the
  286. // interface-with-self specific. So the self-type we use is the abstract
  287. // symbolic Self from the self specific of the interface-with-self.
  288. auto self_specific_args_id = context.specifics().GetArgsOrEmpty(
  289. context.generics().GetSelfSpecific(generic_with_self_id));
  290. auto self_specific_args = context.inst_blocks().Get(self_specific_args_id);
  291. return context.constant_values().Get(self_specific_args.back());
  292. }
  293. // Extended name lookup into a type, like `x.F`, can find a facet
  294. // type extended scope from the type of `x`. The type of `x` maybe a
  295. // facet converted to a type, so drop the `as type` conversion if
  296. // so.
  297. auto canonical_facet_or_type =
  298. GetCanonicalFacetOrTypeValue(context, self_type_const_id);
  299. auto type_of_canonical_facet_or_type =
  300. context.insts()
  301. .Get(context.constant_values().GetInstId(canonical_facet_or_type))
  302. .type_id();
  303. if (type_of_canonical_facet_or_type == SemIR::TypeType::TypeId) {
  304. // If we still have a type, turn it into a facet for use in the
  305. // interface-with-self specific.
  306. return GetConstantFacetValueForType(
  307. context, context.types().GetAsTypeInstId(
  308. context.constant_values().GetInstId(self_type_const_id)));
  309. }
  310. // We have a facet for the self-type (or perhaps an ErrorInst), which we can
  311. // use directly in the interface-with-self specific.
  312. return canonical_facet_or_type;
  313. }
  314. auto AppendLookupScopesForConstant(Context& context, SemIR::LocId loc_id,
  315. SemIR::ConstantId lookup_const_id,
  316. SemIR::ConstantId self_type_const_id,
  317. llvm::SmallVector<LookupScope>* scopes)
  318. -> bool {
  319. auto lookup_inst_id = context.constant_values().GetInstId(lookup_const_id);
  320. auto lookup = context.insts().Get(lookup_inst_id);
  321. if (auto ns = lookup.TryAs<SemIR::Namespace>()) {
  322. scopes->push_back(LookupScope{.name_scope_id = ns->name_scope_id,
  323. .specific_id = SemIR::SpecificId::None,
  324. .self_const_id = SemIR::ConstantId::None});
  325. return true;
  326. }
  327. if (auto class_ty = lookup.TryAs<SemIR::ClassType>()) {
  328. // TODO: Allow name lookup into classes that are being defined even if they
  329. // are not complete.
  330. RequireCompleteType(
  331. context, context.types().GetTypeIdForTypeConstantId(lookup_const_id),
  332. loc_id, [&](auto& builder) {
  333. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Context,
  334. "member access into incomplete class {0}",
  335. InstIdAsType);
  336. builder.Context(loc_id, QualifiedExprInIncompleteClassScope,
  337. lookup_inst_id);
  338. });
  339. auto& class_info = context.classes().Get(class_ty->class_id);
  340. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  341. .specific_id = class_ty->specific_id,
  342. .self_const_id = self_type_const_id});
  343. return true;
  344. }
  345. // Extended scopes may point to a FacetType.
  346. if (auto facet_type = lookup.TryAs<SemIR::FacetType>()) {
  347. // TODO: Allow name lookup into facet types that are being defined even if
  348. // they are not complete.
  349. if (RequireCompleteType(
  350. context,
  351. context.types().GetTypeIdForTypeConstantId(lookup_const_id), loc_id,
  352. [&](auto& builder) {
  353. CARBON_DIAGNOSTIC(
  354. QualifiedExprInIncompleteFacetTypeScope, Context,
  355. "member access into incomplete facet type {0}", InstIdAsType);
  356. builder.Context(loc_id, QualifiedExprInIncompleteFacetTypeScope,
  357. lookup_inst_id);
  358. })) {
  359. auto facet_type_info =
  360. context.facet_types().Get(facet_type->facet_type_id);
  361. // Name lookup into "extend" constraints but not "self impls" constraints.
  362. for (const auto& extend : facet_type_info.extend_constraints) {
  363. auto& interface = context.interfaces().Get(extend.interface_id);
  364. // We need to build the inner interface-with-self specific. To do that
  365. // we need to determine the self facet value to use.
  366. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  367. context, interface.generic_with_self_id, self_type_const_id);
  368. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  369. context, loc_id, interface.generic_id,
  370. interface.generic_with_self_id, extend.specific_id, self_facet);
  371. scopes->push_back({.name_scope_id = interface.scope_with_self_id,
  372. .specific_id = interface_with_self_specific_id,
  373. .self_const_id = self_type_const_id});
  374. }
  375. for (const auto& extend : facet_type_info.extend_named_constraints) {
  376. auto& constraint =
  377. context.named_constraints().Get(extend.named_constraint_id);
  378. // We need to build the inner constraint-with-self specific. To do that
  379. // we need to determine the self facet value to use.
  380. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  381. context, constraint.generic_with_self_id, self_type_const_id);
  382. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  383. context, loc_id, constraint.generic_id,
  384. constraint.generic_with_self_id, extend.specific_id, self_facet);
  385. scopes->push_back({.name_scope_id = constraint.scope_with_self_id,
  386. .specific_id = constraint_with_self_specific_id,
  387. .self_const_id = self_type_const_id});
  388. }
  389. } else {
  390. // Lookup into this scope should fail without producing an error since
  391. // `RequireCompleteFacetType` has already issued a diagnostic.
  392. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  393. .specific_id = SemIR::SpecificId::None,
  394. .self_const_id = SemIR::ConstantId::None});
  395. }
  396. return true;
  397. }
  398. if (lookup_const_id == SemIR::ErrorInst::ConstantId) {
  399. // Lookup into this scope should fail without producing an error.
  400. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  401. .specific_id = SemIR::SpecificId::None,
  402. .self_const_id = SemIR::ConstantId::None});
  403. return true;
  404. }
  405. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  406. // treat it as a name scope, even if it doesn't have members. For example,
  407. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  408. // there's no name `X` in `type`.
  409. return false;
  410. }
  411. // Prints a diagnostic for a missing qualified name.
  412. static auto DiagnoseMemberNameNotFound(
  413. Context& context, SemIR::LocId loc_id, SemIR::NameId name_id,
  414. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  415. if (lookup_scopes.size() == 1 &&
  416. lookup_scopes.front().name_scope_id.has_value()) {
  417. if (auto specific_id = lookup_scopes.front().specific_id;
  418. specific_id.has_value()) {
  419. CARBON_DIAGNOSTIC(MemberNameNotFoundInSpecificScope, Error,
  420. "member name `{0}` not found in {1}", SemIR::NameId,
  421. SemIR::SpecificId);
  422. context.emitter().Emit(loc_id, MemberNameNotFoundInSpecificScope, name_id,
  423. specific_id);
  424. } else {
  425. auto scope_inst_id = context.name_scopes()
  426. .Get(lookup_scopes.front().name_scope_id)
  427. .inst_id();
  428. CARBON_DIAGNOSTIC(MemberNameNotFoundInInstScope, Error,
  429. "member name `{0}` not found in {1}", SemIR::NameId,
  430. InstIdAsType);
  431. context.emitter().Emit(loc_id, MemberNameNotFoundInInstScope, name_id,
  432. scope_inst_id);
  433. }
  434. return;
  435. }
  436. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  437. SemIR::NameId);
  438. context.emitter().Emit(loc_id, MemberNameNotFound, name_id);
  439. }
  440. auto LookupQualifiedName(Context& context, SemIR::LocId loc_id,
  441. SemIR::NameId name_id,
  442. llvm::ArrayRef<LookupScope> lookup_scopes,
  443. bool required, std::optional<AccessInfo> access_info)
  444. -> LookupResult {
  445. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  446. // TODO: Support reporting of multiple prohibited access.
  447. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  448. LookupResult result = {
  449. .specific_id = SemIR::SpecificId::None,
  450. .scope_result = SemIR::ScopeLookupResult::MakeNotFound()};
  451. auto parent_const_id = SemIR::ConstantId::None;
  452. bool has_error = false;
  453. bool is_parent_access = false;
  454. // Walk this scope and, if nothing is found here, the scopes it extends.
  455. while (!scopes.empty()) {
  456. auto [scope_id, specific_id, self_const_id] = scopes.pop_back_val();
  457. if (!scope_id.has_value()) {
  458. has_error = true;
  459. continue;
  460. }
  461. auto& name_scope = context.name_scopes().Get(scope_id);
  462. has_error |= name_scope.has_error();
  463. const SemIR::ScopeLookupResult scope_result =
  464. LookupNameInExactScope(context, loc_id, name_id, scope_id, name_scope);
  465. SemIR::AccessKind access_kind = scope_result.access_kind();
  466. if (is_parent_access && scope_result.is_found() &&
  467. !access_info.has_value()) {
  468. access_info =
  469. AccessInfo{.constant_id = parent_const_id,
  470. .highest_allowed_access = SemIR::AccessKind::Protected};
  471. }
  472. auto is_access_prohibited =
  473. IsAccessProhibited(access_info, access_kind, is_parent_access);
  474. // Keep track of prohibited accesses, this will be useful for reporting
  475. // multiple prohibited accesses if we can't find a suitable lookup.
  476. if (is_access_prohibited) {
  477. prohibited_accesses.push_back({
  478. .scope_result_id = scope_result.target_inst_id(),
  479. .access_kind = access_kind,
  480. .is_parent_access = is_parent_access,
  481. });
  482. }
  483. if (!scope_result.is_found() || is_access_prohibited) {
  484. // If nothing is found in this scope or if we encountered an invalid
  485. // access, look in its extended scopes.
  486. const auto& extended = name_scope.extended_scopes();
  487. scopes.reserve(scopes.size() + extended.size());
  488. for (auto extended_id : llvm::reverse(extended)) {
  489. // Substitute into the constant describing the extended scope to
  490. // determine its corresponding specific.
  491. CARBON_CHECK(extended_id.has_value());
  492. LoadImportRef(context, extended_id);
  493. SemIR::ConstantId const_id = GetConstantValueInSpecific(
  494. context.sem_ir(), specific_id, extended_id);
  495. if (!AppendLookupScopesForConstant(context, loc_id, const_id,
  496. self_const_id, &scopes)) {
  497. // TODO: Handle case where we have a symbolic type and instead should
  498. // look in its type.
  499. }
  500. }
  501. is_parent_access |= !extended.empty();
  502. parent_const_id = context.constant_values().Get(name_scope.inst_id());
  503. continue;
  504. }
  505. // If this is our second lookup result, diagnose an ambiguity.
  506. if (result.scope_result.is_found()) {
  507. CARBON_DIAGNOSTIC(
  508. NameAmbiguousDueToExtend, Error,
  509. "ambiguous use of name `{0}` found in multiple extended scopes",
  510. SemIR::NameId);
  511. context.emitter().Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  512. // TODO: Add notes pointing to the scopes.
  513. return {.specific_id = SemIR::SpecificId::None,
  514. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  515. }
  516. result.scope_result = scope_result;
  517. result.specific_id = specific_id;
  518. }
  519. if ((!prohibited_accesses.empty() || required) &&
  520. !result.scope_result.is_found()) {
  521. if (!has_error) {
  522. if (prohibited_accesses.empty()) {
  523. DiagnoseMemberNameNotFound(context, loc_id, name_id, lookup_scopes);
  524. } else {
  525. // TODO: We should report multiple prohibited accesses in case we don't
  526. // find a valid lookup. Reporting the last one should suffice for now.
  527. auto [scope_result_id, access_kind, is_parent_access] =
  528. prohibited_accesses.back();
  529. // Note, `access_info` is guaranteed to have a value here, since
  530. // `prohibited_accesses` is non-empty.
  531. DiagnoseInvalidQualifiedNameAccess(
  532. context, loc_id, SemIR::LocId(scope_result_id), name_id,
  533. access_kind, is_parent_access, *access_info);
  534. }
  535. }
  536. CARBON_CHECK(!result.scope_result.is_poisoned());
  537. return {.specific_id = SemIR::SpecificId::None,
  538. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  539. }
  540. return result;
  541. }
  542. // Returns a `Core.<qualifiers>` name for diagnostics.
  543. static auto GetCoreQualifiedName(llvm::ArrayRef<CoreIdentifier> qualifiers)
  544. -> std::string {
  545. RawStringOstream str;
  546. str << "Core";
  547. for (auto qualifier : qualifiers) {
  548. str << "." << qualifier;
  549. }
  550. return str.TakeStr();
  551. }
  552. // Returns the scope of the Core package, or `None` if it's not found.
  553. //
  554. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  555. // name lookup to find it.
  556. static auto GetCorePackage(Context& context, SemIR::LocId loc_id,
  557. llvm::ArrayRef<CoreIdentifier> qualifiers)
  558. -> SemIR::NameScopeId {
  559. if (context.name_scopes().IsCorePackage(SemIR::NameScopeId::Package)) {
  560. return SemIR::NameScopeId::Package;
  561. }
  562. // Look up `package.Core`.
  563. auto core_scope_result = LookupNameInExactScope(
  564. context, loc_id, SemIR::NameId::Core, SemIR::NameScopeId::Package,
  565. context.name_scopes().Get(SemIR::NameScopeId::Package));
  566. if (core_scope_result.is_found()) {
  567. // We expect it to be a namespace.
  568. if (auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(
  569. core_scope_result.target_inst_id())) {
  570. // TODO: Decide whether to allow the case where `Core` is not a package.
  571. return namespace_inst->name_scope_id;
  572. }
  573. }
  574. CARBON_DIAGNOSTIC(
  575. CoreNotFound, Error,
  576. "`{0}` implicitly referenced here, but package `Core` not found",
  577. std::string);
  578. context.emitter().Emit(loc_id, CoreNotFound,
  579. GetCoreQualifiedName(qualifiers));
  580. return SemIR::NameScopeId::None;
  581. }
  582. auto LookupNameInCore(Context& context, SemIR::LocId loc_id,
  583. llvm::ArrayRef<CoreIdentifier> qualifiers)
  584. -> SemIR::InstId {
  585. CARBON_CHECK(!qualifiers.empty());
  586. auto core_package_id = GetCorePackage(context, loc_id, qualifiers);
  587. if (!core_package_id.has_value()) {
  588. return SemIR::ErrorInst::InstId;
  589. }
  590. auto inst_id = SemIR::InstId::None;
  591. for (auto qualifier : qualifiers) {
  592. auto name_id = context.core_identifiers().AddNameId(qualifier);
  593. auto scope_id = SemIR::NameScopeId::None;
  594. if (inst_id.has_value()) {
  595. auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(inst_id);
  596. if (namespace_inst) {
  597. scope_id = namespace_inst->name_scope_id;
  598. }
  599. } else {
  600. scope_id = core_package_id;
  601. }
  602. auto scope_result =
  603. scope_id.has_value()
  604. ? LookupNameInExactScope(context, loc_id, name_id, scope_id,
  605. context.name_scopes().Get(scope_id))
  606. : SemIR::ScopeLookupResult::MakeNotFound();
  607. if (!scope_result.is_found()) {
  608. CARBON_DIAGNOSTIC(CoreNameNotFound, Error,
  609. "name `{0}` implicitly referenced here, but not found",
  610. std::string);
  611. context.emitter().Emit(loc_id, CoreNameNotFound,
  612. GetCoreQualifiedName(qualifiers));
  613. return SemIR::ErrorInst::InstId;
  614. }
  615. // Look through import_refs and aliases.
  616. inst_id = context.constant_values().GetConstantInstId(
  617. scope_result.target_inst_id());
  618. }
  619. return inst_id;
  620. }
  621. auto DiagnoseDuplicateName(Context& context, SemIR::NameId name_id,
  622. SemIR::LocId dup_def, SemIR::LocId prev_def)
  623. -> void {
  624. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  625. "duplicate name `{0}` being declared in the same scope",
  626. SemIR::NameId);
  627. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  628. context.emitter()
  629. .Build(dup_def, NameDeclDuplicate, name_id)
  630. .Note(prev_def, NameDeclPrevious)
  631. .Emit();
  632. }
  633. auto DiagnosePoisonedName(Context& context, SemIR::NameId name_id,
  634. SemIR::LocId poisoning_loc_id,
  635. SemIR::LocId decl_name_loc_id) -> void {
  636. CARBON_CHECK(poisoning_loc_id.has_value(),
  637. "Trying to diagnose poisoned name with no poisoning location");
  638. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  639. "name `{0}` used before it was declared", SemIR::NameId);
  640. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  641. context.emitter()
  642. .Build(poisoning_loc_id, NameUseBeforeDecl, name_id)
  643. .Note(decl_name_loc_id, NameUseBeforeDeclNote)
  644. .Emit();
  645. }
  646. auto DiagnoseNameNotFound(Context& context, SemIR::LocId loc_id,
  647. SemIR::NameId name_id) -> void {
  648. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  649. context.emitter().Emit(loc_id, NameNotFound, name_id);
  650. }
  651. } // namespace Carbon::Check