context.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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/base/kind_switch.h"
  12. #include "toolchain/check/decl_name_stack.h"
  13. #include "toolchain/check/eval.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/generic_region_stack.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/inst_block_stack.h"
  19. #include "toolchain/check/merge.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/builtin_inst_kind.h"
  26. #include "toolchain/sem_ir/file.h"
  27. #include "toolchain/sem_ir/formatter.h"
  28. #include "toolchain/sem_ir/generic.h"
  29. #include "toolchain/sem_ir/ids.h"
  30. #include "toolchain/sem_ir/import_ir.h"
  31. #include "toolchain/sem_ir/inst.h"
  32. #include "toolchain/sem_ir/inst_kind.h"
  33. #include "toolchain/sem_ir/name_scope.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  37. const Parse::Tree& parse_tree,
  38. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  39. get_parse_tree_and_subtrees,
  40. SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream)
  41. : tokens_(&tokens),
  42. emitter_(&emitter),
  43. parse_tree_(&parse_tree),
  44. get_parse_tree_and_subtrees_(get_parse_tree_and_subtrees),
  45. sem_ir_(&sem_ir),
  46. vlog_stream_(vlog_stream),
  47. node_stack_(parse_tree, vlog_stream),
  48. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  49. pattern_block_stack_("pattern_block_stack_", sem_ir, vlog_stream),
  50. param_and_arg_refs_stack_(sem_ir, vlog_stream, node_stack_),
  51. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  52. decl_name_stack_(this),
  53. scope_stack_(sem_ir_->identifiers()),
  54. global_init_(this) {
  55. // Map the builtin `<error>` and `type` type constants to their corresponding
  56. // special `TypeId` values.
  57. type_ids_for_type_constants_.Insert(
  58. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinError),
  59. SemIR::TypeId::Error);
  60. type_ids_for_type_constants_.Insert(
  61. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinTypeType),
  62. SemIR::TypeId::TypeType);
  63. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  64. // in the right places.
  65. generic_region_stack().Push();
  66. }
  67. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  68. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  69. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  70. return false;
  71. }
  72. auto Context::VerifyOnFinish() -> void {
  73. // Information in all the various context objects should be cleaned up as
  74. // various pieces of context go out of scope. At this point, nothing should
  75. // remain.
  76. // node_stack_ will still contain top-level entities.
  77. inst_block_stack_.VerifyOnFinish();
  78. pattern_block_stack_.VerifyOnFinish();
  79. param_and_arg_refs_stack_.VerifyOnFinish();
  80. args_type_info_stack_.VerifyOnFinish();
  81. CARBON_CHECK(struct_type_fields_stack_.empty());
  82. // TODO: Add verification for decl_name_stack_ and
  83. // decl_introducer_state_stack_.
  84. scope_stack_.VerifyOnFinish();
  85. // TODO: Add verification for generic_region_stack_.
  86. }
  87. auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
  88. -> SemIR::InstId {
  89. if (loc_id_and_inst.loc_id.is_implicit()) {
  90. auto const_id =
  91. TryEvalInst(*this, SemIR::InstId::Invalid, loc_id_and_inst.inst);
  92. if (const_id.is_valid()) {
  93. CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
  94. return constant_values().GetInstId(const_id);
  95. }
  96. }
  97. // TODO: For an implicit instruction, this reattempts evaluation.
  98. return AddInst(loc_id_and_inst);
  99. }
  100. // Finish producing an instruction. Set its constant value, and register it in
  101. // any applicable instruction lists.
  102. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  103. GenericRegionStack::DependencyKind dep_kind =
  104. GenericRegionStack::DependencyKind::None;
  105. // If the instruction has a symbolic constant type, track that we need to
  106. // substitute into it.
  107. if (types().GetConstantId(inst.type_id()).is_symbolic()) {
  108. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  109. }
  110. // If the instruction has a constant value, compute it.
  111. auto const_id = TryEvalInst(*this, inst_id, inst);
  112. constant_values().Set(inst_id, const_id);
  113. if (const_id.is_constant()) {
  114. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  115. constant_values().GetInstId(const_id));
  116. // If the constant value is symbolic, track that we need to substitute into
  117. // it.
  118. if (const_id.is_symbolic()) {
  119. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  120. }
  121. }
  122. // Keep track of dependent instructions.
  123. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  124. // TODO: Also check for template-dependent instructions.
  125. generic_region_stack().AddDependentInst(
  126. {.inst_id = inst_id, .kind = dep_kind});
  127. }
  128. }
  129. // Returns whether a parse node associated with an imported instruction of kind
  130. // `imported_kind` is usable as the location of a corresponding local
  131. // instruction of kind `local_kind`.
  132. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  133. SemIR::InstKind local_kind) -> bool {
  134. if (imported_kind == local_kind) {
  135. return true;
  136. }
  137. if (imported_kind == SemIR::ImportDecl::Kind &&
  138. local_kind == SemIR::Namespace::Kind) {
  139. static_assert(
  140. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  141. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  142. return true;
  143. }
  144. return false;
  145. }
  146. auto Context::CheckCompatibleImportedNodeKind(
  147. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  148. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  149. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  150. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  151. CARBON_CHECK(
  152. HasCompatibleImportedNodeKind(imported_kind, kind),
  153. "Node of kind {0} created with location of imported node of kind {1}",
  154. kind, imported_kind);
  155. }
  156. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  157. -> SemIR::InstId {
  158. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  159. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  160. constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
  161. return inst_id;
  162. }
  163. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  164. -> SemIR::InstId {
  165. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  166. inst_block_stack_.AddInstId(inst_id);
  167. return inst_id;
  168. }
  169. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  170. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  171. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  172. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  173. FinishInst(inst_id, loc_id_and_inst.inst);
  174. }
  175. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  176. SemIR::Inst inst) -> void {
  177. sem_ir().insts().Set(inst_id, inst);
  178. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  179. FinishInst(inst_id, inst);
  180. }
  181. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  182. -> void {
  183. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  184. "duplicate name being declared in the same scope");
  185. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  186. emitter_->Build(dup_def, NameDeclDuplicate)
  187. .Note(prev_def, NameDeclPrevious)
  188. .Emit();
  189. }
  190. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  191. -> void {
  192. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  193. emitter_->Emit(loc, NameNotFound, name_id);
  194. }
  195. auto Context::NoteAbstractClass(SemIR::ClassId class_id,
  196. DiagnosticBuilder& builder) -> void {
  197. const auto& class_info = classes().Get(class_id);
  198. CARBON_CHECK(
  199. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  200. "Class is not abstract");
  201. CARBON_DIAGNOSTIC(ClassAbstractHere, Note,
  202. "class was declared abstract here");
  203. builder.Note(class_info.definition_id, ClassAbstractHere);
  204. }
  205. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  206. DiagnosticBuilder& builder) -> void {
  207. const auto& class_info = classes().Get(class_id);
  208. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  209. if (class_info.definition_id.is_valid()) {
  210. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  211. "class is incomplete within its definition");
  212. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  213. } else {
  214. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  215. "class was forward declared here");
  216. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  217. }
  218. }
  219. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  220. DiagnosticBuilder& builder) -> void {
  221. const auto& interface_info = interfaces().Get(interface_id);
  222. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  223. if (interface_info.is_being_defined()) {
  224. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  225. "interface is currently being defined");
  226. builder.Note(interface_info.definition_id,
  227. InterfaceUndefinedWithinDefinition);
  228. } else {
  229. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  230. "interface was forward declared here");
  231. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  232. }
  233. }
  234. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
  235. -> void {
  236. if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
  237. existing.is_valid()) {
  238. DiagnoseDuplicateName(target_id, existing);
  239. }
  240. }
  241. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  242. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  243. if (!scope_id.is_valid()) {
  244. // Look for a name in the current scope only. There are two cases where the
  245. // name would be in an outer scope:
  246. //
  247. // - The name is the sole component of the declared name:
  248. //
  249. // class A;
  250. // fn F() {
  251. // class A;
  252. // }
  253. //
  254. // In this case, the inner A is not the same class as the outer A, so
  255. // lookup should not find the outer A.
  256. //
  257. // - The name is a qualifier of some larger declared name:
  258. //
  259. // class A { class B; }
  260. // fn F() {
  261. // class A.B {}
  262. // }
  263. //
  264. // In this case, we're not in the correct scope to define a member of
  265. // class A, so we should reject, and we achieve this by not finding the
  266. // name A from the outer scope.
  267. return scope_stack().LookupInCurrentScope(name_id);
  268. } else {
  269. // We do not look into `extend`ed scopes here. A qualified name in a
  270. // declaration must specify the exact scope in which the name was originally
  271. // introduced:
  272. //
  273. // base class A { fn F(); }
  274. // class B { extend base: A; }
  275. //
  276. // // Error, no `F` in `B`.
  277. // fn B.F() {}
  278. return LookupNameInExactScope(loc_id, name_id, scope_id,
  279. name_scopes().Get(scope_id))
  280. .first;
  281. }
  282. }
  283. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  284. SemIR::NameId name_id, bool required)
  285. -> LookupResult {
  286. // TODO: Check for shadowed lookup results.
  287. // Find the results from ancestor lexical scopes. These will be combined with
  288. // results from non-lexical scopes such as namespaces and classes.
  289. auto [lexical_result, non_lexical_scopes] =
  290. scope_stack().LookupInLexicalScopes(name_id);
  291. // Walk the non-lexical scopes and perform lookups into each of them.
  292. for (auto [index, lookup_scope_id, specific_id] :
  293. llvm::reverse(non_lexical_scopes)) {
  294. if (auto non_lexical_result = LookupQualifiedName(
  295. node_id, name_id,
  296. {.name_scope_id = lookup_scope_id, .specific_id = specific_id},
  297. /*required=*/false);
  298. non_lexical_result.inst_id.is_valid()) {
  299. return non_lexical_result;
  300. }
  301. }
  302. if (lexical_result.is_valid()) {
  303. // A lexical scope never needs an associated specific. If there's a
  304. // lexically enclosing generic, then it also encloses the point of use of
  305. // the name.
  306. return {.specific_id = SemIR::SpecificId::Invalid,
  307. .inst_id = lexical_result};
  308. }
  309. // We didn't find anything at all.
  310. if (required) {
  311. DiagnoseNameNotFound(node_id, name_id);
  312. }
  313. return {.specific_id = SemIR::SpecificId::Invalid,
  314. .inst_id = SemIR::InstId::BuiltinError};
  315. }
  316. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  317. SemIR::NameScopeId scope_id,
  318. const SemIR::NameScope& scope)
  319. -> std::pair<SemIR::InstId, SemIR::AccessKind> {
  320. if (auto lookup = scope.name_map.Lookup(name_id)) {
  321. auto entry = scope.names[lookup.value()];
  322. LoadImportRef(*this, entry.inst_id);
  323. return {entry.inst_id, entry.access_kind};
  324. }
  325. if (!scope.import_ir_scopes.empty()) {
  326. // TODO: Enforce other access modifiers for imports.
  327. return {ImportNameFromOtherPackage(*this, loc, scope_id,
  328. scope.import_ir_scopes, name_id),
  329. SemIR::AccessKind::Public};
  330. }
  331. return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
  332. }
  333. // Prints diagnostics on invalid qualified name access.
  334. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  335. SemIR::InstId scope_result_id,
  336. SemIR::NameId name_id,
  337. SemIR::AccessKind access_kind,
  338. bool is_parent_access,
  339. AccessInfo access_info) -> void {
  340. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  341. context.constant_values().GetInstId(access_info.constant_id));
  342. if (!class_type) {
  343. return;
  344. }
  345. // TODO: Support scoped entities other than just classes.
  346. auto class_info = context.classes().Get(class_type->class_id);
  347. auto parent_type_id = class_info.self_type_id;
  348. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  349. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  350. class_info.base_id)) {
  351. parent_type_id = base_decl->base_type_id;
  352. } else if (auto adapt_decl =
  353. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  354. class_info.adapt_id)) {
  355. parent_type_id = adapt_decl->adapted_type_id;
  356. } else {
  357. CARBON_FATAL("Expected parent for parent access");
  358. }
  359. }
  360. CARBON_DIAGNOSTIC(
  361. ClassInvalidMemberAccess, Error,
  362. "cannot access {0:private|protected} member `{1}` of type {2}",
  363. BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  364. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  365. context.emitter()
  366. .Build(loc, ClassInvalidMemberAccess,
  367. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  368. .Note(scope_result_id, ClassMemberDeclaration)
  369. .Emit();
  370. }
  371. // Returns whether the access is prohibited by the access modifiers.
  372. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  373. SemIR::AccessKind access_kind,
  374. bool is_parent_access) -> bool {
  375. if (!access_info) {
  376. return false;
  377. }
  378. switch (access_kind) {
  379. case SemIR::AccessKind::Public:
  380. return false;
  381. case SemIR::AccessKind::Protected:
  382. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  383. case SemIR::AccessKind::Private:
  384. return access_info->highest_allowed_access !=
  385. SemIR::AccessKind::Private ||
  386. is_parent_access;
  387. }
  388. }
  389. // Information regarding a prohibited access.
  390. struct ProhibitedAccessInfo {
  391. // The resulting inst of the lookup.
  392. SemIR::InstId scope_result_id;
  393. // The access kind of the lookup.
  394. SemIR::AccessKind access_kind;
  395. // If the lookup is from an extended scope. For example, if this is a base
  396. // class member access from a class that extends it.
  397. bool is_parent_access;
  398. };
  399. auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
  400. LookupScope scope, bool required,
  401. std::optional<AccessInfo> access_info)
  402. -> LookupResult {
  403. llvm::SmallVector<LookupScope> scopes = {scope};
  404. // TODO: Support reporting of multiple prohibited access.
  405. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  406. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  407. .inst_id = SemIR::InstId::Invalid};
  408. bool has_error = false;
  409. bool is_parent_access = false;
  410. // Walk this scope and, if nothing is found here, the scopes it extends.
  411. while (!scopes.empty()) {
  412. auto [scope_id, specific_id] = scopes.pop_back_val();
  413. const auto& name_scope = name_scopes().Get(scope_id);
  414. has_error |= name_scope.has_error;
  415. auto [scope_result_id, access_kind] =
  416. LookupNameInExactScope(loc, name_id, scope_id, name_scope);
  417. auto is_access_prohibited =
  418. IsAccessProhibited(access_info, access_kind, is_parent_access);
  419. // Keep track of prohibited accesses, this will be useful for reporting
  420. // multiple prohibited accesses if we can't find a suitable lookup.
  421. if (is_access_prohibited) {
  422. prohibited_accesses.push_back({
  423. .scope_result_id = scope_result_id,
  424. .access_kind = access_kind,
  425. .is_parent_access = is_parent_access,
  426. });
  427. }
  428. if (!scope_result_id.is_valid() || is_access_prohibited) {
  429. // If nothing is found in this scope or if we encountered an invalid
  430. // access, look in its extended scopes.
  431. auto extended = name_scope.extended_scopes;
  432. scopes.reserve(scopes.size() + extended.size());
  433. for (auto extended_id : llvm::reverse(extended)) {
  434. // TODO: Track a constant describing the extended scope, and substitute
  435. // into it to determine its corresponding specific.
  436. scopes.push_back({.name_scope_id = extended_id,
  437. .specific_id = SemIR::SpecificId::Invalid});
  438. }
  439. is_parent_access |= !extended.empty();
  440. continue;
  441. }
  442. // If this is our second lookup result, diagnose an ambiguity.
  443. if (result.inst_id.is_valid()) {
  444. CARBON_DIAGNOSTIC(
  445. NameAmbiguousDueToExtend, Error,
  446. "ambiguous use of name `{0}` found in multiple extended scopes",
  447. SemIR::NameId);
  448. emitter_->Emit(loc, NameAmbiguousDueToExtend, name_id);
  449. // TODO: Add notes pointing to the scopes.
  450. return {.specific_id = SemIR::SpecificId::Invalid,
  451. .inst_id = SemIR::InstId::BuiltinError};
  452. }
  453. result.inst_id = scope_result_id;
  454. result.specific_id = specific_id;
  455. }
  456. if (required && !result.inst_id.is_valid()) {
  457. if (!has_error) {
  458. if (prohibited_accesses.empty()) {
  459. DiagnoseNameNotFound(loc, name_id);
  460. } else {
  461. // TODO: We should report multiple prohibited accesses in case we don't
  462. // find a valid lookup. Reporting the last one should suffice for now.
  463. auto [scope_result_id, access_kind, is_parent_access] =
  464. prohibited_accesses.back();
  465. // Note, `access_info` is guaranteed to have a value here, since
  466. // `prohibited_accesses` is non-empty.
  467. DiagnoseInvalidQualifiedNameAccess(*this, loc, scope_result_id, name_id,
  468. access_kind, is_parent_access,
  469. *access_info);
  470. }
  471. }
  472. return {.specific_id = SemIR::SpecificId::Invalid,
  473. .inst_id = SemIR::InstId::BuiltinError};
  474. }
  475. return result;
  476. }
  477. // Returns the scope of the Core package, or Invalid if it's not found.
  478. //
  479. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  480. // name lookup to find it.
  481. static auto GetCorePackage(Context& context, SemIRLoc loc)
  482. -> SemIR::NameScopeId {
  483. auto core_ident_id = context.identifiers().Add("Core");
  484. auto packaging = context.parse_tree().packaging_decl();
  485. if (packaging && packaging->names.package_id == core_ident_id) {
  486. return SemIR::NameScopeId::Package;
  487. }
  488. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  489. // Look up `package.Core`.
  490. auto [core_inst_id, _] = context.LookupNameInExactScope(
  491. loc, core_name_id, SemIR::NameScopeId::Package,
  492. context.name_scopes().Get(SemIR::NameScopeId::Package));
  493. if (core_inst_id.is_valid()) {
  494. // We expect it to be a namespace.
  495. if (auto namespace_inst =
  496. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  497. // TODO: Decide whether to allow the case where `Core` is not a package.
  498. return namespace_inst->name_scope_id;
  499. }
  500. }
  501. CARBON_DIAGNOSTIC(CoreNotFound, Error,
  502. "package `Core` implicitly referenced here, but not found");
  503. context.emitter().Emit(loc, CoreNotFound);
  504. return SemIR::NameScopeId::Invalid;
  505. }
  506. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  507. -> SemIR::InstId {
  508. auto core_package_id = GetCorePackage(*this, loc);
  509. if (!core_package_id.is_valid()) {
  510. return SemIR::InstId::BuiltinError;
  511. }
  512. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  513. auto [inst_id, _] = LookupNameInExactScope(
  514. loc, name_id, core_package_id, name_scopes().Get(core_package_id));
  515. if (!inst_id.is_valid()) {
  516. CARBON_DIAGNOSTIC(
  517. CoreNameNotFound, Error,
  518. "name `Core.{0}` implicitly referenced here, but not found",
  519. SemIR::NameId);
  520. emitter_->Emit(loc, CoreNameNotFound, name_id);
  521. return SemIR::InstId::BuiltinError;
  522. }
  523. // Look through import_refs and aliases.
  524. return constant_values().GetConstantInstId(inst_id);
  525. }
  526. template <typename BranchNode, typename... Args>
  527. static auto AddDominatedBlockAndBranchImpl(Context& context,
  528. Parse::NodeId node_id, Args... args)
  529. -> SemIR::InstBlockId {
  530. if (!context.inst_block_stack().is_current_block_reachable()) {
  531. return SemIR::InstBlockId::Unreachable;
  532. }
  533. auto block_id = context.inst_blocks().AddDefaultValue();
  534. context.AddInst<BranchNode>(node_id, {block_id, args...});
  535. return block_id;
  536. }
  537. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  538. -> SemIR::InstBlockId {
  539. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  540. }
  541. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  542. SemIR::InstId arg_id)
  543. -> SemIR::InstBlockId {
  544. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  545. arg_id);
  546. }
  547. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  548. SemIR::InstId cond_id)
  549. -> SemIR::InstBlockId {
  550. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  551. cond_id);
  552. }
  553. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  554. -> void {
  555. CARBON_CHECK(num_blocks >= 2, "no convergence");
  556. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  557. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  558. if (inst_block_stack().is_current_block_reachable()) {
  559. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  560. new_block_id = inst_blocks().AddDefaultValue();
  561. }
  562. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  563. }
  564. inst_block_stack().Pop();
  565. }
  566. inst_block_stack().Push(new_block_id);
  567. }
  568. auto Context::AddConvergenceBlockWithArgAndPush(
  569. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  570. -> SemIR::InstId {
  571. CARBON_CHECK(block_args.size() >= 2, "no convergence");
  572. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  573. for (auto arg_id : block_args) {
  574. if (inst_block_stack().is_current_block_reachable()) {
  575. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  576. new_block_id = inst_blocks().AddDefaultValue();
  577. }
  578. AddInst<SemIR::BranchWithArg>(
  579. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  580. }
  581. inst_block_stack().Pop();
  582. }
  583. inst_block_stack().Push(new_block_id);
  584. // Acquire the result value.
  585. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  586. return AddInst<SemIR::BlockArg>(
  587. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  588. }
  589. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  590. SemIR::InstId cond_id,
  591. SemIR::InstId if_true,
  592. SemIR::InstId if_false)
  593. -> void {
  594. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  595. // Determine the constant result based on the condition value.
  596. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  597. auto cond_const_id = constant_values().Get(cond_id);
  598. if (!cond_const_id.is_template()) {
  599. // Symbolic or non-constant condition means a non-constant result.
  600. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  601. constant_values().GetInstId(cond_const_id))) {
  602. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  603. : if_false);
  604. } else {
  605. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error,
  606. "Unexpected constant branch condition.");
  607. const_id = SemIR::ConstantId::Error;
  608. }
  609. if (const_id.is_constant()) {
  610. CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
  611. constant_values().GetInstId(const_id));
  612. constant_values().Set(select_id, const_id);
  613. }
  614. }
  615. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  616. CARBON_CHECK(!inst_block_stack().empty(), "no current code block");
  617. if (return_scope_stack().empty()) {
  618. CARBON_CHECK(node_id.is_valid(),
  619. "No current function, but node_id not provided");
  620. TODO(node_id,
  621. "Control flow expressions are currently only supported inside "
  622. "functions.");
  623. return;
  624. }
  625. if (!inst_block_stack().is_current_block_reachable()) {
  626. // Don't include unreachable blocks in the function.
  627. return;
  628. }
  629. auto function_id =
  630. insts()
  631. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  632. .function_id;
  633. functions()
  634. .Get(function_id)
  635. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  636. }
  637. auto Context::is_current_position_reachable() -> bool {
  638. if (!inst_block_stack().is_current_block_reachable()) {
  639. return false;
  640. }
  641. // Our current position is at the end of a reachable block. That position is
  642. // reachable unless the previous instruction is a terminator instruction.
  643. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  644. if (block_contents.empty()) {
  645. return true;
  646. }
  647. const auto& last_inst = insts().Get(block_contents.back());
  648. return last_inst.kind().terminator_kind() !=
  649. SemIR::TerminatorKind::Terminator;
  650. }
  651. auto Context::Finalize() -> void {
  652. // Pop information for the file-level scope.
  653. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  654. scope_stack().Pop();
  655. // Finalizes the list of exports on the IR.
  656. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  657. // Finalizes the ImportRef inst block.
  658. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  659. // Finalizes __global_init.
  660. global_init_.Finalize();
  661. }
  662. namespace {
  663. // Worklist-based type completion mechanism.
  664. //
  665. // When attempting to complete a type, we may find other types that also need to
  666. // be completed: types nested within that type, and the value representation of
  667. // the type. In order to complete a type without recursing arbitrarily deeply,
  668. // we use a worklist of tasks:
  669. //
  670. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  671. // nested within a type to the work list.
  672. // - A `BuildValueRepr` step computes the value representation for a
  673. // type, once all of its nested types are complete, and marks the type as
  674. // complete.
  675. class TypeCompleter {
  676. public:
  677. TypeCompleter(Context& context, Context::BuildDiagnosticFn diagnoser)
  678. : context_(context), diagnoser_(diagnoser) {}
  679. // Attempts to complete the given type. Returns true if it is now complete,
  680. // false if it could not be completed.
  681. auto Complete(SemIR::TypeId type_id) -> bool {
  682. Push(type_id);
  683. while (!work_list_.empty()) {
  684. if (!ProcessStep()) {
  685. return false;
  686. }
  687. }
  688. return true;
  689. }
  690. private:
  691. // Adds `type_id` to the work list, if it's not already complete.
  692. auto Push(SemIR::TypeId type_id) -> void {
  693. if (!context_.types().IsComplete(type_id)) {
  694. work_list_.push_back(
  695. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  696. }
  697. }
  698. // Runs the next step.
  699. auto ProcessStep() -> bool {
  700. auto [type_id, phase] = work_list_.back();
  701. // We might have enqueued the same type more than once. Just skip the
  702. // type if it's already complete.
  703. if (context_.types().IsComplete(type_id)) {
  704. work_list_.pop_back();
  705. return true;
  706. }
  707. auto inst_id = context_.types().GetInstId(type_id);
  708. auto inst = context_.insts().Get(inst_id);
  709. auto old_work_list_size = work_list_.size();
  710. switch (phase) {
  711. case Phase::AddNestedIncompleteTypes:
  712. if (!AddNestedIncompleteTypes(inst)) {
  713. return false;
  714. }
  715. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  716. "AddNestedIncompleteTypes should not remove work items");
  717. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  718. break;
  719. case Phase::BuildValueRepr: {
  720. auto value_rep = BuildValueRepr(type_id, inst);
  721. context_.types().SetValueRepr(type_id, value_rep);
  722. CARBON_CHECK(old_work_list_size == work_list_.size(),
  723. "BuildValueRepr should not change work items");
  724. work_list_.pop_back();
  725. // Also complete the value representation type, if necessary. This
  726. // should never fail: the value representation shouldn't require any
  727. // additional nested types to be complete.
  728. if (!context_.types().IsComplete(value_rep.type_id)) {
  729. work_list_.push_back(
  730. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  731. }
  732. // For a pointer representation, the pointee also needs to be complete.
  733. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  734. if (value_rep.type_id == SemIR::TypeId::Error) {
  735. break;
  736. }
  737. auto pointee_type_id =
  738. context_.sem_ir().GetPointeeType(value_rep.type_id);
  739. if (!context_.types().IsComplete(pointee_type_id)) {
  740. work_list_.push_back(
  741. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  742. }
  743. }
  744. break;
  745. }
  746. }
  747. return true;
  748. }
  749. // Adds any types nested within `type_inst` that need to be complete for
  750. // `type_inst` to be complete to our work list.
  751. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  752. CARBON_KIND_SWITCH(type_inst) {
  753. case CARBON_KIND(SemIR::ArrayType inst): {
  754. Push(inst.element_type_id);
  755. break;
  756. }
  757. case CARBON_KIND(SemIR::StructType inst): {
  758. for (auto field : context_.struct_type_fields().Get(inst.fields_id)) {
  759. Push(field.type_id);
  760. }
  761. break;
  762. }
  763. case CARBON_KIND(SemIR::TupleType inst): {
  764. for (auto element_type_id :
  765. context_.type_blocks().Get(inst.elements_id)) {
  766. Push(element_type_id);
  767. }
  768. break;
  769. }
  770. case CARBON_KIND(SemIR::ClassType inst): {
  771. auto& class_info = context_.classes().Get(inst.class_id);
  772. if (!class_info.is_defined()) {
  773. if (diagnoser_) {
  774. auto builder = diagnoser_();
  775. context_.NoteIncompleteClass(inst.class_id, builder);
  776. builder.Emit();
  777. }
  778. return false;
  779. }
  780. if (inst.specific_id.is_valid()) {
  781. ResolveSpecificDefinition(context_, inst.specific_id);
  782. }
  783. Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
  784. break;
  785. }
  786. case CARBON_KIND(SemIR::ConstType inst): {
  787. Push(inst.inner_id);
  788. break;
  789. }
  790. default:
  791. break;
  792. }
  793. return true;
  794. }
  795. // Makes an empty value representation, which is used for types that have no
  796. // state, such as empty structs and tuples.
  797. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  798. return {.kind = SemIR::ValueRepr::None,
  799. .type_id = context_.GetTupleType({})};
  800. }
  801. // Makes a value representation that uses pass-by-copy, copying the given
  802. // type.
  803. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  804. SemIR::ValueRepr::AggregateKind aggregate_kind =
  805. SemIR::ValueRepr::NotAggregate) const
  806. -> SemIR::ValueRepr {
  807. return {.kind = SemIR::ValueRepr::Copy,
  808. .aggregate_kind = aggregate_kind,
  809. .type_id = rep_id};
  810. }
  811. // Makes a value representation that uses pass-by-address with the given
  812. // pointee type.
  813. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  814. SemIR::ValueRepr::AggregateKind aggregate_kind =
  815. SemIR::ValueRepr::NotAggregate) const
  816. -> SemIR::ValueRepr {
  817. // TODO: Should we add `const` qualification to `pointee_id`?
  818. return {.kind = SemIR::ValueRepr::Pointer,
  819. .aggregate_kind = aggregate_kind,
  820. .type_id = context_.GetPointerType(pointee_id)};
  821. }
  822. // Gets the value representation of a nested type, which should already be
  823. // complete.
  824. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  825. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  826. "Nested type should already be complete");
  827. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  828. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown,
  829. "Complete type should have a value representation");
  830. return value_rep;
  831. }
  832. auto BuildValueReprForInst(SemIR::TypeId type_id,
  833. SemIR::BuiltinInst builtin) const
  834. -> SemIR::ValueRepr {
  835. switch (builtin.builtin_inst_kind) {
  836. case SemIR::BuiltinInstKind::TypeType:
  837. case SemIR::BuiltinInstKind::AutoType:
  838. case SemIR::BuiltinInstKind::Error:
  839. case SemIR::BuiltinInstKind::Invalid:
  840. case SemIR::BuiltinInstKind::BoolType:
  841. case SemIR::BuiltinInstKind::IntLiteralType:
  842. case SemIR::BuiltinInstKind::IntType:
  843. case SemIR::BuiltinInstKind::FloatType:
  844. case SemIR::BuiltinInstKind::NamespaceType:
  845. case SemIR::BuiltinInstKind::BoundMethodType:
  846. case SemIR::BuiltinInstKind::WitnessType:
  847. case SemIR::BuiltinInstKind::SpecificFunctionType:
  848. case SemIR::BuiltinInstKind::VtableType:
  849. return MakeCopyValueRepr(type_id);
  850. case SemIR::BuiltinInstKind::StringType:
  851. // TODO: Decide on string value semantics. This should probably be a
  852. // custom value representation carrying a pointer and size or
  853. // similar.
  854. return MakePointerValueRepr(type_id);
  855. }
  856. llvm_unreachable("All builtin kinds were handled above");
  857. }
  858. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  859. SemIR::TypeId elementwise_rep,
  860. bool same_as_object_rep) const
  861. -> SemIR::ValueRepr {
  862. SemIR::ValueRepr::AggregateKind aggregate_kind =
  863. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  864. : SemIR::ValueRepr::ValueAggregate;
  865. if (num_elements == 1) {
  866. // The value representation for a struct or tuple with a single element
  867. // is a struct or tuple containing the value representation of the
  868. // element.
  869. // TODO: Consider doing the same whenever `elementwise_rep` is
  870. // sufficiently small.
  871. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  872. }
  873. // For a struct or tuple with multiple fields, we use a pointer
  874. // to the elementwise value representation.
  875. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  876. }
  877. auto BuildValueReprForInst(SemIR::TypeId type_id,
  878. SemIR::StructType struct_type) const
  879. -> SemIR::ValueRepr {
  880. auto fields = context_.struct_type_fields().Get(struct_type.fields_id);
  881. if (fields.empty()) {
  882. return MakeEmptyValueRepr();
  883. }
  884. // Find the value representation for each field, and construct a struct
  885. // of value representations.
  886. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  887. value_rep_fields.reserve(fields.size());
  888. bool same_as_object_rep = true;
  889. for (auto field : fields) {
  890. auto field_value_rep = GetNestedValueRepr(field.type_id);
  891. if (field_value_rep.type_id != field.type_id) {
  892. same_as_object_rep = false;
  893. field.type_id = field_value_rep.type_id;
  894. }
  895. value_rep_fields.push_back(field);
  896. }
  897. auto value_rep =
  898. same_as_object_rep
  899. ? type_id
  900. : context_.GetStructType(
  901. context_.struct_type_fields().AddCanonical(value_rep_fields));
  902. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  903. same_as_object_rep);
  904. }
  905. auto BuildValueReprForInst(SemIR::TypeId type_id,
  906. SemIR::TupleType tuple_type) const
  907. -> SemIR::ValueRepr {
  908. // TODO: Share more code with structs.
  909. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  910. if (elements.empty()) {
  911. return MakeEmptyValueRepr();
  912. }
  913. // Find the value representation for each element, and construct a tuple
  914. // of value representations.
  915. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  916. value_rep_elements.reserve(elements.size());
  917. bool same_as_object_rep = true;
  918. for (auto element_type_id : elements) {
  919. auto element_value_rep = GetNestedValueRepr(element_type_id);
  920. if (element_value_rep.type_id != element_type_id) {
  921. same_as_object_rep = false;
  922. }
  923. value_rep_elements.push_back(element_value_rep.type_id);
  924. }
  925. auto value_rep = same_as_object_rep
  926. ? type_id
  927. : context_.GetTupleType(value_rep_elements);
  928. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  929. same_as_object_rep);
  930. }
  931. auto BuildValueReprForInst(SemIR::TypeId type_id,
  932. SemIR::ArrayType /*inst*/) const
  933. -> SemIR::ValueRepr {
  934. // For arrays, it's convenient to always use a pointer representation,
  935. // even when the array has zero or one element, in order to support
  936. // indexing.
  937. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  938. }
  939. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  940. SemIR::ClassType inst) const -> SemIR::ValueRepr {
  941. auto& class_info = context_.classes().Get(inst.class_id);
  942. // The value representation of an adapter is the value representation of
  943. // its adapted type.
  944. if (class_info.adapt_id.is_valid()) {
  945. return GetNestedValueRepr(SemIR::GetTypeInSpecific(
  946. context_.sem_ir(), inst.specific_id,
  947. context_.insts()
  948. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  949. .adapted_type_id));
  950. }
  951. // Otherwise, the value representation for a class is a pointer to the
  952. // object representation.
  953. // TODO: Support customized value representations for classes.
  954. // TODO: Pick a better value representation when possible.
  955. return MakePointerValueRepr(
  956. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  957. SemIR::ValueRepr::ObjectAggregate);
  958. }
  959. template <typename InstT>
  960. requires(
  961. InstT::Kind
  962. .template IsAnyOf<SemIR::AssociatedEntityType, SemIR::FacetType,
  963. SemIR::FunctionType, SemIR::GenericClassType,
  964. SemIR::GenericInterfaceType, SemIR::InterfaceType,
  965. SemIR::UnboundElementType, SemIR::WhereExpr>())
  966. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  967. -> SemIR::ValueRepr {
  968. // These types have no runtime operations, so we use an empty value
  969. // representation.
  970. //
  971. // TODO: There is information we could model here:
  972. // - For an interface, we could use a witness.
  973. // - For an associated entity, we could use an index into the witness.
  974. // - For an unbound element, we could use an index or offset.
  975. return MakeEmptyValueRepr();
  976. }
  977. template <typename InstT>
  978. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  979. SemIR::InterfaceWitnessAccess>())
  980. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  981. -> SemIR::ValueRepr {
  982. // For symbolic types, we arbitrarily pick a copy representation.
  983. return MakeCopyValueRepr(type_id);
  984. }
  985. template <typename InstT>
  986. requires(InstT::Kind.template IsAnyOf<SemIR::FloatType, SemIR::IntType,
  987. SemIR::PointerType>())
  988. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  989. -> SemIR::ValueRepr {
  990. return MakeCopyValueRepr(type_id);
  991. }
  992. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  993. SemIR::ConstType inst) const -> SemIR::ValueRepr {
  994. // The value representation of `const T` is the same as that of `T`.
  995. // Objects are not modifiable through their value representations.
  996. return GetNestedValueRepr(inst.inner_id);
  997. }
  998. template <typename InstT>
  999. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  1000. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  1001. -> SemIR::ValueRepr {
  1002. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  1003. }
  1004. // Builds and returns the value representation for the given type. All nested
  1005. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  1006. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  1007. -> SemIR::ValueRepr {
  1008. // Use overload resolution to select the implementation, producing compile
  1009. // errors when BuildValueReprForInst isn't defined for a given instruction.
  1010. CARBON_KIND_SWITCH(inst) {
  1011. #define CARBON_SEM_IR_INST_KIND(Name) \
  1012. case CARBON_KIND(SemIR::Name typed_inst): { \
  1013. return BuildValueReprForInst(type_id, typed_inst); \
  1014. }
  1015. #include "toolchain/sem_ir/inst_kind.def"
  1016. }
  1017. }
  1018. enum class Phase : int8_t {
  1019. // The next step is to add nested types to the list of types to complete.
  1020. AddNestedIncompleteTypes,
  1021. // The next step is to build the value representation for the type.
  1022. BuildValueRepr,
  1023. };
  1024. struct WorkItem {
  1025. SemIR::TypeId type_id;
  1026. Phase phase;
  1027. };
  1028. Context& context_;
  1029. llvm::SmallVector<WorkItem> work_list_;
  1030. Context::BuildDiagnosticFn diagnoser_;
  1031. };
  1032. } // namespace
  1033. auto Context::TryToCompleteType(SemIR::TypeId type_id,
  1034. BuildDiagnosticFn diagnoser,
  1035. BuildDiagnosticFn abstract_diagnoser) -> bool {
  1036. if (!TypeCompleter(*this, diagnoser).Complete(type_id)) {
  1037. return false;
  1038. }
  1039. if (!abstract_diagnoser) {
  1040. return true;
  1041. }
  1042. if (auto class_type = types().TryGetAs<SemIR::ClassType>(type_id)) {
  1043. auto& class_info = classes().Get(class_type->class_id);
  1044. if (class_info.inheritance_kind !=
  1045. SemIR::Class::InheritanceKind::Abstract) {
  1046. return true;
  1047. }
  1048. auto builder = abstract_diagnoser();
  1049. if (!builder) {
  1050. return false;
  1051. }
  1052. NoteAbstractClass(class_type->class_id, builder);
  1053. builder.Emit();
  1054. return false;
  1055. }
  1056. return true;
  1057. }
  1058. auto Context::TryToDefineType(SemIR::TypeId type_id,
  1059. BuildDiagnosticFn diagnoser) -> bool {
  1060. if (!TryToCompleteType(type_id, diagnoser)) {
  1061. return false;
  1062. }
  1063. if (auto interface = types().TryGetAs<SemIR::InterfaceType>(type_id)) {
  1064. auto interface_id = interface->interface_id;
  1065. if (!interfaces().Get(interface_id).is_defined()) {
  1066. auto builder = diagnoser();
  1067. NoteUndefinedInterface(interface_id, builder);
  1068. builder.Emit();
  1069. return false;
  1070. }
  1071. if (interface->specific_id.is_valid()) {
  1072. ResolveSpecificDefinition(*this, interface->specific_id);
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  1078. -> SemIR::TypeId {
  1079. CARBON_CHECK(constant_id.is_constant(),
  1080. "Canonicalizing non-constant type: {0}", constant_id);
  1081. auto type_id =
  1082. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  1083. // TODO: For now, we allow values of facet type to be used as types.
  1084. CARBON_CHECK(IsFacetType(type_id) || constant_id == SemIR::ConstantId::Error,
  1085. "Forming type ID for non-type constant of type {0}",
  1086. types().GetAsInst(type_id));
  1087. return SemIR::TypeId::ForTypeConstant(constant_id);
  1088. }
  1089. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  1090. template <typename InstT, typename... EachArgT>
  1091. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  1092. -> SemIR::TypeId {
  1093. // TODO: Remove inst_id parameter from TryEvalInst.
  1094. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  1095. return context.GetTypeIdForTypeConstant(
  1096. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  1097. }
  1098. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  1099. // and completes the type. This should only be used when type completion cannot
  1100. // fail.
  1101. template <typename InstT, typename... EachArgT>
  1102. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  1103. -> SemIR::TypeId {
  1104. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  1105. bool complete = context.TryToCompleteType(type_id);
  1106. CARBON_CHECK(complete, "Type completion should not fail");
  1107. return type_id;
  1108. }
  1109. auto Context::GetStructType(SemIR::StructTypeFieldsId fields_id)
  1110. -> SemIR::TypeId {
  1111. return GetTypeImpl<SemIR::StructType>(*this, fields_id);
  1112. }
  1113. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1114. -> SemIR::TypeId {
  1115. return GetTypeImpl<SemIR::TupleType>(*this,
  1116. type_blocks().AddCanonical(type_ids));
  1117. }
  1118. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  1119. SemIR::TypeId entity_type_id)
  1120. -> SemIR::TypeId {
  1121. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id,
  1122. entity_type_id);
  1123. }
  1124. auto Context::GetBuiltinType(SemIR::BuiltinInstKind kind) -> SemIR::TypeId {
  1125. CARBON_CHECK(kind != SemIR::BuiltinInstKind::Invalid);
  1126. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  1127. // To keep client code simpler, complete builtin types before returning them.
  1128. bool complete = TryToCompleteType(type_id);
  1129. CARBON_CHECK(complete, "Failed to complete builtin type");
  1130. return type_id;
  1131. }
  1132. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  1133. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1134. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  1135. }
  1136. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  1137. SemIR::SpecificId enclosing_specific_id)
  1138. -> SemIR::TypeId {
  1139. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  1140. enclosing_specific_id);
  1141. }
  1142. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  1143. SemIR::SpecificId enclosing_specific_id)
  1144. -> SemIR::TypeId {
  1145. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  1146. *this, interface_id, enclosing_specific_id);
  1147. }
  1148. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1149. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1150. }
  1151. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1152. SemIR::TypeId element_type_id)
  1153. -> SemIR::TypeId {
  1154. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1155. element_type_id);
  1156. }
  1157. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1158. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1159. return const_type->inner_id;
  1160. }
  1161. return type_id;
  1162. }
  1163. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1164. output << "Check::Context\n";
  1165. // In a stack dump, this is probably indented by a tab. We treat that as 8
  1166. // spaces then add a couple to indent past the Context label.
  1167. constexpr int Indent = 10;
  1168. node_stack_.PrintForStackDump(Indent, output);
  1169. inst_block_stack_.PrintForStackDump(Indent, output);
  1170. pattern_block_stack_.PrintForStackDump(Indent, output);
  1171. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  1172. args_type_info_stack_.PrintForStackDump(Indent, output);
  1173. }
  1174. auto Context::DumpFormattedFile() const -> void {
  1175. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  1176. formatter.Print(llvm::errs());
  1177. }
  1178. } // namespace Carbon::Check