context.cpp 45 KB

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