name_lookup.cpp 19 KB

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