context.cpp 45 KB

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