context.cpp 49 KB

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