context.cpp 49 KB

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