context.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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/context.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "common/check.h"
  9. #include "common/vlog.h"
  10. #include "llvm/ADT/Sequence.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/generic_region_stack.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/import_ref.h"
  17. #include "toolchain/check/inst_block_stack.h"
  18. #include "toolchain/check/merge.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/diagnostics/format_providers.h"
  22. #include "toolchain/lex/tokenized_buffer.h"
  23. #include "toolchain/parse/node_ids.h"
  24. #include "toolchain/parse/node_kind.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/formatter.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/import_ir.h"
  30. #include "toolchain/sem_ir/inst.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. Context::Context(DiagnosticEmitter* emitter,
  37. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter,
  38. SemIR::File* sem_ir, int imported_ir_count, int total_ir_count,
  39. llvm::raw_ostream* vlog_stream)
  40. : emitter_(emitter),
  41. tree_and_subtrees_getter_(tree_and_subtrees_getter),
  42. sem_ir_(sem_ir),
  43. vlog_stream_(vlog_stream),
  44. node_stack_(sem_ir->parse_tree(), vlog_stream),
  45. inst_block_stack_("inst_block_stack_", *sem_ir, vlog_stream),
  46. pattern_block_stack_("pattern_block_stack_", *sem_ir, vlog_stream),
  47. param_and_arg_refs_stack_(*sem_ir, vlog_stream, node_stack_),
  48. args_type_info_stack_("args_type_info_stack_", *sem_ir, vlog_stream),
  49. decl_name_stack_(this),
  50. scope_stack_(sem_ir_),
  51. vtable_stack_("vtable_stack_", *sem_ir, vlog_stream),
  52. global_init_(this),
  53. region_stack_(
  54. [this](SemIRLoc loc, std::string label) { TODO(loc, label); }) {
  55. // Prepare fields which relate to the number of IRs available for import.
  56. import_irs().Reserve(imported_ir_count);
  57. import_ir_constant_values_.reserve(imported_ir_count);
  58. check_ir_map_.resize(total_ir_count, SemIR::ImportIRId::None);
  59. // Map the builtin `<error>` and `type` type constants to their corresponding
  60. // special `TypeId` values.
  61. type_ids_for_type_constants_.Insert(
  62. SemIR::ConstantId::ForTemplateConstant(SemIR::ErrorInst::SingletonInstId),
  63. SemIR::ErrorInst::SingletonTypeId);
  64. type_ids_for_type_constants_.Insert(
  65. SemIR::ConstantId::ForTemplateConstant(SemIR::TypeType::SingletonInstId),
  66. SemIR::TypeType::SingletonTypeId);
  67. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  68. // in the right places.
  69. generic_region_stack().Push();
  70. }
  71. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  72. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  73. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  74. return false;
  75. }
  76. auto Context::VerifyOnFinish() -> void {
  77. // Information in all the various context objects should be cleaned up as
  78. // various pieces of context go out of scope. At this point, nothing should
  79. // remain.
  80. // node_stack_ will still contain top-level entities.
  81. inst_block_stack_.VerifyOnFinish();
  82. pattern_block_stack_.VerifyOnFinish();
  83. param_and_arg_refs_stack_.VerifyOnFinish();
  84. args_type_info_stack_.VerifyOnFinish();
  85. CARBON_CHECK(struct_type_fields_stack_.empty());
  86. // TODO: Add verification for decl_name_stack_ and
  87. // decl_introducer_state_stack_.
  88. scope_stack_.VerifyOnFinish();
  89. // TODO: Add verification for generic_region_stack_.
  90. }
  91. auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
  92. -> SemIR::InstId {
  93. if (loc_id_and_inst.loc_id.is_implicit()) {
  94. auto const_id =
  95. TryEvalInst(*this, SemIR::InstId::None, loc_id_and_inst.inst);
  96. if (const_id.has_value()) {
  97. CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
  98. return constant_values().GetInstId(const_id);
  99. }
  100. }
  101. // TODO: For an implicit instruction, this reattempts evaluation.
  102. return AddInst(loc_id_and_inst);
  103. }
  104. // Finish producing an instruction. Set its constant value, and register it in
  105. // any applicable instruction lists.
  106. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  107. GenericRegionStack::DependencyKind dep_kind =
  108. GenericRegionStack::DependencyKind::None;
  109. // If the instruction has a symbolic constant type, track that we need to
  110. // substitute into it.
  111. if (constant_values().DependsOnGenericParameter(
  112. types().GetConstantId(inst.type_id()))) {
  113. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  114. }
  115. // If the instruction has a constant value, compute it.
  116. auto const_id = TryEvalInst(*this, inst_id, inst);
  117. constant_values().Set(inst_id, const_id);
  118. if (const_id.is_constant()) {
  119. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  120. constant_values().GetInstId(const_id));
  121. // If the constant value is symbolic, track that we need to substitute into
  122. // it.
  123. if (constant_values().DependsOnGenericParameter(const_id)) {
  124. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  125. }
  126. }
  127. // Keep track of dependent instructions.
  128. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  129. // TODO: Also check for template-dependent instructions.
  130. generic_region_stack().AddDependentInst(
  131. {.inst_id = inst_id, .kind = dep_kind});
  132. }
  133. }
  134. // Returns whether a parse node associated with an imported instruction of kind
  135. // `imported_kind` is usable as the location of a corresponding local
  136. // instruction of kind `local_kind`.
  137. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  138. SemIR::InstKind local_kind) -> bool {
  139. if (imported_kind == local_kind) {
  140. return true;
  141. }
  142. if (imported_kind == SemIR::ImportDecl::Kind &&
  143. local_kind == SemIR::Namespace::Kind) {
  144. static_assert(
  145. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  146. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  147. return true;
  148. }
  149. return false;
  150. }
  151. auto Context::CheckCompatibleImportedNodeKind(
  152. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  153. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  154. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  155. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  156. CARBON_CHECK(
  157. HasCompatibleImportedNodeKind(imported_kind, kind),
  158. "Node of kind {0} created with location of imported node of kind {1}",
  159. kind, imported_kind);
  160. }
  161. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  162. -> SemIR::InstId {
  163. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  164. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  165. constant_values().Set(inst_id, SemIR::ConstantId::None);
  166. return inst_id;
  167. }
  168. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  169. -> SemIR::InstId {
  170. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  171. inst_block_stack_.AddInstId(inst_id);
  172. return inst_id;
  173. }
  174. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  175. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  176. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  177. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  178. FinishInst(inst_id, loc_id_and_inst.inst);
  179. }
  180. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  181. SemIR::Inst inst) -> void {
  182. sem_ir().insts().Set(inst_id, inst);
  183. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  184. FinishInst(inst_id, inst);
  185. }
  186. auto Context::ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  187. SemIR::Inst inst) -> void {
  188. auto old_const_id = sem_ir().constant_values().Get(inst_id);
  189. sem_ir().insts().Set(inst_id, inst);
  190. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  191. auto new_const_id = TryEvalInst(*this, inst_id, inst);
  192. CARBON_CHECK(old_const_id == new_const_id);
  193. }
  194. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  195. -> void {
  196. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  197. "duplicate name being declared in the same scope");
  198. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  199. emitter_->Build(dup_def, NameDeclDuplicate)
  200. .Note(prev_def, NameDeclPrevious)
  201. .Emit();
  202. }
  203. auto Context::DiagnosePoisonedName(SemIR::LocId poisoning_loc_id,
  204. SemIR::InstId decl_inst_id) -> void {
  205. CARBON_CHECK(poisoning_loc_id.has_value(),
  206. "Trying to diagnose poisoned name with no poisoning location");
  207. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  208. "name used before it was declared");
  209. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  210. emitter_->Build(poisoning_loc_id, NameUseBeforeDecl)
  211. .Note(decl_inst_id, NameUseBeforeDeclNote)
  212. .Emit();
  213. }
  214. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  215. -> void {
  216. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  217. emitter_->Emit(loc, NameNotFound, name_id);
  218. }
  219. auto Context::DiagnoseMemberNameNotFound(
  220. SemIRLoc loc, SemIR::NameId name_id,
  221. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  222. if (lookup_scopes.size() == 1 &&
  223. lookup_scopes.front().name_scope_id.has_value()) {
  224. auto specific_id = lookup_scopes.front().specific_id;
  225. auto scope_inst_id =
  226. specific_id.has_value()
  227. ? GetInstForSpecific(*this, specific_id)
  228. : name_scopes().Get(lookup_scopes.front().name_scope_id).inst_id();
  229. CARBON_DIAGNOSTIC(MemberNameNotFoundInScope, Error,
  230. "member name `{0}` not found in {1}", SemIR::NameId,
  231. InstIdAsType);
  232. emitter_->Emit(loc, MemberNameNotFoundInScope, name_id, scope_inst_id);
  233. return;
  234. }
  235. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  236. SemIR::NameId);
  237. emitter_->Emit(loc, MemberNameNotFound, name_id);
  238. }
  239. auto Context::NoteAbstractClass(SemIR::ClassId class_id,
  240. DiagnosticBuilder& builder) -> void {
  241. const auto& class_info = classes().Get(class_id);
  242. CARBON_CHECK(
  243. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  244. "Class is not abstract");
  245. CARBON_DIAGNOSTIC(ClassAbstractHere, Note,
  246. "class was declared abstract here");
  247. builder.Note(class_info.definition_id, ClassAbstractHere);
  248. }
  249. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  250. DiagnosticBuilder& builder) -> void {
  251. const auto& class_info = classes().Get(class_id);
  252. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  253. if (class_info.has_definition_started()) {
  254. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  255. "class is incomplete within its definition");
  256. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  257. } else {
  258. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  259. "class was forward declared here");
  260. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  261. }
  262. }
  263. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  264. DiagnosticBuilder& builder) -> void {
  265. const auto& interface_info = interfaces().Get(interface_id);
  266. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  267. if (interface_info.is_being_defined()) {
  268. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  269. "interface is currently being defined");
  270. builder.Note(interface_info.definition_id,
  271. InterfaceUndefinedWithinDefinition);
  272. } else {
  273. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  274. "interface was forward declared here");
  275. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  276. }
  277. }
  278. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id,
  279. ScopeIndex scope_index) -> void {
  280. if (auto existing =
  281. scope_stack().LookupOrAddName(name_id, target_id, scope_index);
  282. existing.has_value()) {
  283. DiagnoseDuplicateName(target_id, existing);
  284. }
  285. }
  286. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  287. SemIR::NameScopeId scope_id,
  288. ScopeIndex scope_index)
  289. -> SemIR::ScopeLookupResult {
  290. if (!scope_id.has_value()) {
  291. // Look for a name in the specified scope or a scope nested within it only.
  292. // There are two cases where the name would be in an outer scope:
  293. //
  294. // - The name is the sole component of the declared name:
  295. //
  296. // class A;
  297. // fn F() {
  298. // class A;
  299. // }
  300. //
  301. // In this case, the inner A is not the same class as the outer A, so
  302. // lookup should not find the outer A.
  303. //
  304. // - The name is a qualifier of some larger declared name:
  305. //
  306. // class A { class B; }
  307. // fn F() {
  308. // class A.B {}
  309. // }
  310. //
  311. // In this case, we're not in the correct scope to define a member of
  312. // class A, so we should reject, and we achieve this by not finding the
  313. // name A from the outer scope.
  314. //
  315. // There is also one case where the name would be in an inner scope:
  316. //
  317. // - The name is redeclared by a parameter of the same entity:
  318. //
  319. // fn F() {
  320. // class C(C:! type);
  321. // }
  322. //
  323. // In this case, the class C is not a redeclaration of its parameter, but
  324. // we find the parameter in order to diagnose a redeclaration error.
  325. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  326. scope_stack().LookupInLexicalScopesWithin(name_id, scope_index),
  327. SemIR::AccessKind::Public);
  328. } else {
  329. // We do not look into `extend`ed scopes here. A qualified name in a
  330. // declaration must specify the exact scope in which the name was originally
  331. // introduced:
  332. //
  333. // base class A { fn F(); }
  334. // class B { extend base: A; }
  335. //
  336. // // Error, no `F` in `B`.
  337. // fn B.F() {}
  338. return LookupNameInExactScope(loc_id, name_id, scope_id,
  339. name_scopes().Get(scope_id),
  340. /*is_being_declared=*/true);
  341. }
  342. }
  343. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  344. SemIR::NameId name_id, bool required)
  345. -> LookupResult {
  346. // TODO: Check for shadowed lookup results.
  347. // Find the results from ancestor lexical scopes. These will be combined with
  348. // results from non-lexical scopes such as namespaces and classes.
  349. auto [lexical_result, non_lexical_scopes] =
  350. scope_stack().LookupInLexicalScopes(name_id);
  351. // Walk the non-lexical scopes and perform lookups into each of them.
  352. for (auto [index, lookup_scope_id, specific_id] :
  353. llvm::reverse(non_lexical_scopes)) {
  354. if (auto non_lexical_result =
  355. LookupQualifiedName(node_id, name_id,
  356. LookupScope{.name_scope_id = lookup_scope_id,
  357. .specific_id = specific_id},
  358. /*required=*/false);
  359. non_lexical_result.scope_result.is_found()) {
  360. return non_lexical_result;
  361. }
  362. }
  363. if (lexical_result == SemIR::InstId::InitTombstone) {
  364. CARBON_DIAGNOSTIC(UsedBeforeInitialization, Error,
  365. "`{0}` used before initialization", SemIR::NameId);
  366. emitter_->Emit(node_id, UsedBeforeInitialization, name_id);
  367. return {.specific_id = SemIR::SpecificId::None,
  368. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  369. }
  370. if (lexical_result.has_value()) {
  371. // A lexical scope never needs an associated specific. If there's a
  372. // lexically enclosing generic, then it also encloses the point of use of
  373. // the name.
  374. return {.specific_id = SemIR::SpecificId::None,
  375. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  376. lexical_result, SemIR::AccessKind::Public)};
  377. }
  378. // We didn't find anything at all.
  379. if (required) {
  380. DiagnoseNameNotFound(node_id, name_id);
  381. }
  382. return {.specific_id = SemIR::SpecificId::None,
  383. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  384. }
  385. auto Context::LookupNameInExactScope(SemIR::LocId loc_id, SemIR::NameId name_id,
  386. SemIR::NameScopeId scope_id,
  387. SemIR::NameScope& scope,
  388. bool is_being_declared)
  389. -> SemIR::ScopeLookupResult {
  390. if (auto entry_id = is_being_declared
  391. ? scope.Lookup(name_id)
  392. : scope.LookupOrPoison(loc_id, name_id)) {
  393. auto lookup_result = scope.GetEntry(*entry_id).result;
  394. if (!lookup_result.is_poisoned()) {
  395. LoadImportRef(*this, lookup_result.target_inst_id());
  396. }
  397. return lookup_result;
  398. }
  399. if (!scope.import_ir_scopes().empty()) {
  400. // TODO: Enforce other access modifiers for imports.
  401. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  402. ImportNameFromOtherPackage(*this, loc_id, scope_id,
  403. scope.import_ir_scopes(), name_id),
  404. SemIR::AccessKind::Public);
  405. }
  406. return SemIR::ScopeLookupResult::MakeNotFound();
  407. }
  408. // Prints diagnostics on invalid qualified name access.
  409. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  410. SemIR::InstId scope_result_id,
  411. SemIR::NameId name_id,
  412. SemIR::AccessKind access_kind,
  413. bool is_parent_access,
  414. AccessInfo access_info) -> void {
  415. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  416. context.constant_values().GetInstId(access_info.constant_id));
  417. if (!class_type) {
  418. return;
  419. }
  420. // TODO: Support scoped entities other than just classes.
  421. const auto& class_info = context.classes().Get(class_type->class_id);
  422. auto parent_type_id = class_info.self_type_id;
  423. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  424. if (auto base_type_id =
  425. class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
  426. base_type_id.has_value()) {
  427. parent_type_id = base_type_id;
  428. } else if (auto adapted_type_id = class_info.GetAdaptedType(
  429. context.sem_ir(), class_type->specific_id);
  430. adapted_type_id.has_value()) {
  431. parent_type_id = adapted_type_id;
  432. } else {
  433. CARBON_FATAL("Expected parent for parent access");
  434. }
  435. }
  436. CARBON_DIAGNOSTIC(
  437. ClassInvalidMemberAccess, Error,
  438. "cannot access {0:private|protected} member `{1}` of type {2}",
  439. BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  440. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  441. context.emitter()
  442. .Build(loc, ClassInvalidMemberAccess,
  443. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  444. .Note(scope_result_id, ClassMemberDeclaration)
  445. .Emit();
  446. }
  447. // Returns whether the access is prohibited by the access modifiers.
  448. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  449. SemIR::AccessKind access_kind,
  450. bool is_parent_access) -> bool {
  451. if (!access_info) {
  452. return false;
  453. }
  454. switch (access_kind) {
  455. case SemIR::AccessKind::Public:
  456. return false;
  457. case SemIR::AccessKind::Protected:
  458. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  459. case SemIR::AccessKind::Private:
  460. return access_info->highest_allowed_access !=
  461. SemIR::AccessKind::Private ||
  462. is_parent_access;
  463. }
  464. }
  465. // Information regarding a prohibited access.
  466. struct ProhibitedAccessInfo {
  467. // The resulting inst of the lookup.
  468. SemIR::InstId scope_result_id;
  469. // The access kind of the lookup.
  470. SemIR::AccessKind access_kind;
  471. // If the lookup is from an extended scope. For example, if this is a base
  472. // class member access from a class that extends it.
  473. bool is_parent_access;
  474. };
  475. auto Context::AppendLookupScopesForConstant(
  476. SemIR::LocId loc_id, SemIR::ConstantId base_const_id,
  477. llvm::SmallVector<LookupScope>* scopes) -> bool {
  478. auto base_id = constant_values().GetInstId(base_const_id);
  479. auto base = insts().Get(base_id);
  480. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  481. scopes->push_back(
  482. LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  483. .specific_id = SemIR::SpecificId::None});
  484. return true;
  485. }
  486. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  487. RequireDefinedType(
  488. *this, GetTypeIdForTypeConstant(base_const_id), loc_id, [&] {
  489. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  490. "member access into incomplete class {0}",
  491. InstIdAsType);
  492. return emitter().Build(loc_id, QualifiedExprInIncompleteClassScope,
  493. base_id);
  494. });
  495. auto& class_info = classes().Get(base_as_class->class_id);
  496. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  497. .specific_id = base_as_class->specific_id});
  498. return true;
  499. }
  500. if (auto base_as_facet_type = base.TryAs<SemIR::FacetType>()) {
  501. RequireDefinedType(
  502. *this, GetTypeIdForTypeConstant(base_const_id), loc_id, [&] {
  503. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  504. "member access into undefined interface {0}",
  505. InstIdAsType);
  506. return emitter().Build(loc_id, QualifiedExprInUndefinedInterfaceScope,
  507. base_id);
  508. });
  509. const auto& facet_type_info =
  510. facet_types().Get(base_as_facet_type->facet_type_id);
  511. for (auto interface : facet_type_info.impls_constraints) {
  512. auto& interface_info = interfaces().Get(interface.interface_id);
  513. scopes->push_back(LookupScope{.name_scope_id = interface_info.scope_id,
  514. .specific_id = interface.specific_id});
  515. }
  516. return true;
  517. }
  518. if (base_const_id == SemIR::ErrorInst::SingletonConstantId) {
  519. // Lookup into this scope should fail without producing an error.
  520. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  521. .specific_id = SemIR::SpecificId::None});
  522. return true;
  523. }
  524. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  525. // treat it as a name scope, even if it doesn't have members. For example,
  526. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  527. // there's no name `X` in `type`.
  528. return false;
  529. }
  530. auto Context::LookupQualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id,
  531. llvm::ArrayRef<LookupScope> lookup_scopes,
  532. bool required,
  533. std::optional<AccessInfo> access_info)
  534. -> LookupResult {
  535. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  536. // TODO: Support reporting of multiple prohibited access.
  537. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  538. LookupResult result = {
  539. .specific_id = SemIR::SpecificId::None,
  540. .scope_result = SemIR::ScopeLookupResult::MakeNotFound()};
  541. bool has_error = false;
  542. bool is_parent_access = false;
  543. // Walk this scope and, if nothing is found here, the scopes it extends.
  544. while (!scopes.empty()) {
  545. auto [scope_id, specific_id] = scopes.pop_back_val();
  546. if (!scope_id.has_value()) {
  547. has_error = true;
  548. continue;
  549. }
  550. auto& name_scope = name_scopes().Get(scope_id);
  551. has_error |= name_scope.has_error();
  552. const SemIR::ScopeLookupResult scope_result =
  553. LookupNameInExactScope(loc_id, name_id, scope_id, name_scope);
  554. SemIR::AccessKind access_kind = scope_result.access_kind();
  555. auto is_access_prohibited =
  556. IsAccessProhibited(access_info, access_kind, is_parent_access);
  557. // Keep track of prohibited accesses, this will be useful for reporting
  558. // multiple prohibited accesses if we can't find a suitable lookup.
  559. if (is_access_prohibited) {
  560. prohibited_accesses.push_back({
  561. .scope_result_id = scope_result.target_inst_id(),
  562. .access_kind = access_kind,
  563. .is_parent_access = is_parent_access,
  564. });
  565. }
  566. if (!scope_result.is_found() || is_access_prohibited) {
  567. // If nothing is found in this scope or if we encountered an invalid
  568. // access, look in its extended scopes.
  569. const auto& extended = name_scope.extended_scopes();
  570. scopes.reserve(scopes.size() + extended.size());
  571. for (auto extended_id : llvm::reverse(extended)) {
  572. // Substitute into the constant describing the extended scope to
  573. // determine its corresponding specific.
  574. CARBON_CHECK(extended_id.has_value());
  575. LoadImportRef(*this, extended_id);
  576. SemIR::ConstantId const_id =
  577. GetConstantValueInSpecific(sem_ir(), specific_id, extended_id);
  578. DiagnosticAnnotationScope annotate_diagnostics(
  579. &emitter(), [&](auto& builder) {
  580. CARBON_DIAGNOSTIC(FromExtendHere, Note,
  581. "declared as an extended scope here");
  582. builder.Note(extended_id, FromExtendHere);
  583. });
  584. if (!AppendLookupScopesForConstant(loc_id, const_id, &scopes)) {
  585. // TODO: Handle case where we have a symbolic type and instead should
  586. // look in its type.
  587. }
  588. }
  589. is_parent_access |= !extended.empty();
  590. continue;
  591. }
  592. // If this is our second lookup result, diagnose an ambiguity.
  593. if (result.scope_result.is_found()) {
  594. CARBON_DIAGNOSTIC(
  595. NameAmbiguousDueToExtend, Error,
  596. "ambiguous use of name `{0}` found in multiple extended scopes",
  597. SemIR::NameId);
  598. emitter_->Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  599. // TODO: Add notes pointing to the scopes.
  600. return {.specific_id = SemIR::SpecificId::None,
  601. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  602. }
  603. result.scope_result = scope_result;
  604. result.specific_id = specific_id;
  605. }
  606. if (required && !result.scope_result.is_found()) {
  607. if (!has_error) {
  608. if (prohibited_accesses.empty()) {
  609. DiagnoseMemberNameNotFound(loc_id, name_id, lookup_scopes);
  610. } else {
  611. // TODO: We should report multiple prohibited accesses in case we don't
  612. // find a valid lookup. Reporting the last one should suffice for now.
  613. auto [scope_result_id, access_kind, is_parent_access] =
  614. prohibited_accesses.back();
  615. // Note, `access_info` is guaranteed to have a value here, since
  616. // `prohibited_accesses` is non-empty.
  617. DiagnoseInvalidQualifiedNameAccess(*this, loc_id, scope_result_id,
  618. name_id, access_kind,
  619. is_parent_access, *access_info);
  620. }
  621. }
  622. CARBON_CHECK(!result.scope_result.is_poisoned());
  623. return {.specific_id = SemIR::SpecificId::None,
  624. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  625. }
  626. return result;
  627. }
  628. // Returns the scope of the Core package, or `None` if it's not found.
  629. //
  630. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  631. // name lookup to find it.
  632. static auto GetCorePackage(Context& context, SemIR::LocId loc_id,
  633. llvm::StringRef name) -> SemIR::NameScopeId {
  634. auto packaging = context.parse_tree().packaging_decl();
  635. if (packaging && packaging->names.package_id == PackageNameId::Core) {
  636. return SemIR::NameScopeId::Package;
  637. }
  638. auto core_name_id = SemIR::NameId::Core;
  639. // Look up `package.Core`.
  640. auto core_scope_result = context.LookupNameInExactScope(
  641. loc_id, core_name_id, SemIR::NameScopeId::Package,
  642. context.name_scopes().Get(SemIR::NameScopeId::Package));
  643. if (core_scope_result.is_found()) {
  644. // We expect it to be a namespace.
  645. if (auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(
  646. core_scope_result.target_inst_id())) {
  647. // TODO: Decide whether to allow the case where `Core` is not a package.
  648. return namespace_inst->name_scope_id;
  649. }
  650. }
  651. CARBON_DIAGNOSTIC(
  652. CoreNotFound, Error,
  653. "`Core.{0}` implicitly referenced here, but package `Core` not found",
  654. std::string);
  655. context.emitter().Emit(loc_id, CoreNotFound, name.str());
  656. return SemIR::NameScopeId::None;
  657. }
  658. auto Context::LookupNameInCore(SemIR::LocId loc_id, llvm::StringRef name)
  659. -> SemIR::InstId {
  660. auto core_package_id = GetCorePackage(*this, loc_id, name);
  661. if (!core_package_id.has_value()) {
  662. return SemIR::ErrorInst::SingletonInstId;
  663. }
  664. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  665. auto scope_result = LookupNameInExactScope(
  666. loc_id, name_id, core_package_id, name_scopes().Get(core_package_id));
  667. if (!scope_result.is_found()) {
  668. CARBON_DIAGNOSTIC(
  669. CoreNameNotFound, Error,
  670. "name `Core.{0}` implicitly referenced here, but not found",
  671. SemIR::NameId);
  672. emitter_->Emit(loc_id, CoreNameNotFound, name_id);
  673. return SemIR::ErrorInst::SingletonInstId;
  674. }
  675. // Look through import_refs and aliases.
  676. return constant_values().GetConstantInstId(scope_result.target_inst_id());
  677. }
  678. auto Context::Finalize() -> void {
  679. // Pop information for the file-level scope.
  680. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  681. scope_stack().Pop();
  682. // Finalizes the list of exports on the IR.
  683. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  684. // Finalizes the ImportRef inst block.
  685. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  686. // Finalizes __global_init.
  687. global_init_.Finalize();
  688. }
  689. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  690. -> SemIR::TypeId {
  691. CARBON_CHECK(constant_id.is_constant(),
  692. "Canonicalizing non-constant type: {0}", constant_id);
  693. auto type_id =
  694. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  695. CARBON_CHECK(type_id == SemIR::TypeType::SingletonTypeId ||
  696. constant_id == SemIR::ErrorInst::SingletonConstantId,
  697. "Forming type ID for non-type constant of type {0}",
  698. types().GetAsInst(type_id));
  699. return SemIR::TypeId::ForTypeConstant(constant_id);
  700. }
  701. auto Context::FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  702. SemIR::SpecificId specific_id)
  703. -> SemIR::FacetType {
  704. SemIR::FacetTypeId facet_type_id = facet_types().Add(
  705. SemIR::FacetTypeInfo{.impls_constraints = {{interface_id, specific_id}},
  706. .other_requirements = false});
  707. return {.type_id = SemIR::TypeType::SingletonTypeId,
  708. .facet_type_id = facet_type_id};
  709. }
  710. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  711. template <typename InstT, typename... EachArgT>
  712. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  713. -> SemIR::TypeId {
  714. // TODO: Remove inst_id parameter from TryEvalInst.
  715. InstT inst = {SemIR::TypeType::SingletonTypeId, each_arg...};
  716. return context.GetTypeIdForTypeConstant(
  717. TryEvalInst(context, SemIR::InstId::None, inst));
  718. }
  719. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  720. // and completes the type. This should only be used when type completion cannot
  721. // fail.
  722. template <typename InstT, typename... EachArgT>
  723. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  724. -> SemIR::TypeId {
  725. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  726. CompleteTypeOrCheckFail(context, type_id);
  727. return type_id;
  728. }
  729. auto Context::GetStructType(SemIR::StructTypeFieldsId fields_id)
  730. -> SemIR::TypeId {
  731. return GetTypeImpl<SemIR::StructType>(*this, fields_id);
  732. }
  733. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  734. -> SemIR::TypeId {
  735. return GetTypeImpl<SemIR::TupleType>(*this,
  736. type_blocks().AddCanonical(type_ids));
  737. }
  738. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id)
  739. -> SemIR::TypeId {
  740. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id);
  741. }
  742. auto Context::GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId {
  743. CARBON_CHECK(SemIR::IsSingletonInstId(singleton_id));
  744. auto type_id = GetTypeIdForTypeInst(singleton_id);
  745. // To keep client code simpler, complete builtin types before returning them.
  746. CompleteTypeOrCheckFail(*this, type_id);
  747. return type_id;
  748. }
  749. auto Context::GetClassType(SemIR::ClassId class_id,
  750. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  751. return GetTypeImpl<SemIR::ClassType>(*this, class_id, specific_id);
  752. }
  753. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  754. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  755. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  756. }
  757. auto Context::GetFunctionTypeWithSelfType(
  758. SemIR::InstId interface_function_type_id, SemIR::InstId self_id)
  759. -> SemIR::TypeId {
  760. return GetCompleteTypeImpl<SemIR::FunctionTypeWithSelfType>(
  761. *this, interface_function_type_id, self_id);
  762. }
  763. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  764. SemIR::SpecificId enclosing_specific_id)
  765. -> SemIR::TypeId {
  766. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  767. enclosing_specific_id);
  768. }
  769. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  770. SemIR::SpecificId enclosing_specific_id)
  771. -> SemIR::TypeId {
  772. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  773. *this, interface_id, enclosing_specific_id);
  774. }
  775. auto Context::GetInterfaceType(SemIR::InterfaceId interface_id,
  776. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  777. return GetTypeImpl<SemIR::FacetType>(
  778. *this, FacetTypeFromInterface(interface_id, specific_id).facet_type_id);
  779. }
  780. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  781. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  782. }
  783. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  784. SemIR::TypeId element_type_id)
  785. -> SemIR::TypeId {
  786. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  787. element_type_id);
  788. }
  789. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  790. output << "Check::Context\n";
  791. // In a stack dump, this is probably indented by a tab. We treat that as 8
  792. // spaces then add a couple to indent past the Context label.
  793. constexpr int Indent = 10;
  794. node_stack_.PrintForStackDump(Indent, output);
  795. inst_block_stack_.PrintForStackDump(Indent, output);
  796. pattern_block_stack_.PrintForStackDump(Indent, output);
  797. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  798. args_type_info_stack_.PrintForStackDump(Indent, output);
  799. }
  800. auto Context::DumpFormattedFile() const -> void {
  801. SemIR::Formatter formatter(sem_ir_);
  802. formatter.Print(llvm::errs());
  803. }
  804. } // namespace Carbon::Check