context.cpp 39 KB

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