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) -> LookupResult {
  274. // TODO: Check for shadowed lookup results.
  275. // Find the results from ancestor lexical scopes. These will be combined with
  276. // results from non-lexical scopes such as namespaces and classes.
  277. auto [lexical_result, non_lexical_scopes] =
  278. scope_stack().LookupInLexicalScopes(name_id);
  279. // Walk the non-lexical scopes and perform lookups into each of them.
  280. for (auto [index, lookup_scope_id, specific_id] :
  281. llvm::reverse(non_lexical_scopes)) {
  282. if (auto non_lexical_result = LookupQualifiedName(
  283. node_id, name_id,
  284. {.name_scope_id = lookup_scope_id, .specific_id = specific_id},
  285. /*required=*/false);
  286. non_lexical_result.inst_id.is_valid()) {
  287. return non_lexical_result;
  288. }
  289. }
  290. if (lexical_result.is_valid()) {
  291. // A lexical scope never needs an associated specific. If there's a
  292. // lexically enclosing generic, then it also encloses the point of use of
  293. // the name.
  294. return {.specific_id = SemIR::SpecificId::Invalid,
  295. .inst_id = lexical_result};
  296. }
  297. // We didn't find anything at all.
  298. DiagnoseNameNotFound(node_id, name_id);
  299. return {.specific_id = SemIR::SpecificId::Invalid,
  300. .inst_id = SemIR::InstId::BuiltinError};
  301. }
  302. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  303. SemIR::NameScopeId scope_id,
  304. const SemIR::NameScope& scope)
  305. -> std::pair<SemIR::InstId, SemIR::AccessKind> {
  306. if (auto lookup = scope.name_map.Lookup(name_id)) {
  307. auto entry = scope.names[lookup.value()];
  308. LoadImportRef(*this, entry.inst_id);
  309. return {entry.inst_id, entry.access_kind};
  310. }
  311. if (!scope.import_ir_scopes.empty()) {
  312. // TODO: Enforce other access modifiers for imports.
  313. return {ImportNameFromOtherPackage(*this, loc, scope_id,
  314. scope.import_ir_scopes, name_id),
  315. SemIR::AccessKind::Public};
  316. }
  317. return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
  318. }
  319. // Prints diagnostics on invalid qualified name access.
  320. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  321. SemIR::InstId scope_result_id,
  322. SemIR::NameId name_id,
  323. SemIR::AccessKind access_kind,
  324. bool is_parent_access,
  325. AccessInfo access_info) -> void {
  326. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  327. context.constant_values().GetInstId(access_info.constant_id));
  328. if (!class_type) {
  329. return;
  330. }
  331. // TODO: Support scoped entities other than just classes.
  332. auto class_info = context.classes().Get(class_type->class_id);
  333. // TODO: Support passing AccessKind to diagnostics.
  334. CARBON_DIAGNOSTIC(ClassInvalidMemberAccess, Error,
  335. "Cannot access {0} member `{1}` of type `{2}`.",
  336. llvm::StringLiteral, SemIR::NameId, SemIR::TypeId);
  337. CARBON_DIAGNOSTIC(ClassMemberDefinition, Note,
  338. "The {0} member `{1}` is defined here.",
  339. llvm::StringLiteral, SemIR::NameId);
  340. auto parent_type_id = class_info.self_type_id;
  341. auto access_desc = access_kind == SemIR::AccessKind::Private
  342. ? llvm::StringLiteral("private")
  343. : llvm::StringLiteral("protected");
  344. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  345. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  346. class_info.base_id)) {
  347. parent_type_id = base_decl->base_type_id;
  348. } else if (auto adapt_decl =
  349. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  350. class_info.adapt_id)) {
  351. parent_type_id = adapt_decl->adapted_type_id;
  352. } else {
  353. CARBON_FATAL("Expected parent for parent access");
  354. }
  355. }
  356. context.emitter()
  357. .Build(loc, ClassInvalidMemberAccess, access_desc, name_id,
  358. parent_type_id)
  359. .Note(scope_result_id, ClassMemberDefinition, access_desc, name_id)
  360. .Emit();
  361. }
  362. // Returns whether the access is prohibited by the access modifiers.
  363. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  364. SemIR::AccessKind access_kind,
  365. bool is_parent_access) -> bool {
  366. if (!access_info) {
  367. return false;
  368. }
  369. switch (access_kind) {
  370. case SemIR::AccessKind::Public:
  371. return false;
  372. case SemIR::AccessKind::Protected:
  373. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  374. case SemIR::AccessKind::Private:
  375. return access_info->highest_allowed_access !=
  376. SemIR::AccessKind::Private ||
  377. is_parent_access;
  378. }
  379. }
  380. // Information regarding a prohibited access.
  381. struct ProhibitedAccessInfo {
  382. // The resulting inst of the lookup.
  383. SemIR::InstId scope_result_id;
  384. // The access kind of the lookup.
  385. SemIR::AccessKind access_kind;
  386. // If the lookup is from an extended scope. For example, if this is a base
  387. // class member access from a class that extends it.
  388. bool is_parent_access;
  389. };
  390. auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
  391. LookupScope scope, bool required,
  392. std::optional<AccessInfo> access_info)
  393. -> LookupResult {
  394. llvm::SmallVector<LookupScope> scopes = {scope};
  395. // TODO: Support reporting of multiple prohibited access.
  396. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  397. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  398. .inst_id = SemIR::InstId::Invalid};
  399. bool has_error = false;
  400. bool is_parent_access = false;
  401. // Walk this scope and, if nothing is found here, the scopes it extends.
  402. while (!scopes.empty()) {
  403. auto [scope_id, specific_id] = scopes.pop_back_val();
  404. const auto& name_scope = name_scopes().Get(scope_id);
  405. has_error |= name_scope.has_error;
  406. auto [scope_result_id, access_kind] =
  407. LookupNameInExactScope(loc, name_id, scope_id, name_scope);
  408. auto is_access_prohibited =
  409. IsAccessProhibited(access_info, access_kind, is_parent_access);
  410. // Keep track of prohibited accesses, this will be useful for reporting
  411. // multiple prohibited accesses if we can't find a suitable lookup.
  412. if (is_access_prohibited) {
  413. prohibited_accesses.push_back({
  414. .scope_result_id = scope_result_id,
  415. .access_kind = access_kind,
  416. .is_parent_access = is_parent_access,
  417. });
  418. }
  419. if (!scope_result_id.is_valid() || is_access_prohibited) {
  420. // If nothing is found in this scope or if we encountered an invalid
  421. // access, look in its extended scopes.
  422. auto extended = name_scope.extended_scopes;
  423. scopes.reserve(scopes.size() + extended.size());
  424. for (auto extended_id : llvm::reverse(extended)) {
  425. // TODO: Track a constant describing the extended scope, and substitute
  426. // into it to determine its corresponding specific.
  427. scopes.push_back({.name_scope_id = extended_id,
  428. .specific_id = SemIR::SpecificId::Invalid});
  429. }
  430. is_parent_access |= !extended.empty();
  431. continue;
  432. }
  433. // If this is our second lookup result, diagnose an ambiguity.
  434. if (result.inst_id.is_valid()) {
  435. // TODO: This is currently not reachable because the only scope that can
  436. // extend is a class scope, and it can only extend a single base class.
  437. // Add test coverage once this is possible.
  438. CARBON_DIAGNOSTIC(
  439. NameAmbiguousDueToExtend, Error,
  440. "Ambiguous use of name `{0}` found in multiple extended scopes.",
  441. SemIR::NameId);
  442. emitter_->Emit(loc, NameAmbiguousDueToExtend, name_id);
  443. // TODO: Add notes pointing to the scopes.
  444. return {.specific_id = SemIR::SpecificId::Invalid,
  445. .inst_id = SemIR::InstId::BuiltinError};
  446. }
  447. result.inst_id = scope_result_id;
  448. result.specific_id = specific_id;
  449. }
  450. if (required && !result.inst_id.is_valid()) {
  451. if (!has_error) {
  452. if (prohibited_accesses.empty()) {
  453. DiagnoseNameNotFound(loc, name_id);
  454. } else {
  455. // TODO: We should report multiple prohibited accesses in case we don't
  456. // find a valid lookup. Reporting the last one should suffice for now.
  457. auto [scope_result_id, access_kind, is_parent_access] =
  458. prohibited_accesses.back();
  459. // Note, `access_info` is guaranteed to have a value here, since
  460. // `prohibited_accesses` is non-empty.
  461. DiagnoseInvalidQualifiedNameAccess(*this, loc, scope_result_id, name_id,
  462. access_kind, is_parent_access,
  463. *access_info);
  464. }
  465. }
  466. return {.specific_id = SemIR::SpecificId::Invalid,
  467. .inst_id = SemIR::InstId::BuiltinError};
  468. }
  469. return result;
  470. }
  471. // Returns the scope of the Core package, or Invalid if it's not found.
  472. //
  473. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  474. // name lookup to find it.
  475. static auto GetCorePackage(Context& context, SemIRLoc loc)
  476. -> SemIR::NameScopeId {
  477. auto core_ident_id = context.identifiers().Add("Core");
  478. auto packaging = context.parse_tree().packaging_decl();
  479. if (packaging && packaging->names.package_id == core_ident_id) {
  480. return SemIR::NameScopeId::Package;
  481. }
  482. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  483. // Look up `package.Core`.
  484. auto [core_inst_id, _] = context.LookupNameInExactScope(
  485. loc, core_name_id, SemIR::NameScopeId::Package,
  486. context.name_scopes().Get(SemIR::NameScopeId::Package));
  487. if (core_inst_id.is_valid()) {
  488. // We expect it to be a namespace.
  489. if (auto namespace_inst =
  490. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  491. // TODO: Decide whether to allow the case where `Core` is not a package.
  492. return namespace_inst->name_scope_id;
  493. }
  494. }
  495. CARBON_DIAGNOSTIC(
  496. CoreNotFound, Error,
  497. "Package `Core` implicitly referenced here, but not found.");
  498. context.emitter().Emit(loc, CoreNotFound);
  499. return SemIR::NameScopeId::Invalid;
  500. }
  501. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  502. -> SemIR::InstId {
  503. auto core_package_id = GetCorePackage(*this, loc);
  504. if (!core_package_id.is_valid()) {
  505. return SemIR::InstId::BuiltinError;
  506. }
  507. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  508. auto [inst_id, _] = LookupNameInExactScope(
  509. loc, name_id, core_package_id, name_scopes().Get(core_package_id));
  510. if (!inst_id.is_valid()) {
  511. CARBON_DIAGNOSTIC(
  512. CoreNameNotFound, Error,
  513. "Name `Core.{0}` implicitly referenced here, but not found.",
  514. SemIR::NameId);
  515. emitter_->Emit(loc, CoreNameNotFound, name_id);
  516. return SemIR::InstId::BuiltinError;
  517. }
  518. // Look through import_refs and aliases.
  519. return constant_values().GetConstantInstId(inst_id);
  520. }
  521. template <typename BranchNode, typename... Args>
  522. static auto AddDominatedBlockAndBranchImpl(Context& context,
  523. Parse::NodeId node_id, Args... args)
  524. -> SemIR::InstBlockId {
  525. if (!context.inst_block_stack().is_current_block_reachable()) {
  526. return SemIR::InstBlockId::Unreachable;
  527. }
  528. auto block_id = context.inst_blocks().AddDefaultValue();
  529. context.AddInst<BranchNode>(node_id, {block_id, args...});
  530. return block_id;
  531. }
  532. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  533. -> SemIR::InstBlockId {
  534. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  535. }
  536. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  537. SemIR::InstId arg_id)
  538. -> SemIR::InstBlockId {
  539. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  540. arg_id);
  541. }
  542. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  543. SemIR::InstId cond_id)
  544. -> SemIR::InstBlockId {
  545. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  546. cond_id);
  547. }
  548. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  549. -> void {
  550. CARBON_CHECK(num_blocks >= 2, "no convergence");
  551. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  552. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  553. if (inst_block_stack().is_current_block_reachable()) {
  554. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  555. new_block_id = inst_blocks().AddDefaultValue();
  556. }
  557. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  558. }
  559. inst_block_stack().Pop();
  560. }
  561. inst_block_stack().Push(new_block_id);
  562. }
  563. auto Context::AddConvergenceBlockWithArgAndPush(
  564. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  565. -> SemIR::InstId {
  566. CARBON_CHECK(block_args.size() >= 2, "no convergence");
  567. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  568. for (auto arg_id : block_args) {
  569. if (inst_block_stack().is_current_block_reachable()) {
  570. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  571. new_block_id = inst_blocks().AddDefaultValue();
  572. }
  573. AddInst<SemIR::BranchWithArg>(
  574. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  575. }
  576. inst_block_stack().Pop();
  577. }
  578. inst_block_stack().Push(new_block_id);
  579. // Acquire the result value.
  580. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  581. return AddInst<SemIR::BlockArg>(
  582. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  583. }
  584. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  585. SemIR::InstId cond_id,
  586. SemIR::InstId if_true,
  587. SemIR::InstId if_false)
  588. -> void {
  589. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  590. // Determine the constant result based on the condition value.
  591. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  592. auto cond_const_id = constant_values().Get(cond_id);
  593. if (!cond_const_id.is_template()) {
  594. // Symbolic or non-constant condition means a non-constant result.
  595. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  596. constant_values().GetInstId(cond_const_id))) {
  597. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  598. : if_false);
  599. } else {
  600. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error,
  601. "Unexpected constant branch condition.");
  602. const_id = SemIR::ConstantId::Error;
  603. }
  604. if (const_id.is_constant()) {
  605. CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
  606. constant_values().GetInstId(const_id));
  607. constant_values().Set(select_id, const_id);
  608. }
  609. }
  610. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  611. CARBON_CHECK(!inst_block_stack().empty(), "no current code block");
  612. if (return_scope_stack().empty()) {
  613. CARBON_CHECK(node_id.is_valid(),
  614. "No current function, but node_id not provided");
  615. TODO(node_id,
  616. "Control flow expressions are currently only supported inside "
  617. "functions.");
  618. return;
  619. }
  620. if (!inst_block_stack().is_current_block_reachable()) {
  621. // Don't include unreachable blocks in the function.
  622. return;
  623. }
  624. auto function_id =
  625. insts()
  626. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  627. .function_id;
  628. functions()
  629. .Get(function_id)
  630. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  631. }
  632. auto Context::is_current_position_reachable() -> bool {
  633. if (!inst_block_stack().is_current_block_reachable()) {
  634. return false;
  635. }
  636. // Our current position is at the end of a reachable block. That position is
  637. // reachable unless the previous instruction is a terminator instruction.
  638. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  639. if (block_contents.empty()) {
  640. return true;
  641. }
  642. const auto& last_inst = insts().Get(block_contents.back());
  643. return last_inst.kind().terminator_kind() !=
  644. SemIR::TerminatorKind::Terminator;
  645. }
  646. auto Context::Finalize() -> void {
  647. // Pop information for the file-level scope.
  648. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  649. scope_stack().Pop();
  650. // Finalizes the list of exports on the IR.
  651. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  652. // Finalizes the ImportRef inst block.
  653. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  654. // Finalizes __global_init.
  655. global_init_.Finalize();
  656. }
  657. namespace {
  658. // Worklist-based type completion mechanism.
  659. //
  660. // When attempting to complete a type, we may find other types that also need to
  661. // be completed: types nested within that type, and the value representation of
  662. // the type. In order to complete a type without recursing arbitrarily deeply,
  663. // we use a worklist of tasks:
  664. //
  665. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  666. // nested within a type to the work list.
  667. // - A `BuildValueRepr` step computes the value representation for a
  668. // type, once all of its nested types are complete, and marks the type as
  669. // complete.
  670. class TypeCompleter {
  671. public:
  672. TypeCompleter(Context& context,
  673. std::optional<Context::BuildDiagnosticFn> diagnoser)
  674. : context_(context), diagnoser_(diagnoser) {}
  675. // Attempts to complete the given type. Returns true if it is now complete,
  676. // false if it could not be completed.
  677. auto Complete(SemIR::TypeId type_id) -> bool {
  678. Push(type_id);
  679. while (!work_list_.empty()) {
  680. if (!ProcessStep()) {
  681. return false;
  682. }
  683. }
  684. return true;
  685. }
  686. private:
  687. // Adds `type_id` to the work list, if it's not already complete.
  688. auto Push(SemIR::TypeId type_id) -> void {
  689. if (!context_.types().IsComplete(type_id)) {
  690. work_list_.push_back(
  691. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  692. }
  693. }
  694. // Runs the next step.
  695. auto ProcessStep() -> bool {
  696. auto [type_id, phase] = work_list_.back();
  697. // We might have enqueued the same type more than once. Just skip the
  698. // type if it's already complete.
  699. if (context_.types().IsComplete(type_id)) {
  700. work_list_.pop_back();
  701. return true;
  702. }
  703. auto inst_id = context_.types().GetInstId(type_id);
  704. auto inst = context_.insts().Get(inst_id);
  705. auto old_work_list_size = work_list_.size();
  706. switch (phase) {
  707. case Phase::AddNestedIncompleteTypes:
  708. if (!AddNestedIncompleteTypes(inst)) {
  709. return false;
  710. }
  711. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  712. "AddNestedIncompleteTypes should not remove work items");
  713. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  714. break;
  715. case Phase::BuildValueRepr: {
  716. auto value_rep = BuildValueRepr(type_id, inst);
  717. context_.types().SetValueRepr(type_id, value_rep);
  718. CARBON_CHECK(old_work_list_size == work_list_.size(),
  719. "BuildValueRepr should not change work items");
  720. work_list_.pop_back();
  721. // Also complete the value representation type, if necessary. This
  722. // should never fail: the value representation shouldn't require any
  723. // additional nested types to be complete.
  724. if (!context_.types().IsComplete(value_rep.type_id)) {
  725. work_list_.push_back(
  726. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  727. }
  728. // For a pointer representation, the pointee also needs to be complete.
  729. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  730. if (value_rep.type_id == SemIR::TypeId::Error) {
  731. break;
  732. }
  733. auto pointee_type_id =
  734. context_.sem_ir().GetPointeeType(value_rep.type_id);
  735. if (!context_.types().IsComplete(pointee_type_id)) {
  736. work_list_.push_back(
  737. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  738. }
  739. }
  740. break;
  741. }
  742. }
  743. return true;
  744. }
  745. // Adds any types nested within `type_inst` that need to be complete for
  746. // `type_inst` to be complete to our work list.
  747. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  748. CARBON_KIND_SWITCH(type_inst) {
  749. case CARBON_KIND(SemIR::ArrayType inst): {
  750. Push(inst.element_type_id);
  751. break;
  752. }
  753. case CARBON_KIND(SemIR::StructType inst): {
  754. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  755. Push(context_.insts()
  756. .GetAs<SemIR::StructTypeField>(field_id)
  757. .field_type_id);
  758. }
  759. break;
  760. }
  761. case CARBON_KIND(SemIR::TupleType inst): {
  762. for (auto element_type_id :
  763. context_.type_blocks().Get(inst.elements_id)) {
  764. Push(element_type_id);
  765. }
  766. break;
  767. }
  768. case CARBON_KIND(SemIR::ClassType inst): {
  769. auto& class_info = context_.classes().Get(inst.class_id);
  770. if (!class_info.is_defined()) {
  771. if (diagnoser_) {
  772. auto builder = (*diagnoser_)();
  773. context_.NoteIncompleteClass(inst.class_id, builder);
  774. builder.Emit();
  775. }
  776. return false;
  777. }
  778. if (inst.specific_id.is_valid()) {
  779. ResolveSpecificDefinition(context_, inst.specific_id);
  780. }
  781. Push(class_info.object_repr_id);
  782. break;
  783. }
  784. case CARBON_KIND(SemIR::ConstType inst): {
  785. Push(inst.inner_id);
  786. break;
  787. }
  788. default:
  789. break;
  790. }
  791. return true;
  792. }
  793. // Makes an empty value representation, which is used for types that have no
  794. // state, such as empty structs and tuples.
  795. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  796. return {.kind = SemIR::ValueRepr::None,
  797. .type_id = context_.GetTupleType({})};
  798. }
  799. // Makes a value representation that uses pass-by-copy, copying the given
  800. // type.
  801. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  802. SemIR::ValueRepr::AggregateKind aggregate_kind =
  803. SemIR::ValueRepr::NotAggregate) const
  804. -> SemIR::ValueRepr {
  805. return {.kind = SemIR::ValueRepr::Copy,
  806. .aggregate_kind = aggregate_kind,
  807. .type_id = rep_id};
  808. }
  809. // Makes a value representation that uses pass-by-address with the given
  810. // pointee type.
  811. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  812. SemIR::ValueRepr::AggregateKind aggregate_kind =
  813. SemIR::ValueRepr::NotAggregate) const
  814. -> SemIR::ValueRepr {
  815. // TODO: Should we add `const` qualification to `pointee_id`?
  816. return {.kind = SemIR::ValueRepr::Pointer,
  817. .aggregate_kind = aggregate_kind,
  818. .type_id = context_.GetPointerType(pointee_id)};
  819. }
  820. // Gets the value representation of a nested type, which should already be
  821. // complete.
  822. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  823. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  824. "Nested type should already be complete");
  825. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  826. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown,
  827. "Complete type should have a value representation");
  828. return value_rep;
  829. }
  830. auto BuildValueReprForInst(SemIR::TypeId type_id,
  831. SemIR::BuiltinInst builtin) const
  832. -> SemIR::ValueRepr {
  833. switch (builtin.builtin_inst_kind) {
  834. case SemIR::BuiltinInstKind::TypeType:
  835. case SemIR::BuiltinInstKind::Error:
  836. case SemIR::BuiltinInstKind::Invalid:
  837. case SemIR::BuiltinInstKind::BoolType:
  838. case SemIR::BuiltinInstKind::IntType:
  839. case SemIR::BuiltinInstKind::FloatType:
  840. case SemIR::BuiltinInstKind::NamespaceType:
  841. case SemIR::BuiltinInstKind::BoundMethodType:
  842. case SemIR::BuiltinInstKind::WitnessType:
  843. return MakeCopyValueRepr(type_id);
  844. case SemIR::BuiltinInstKind::StringType:
  845. // TODO: Decide on string value semantics. This should probably be a
  846. // custom value representation carrying a pointer and size or
  847. // similar.
  848. return MakePointerValueRepr(type_id);
  849. }
  850. llvm_unreachable("All builtin kinds were handled above");
  851. }
  852. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  853. SemIR::TypeId elementwise_rep,
  854. bool same_as_object_rep) const
  855. -> SemIR::ValueRepr {
  856. SemIR::ValueRepr::AggregateKind aggregate_kind =
  857. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  858. : SemIR::ValueRepr::ValueAggregate;
  859. if (num_elements == 1) {
  860. // The value representation for a struct or tuple with a single element
  861. // is a struct or tuple containing the value representation of the
  862. // element.
  863. // TODO: Consider doing the same whenever `elementwise_rep` is
  864. // sufficiently small.
  865. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  866. }
  867. // For a struct or tuple with multiple fields, we use a pointer
  868. // to the elementwise value representation.
  869. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  870. }
  871. auto BuildValueReprForInst(SemIR::TypeId type_id,
  872. SemIR::StructType struct_type) const
  873. -> SemIR::ValueRepr {
  874. // TODO: Share more code with tuples.
  875. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  876. if (fields.empty()) {
  877. return MakeEmptyValueRepr();
  878. }
  879. // Find the value representation for each field, and construct a struct
  880. // of value representations.
  881. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  882. value_rep_fields.reserve(fields.size());
  883. bool same_as_object_rep = true;
  884. for (auto field_id : fields) {
  885. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  886. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  887. if (field_value_rep.type_id != field.field_type_id) {
  888. same_as_object_rep = false;
  889. field.field_type_id = field_value_rep.type_id;
  890. field_id = context_.constant_values().GetInstId(
  891. TryEvalInst(context_, SemIR::InstId::Invalid, field));
  892. }
  893. value_rep_fields.push_back(field_id);
  894. }
  895. auto value_rep = same_as_object_rep
  896. ? type_id
  897. : context_.GetStructType(
  898. context_.inst_blocks().Add(value_rep_fields));
  899. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  900. same_as_object_rep);
  901. }
  902. auto BuildValueReprForInst(SemIR::TypeId type_id,
  903. SemIR::TupleType tuple_type) const
  904. -> SemIR::ValueRepr {
  905. // TODO: Share more code with structs.
  906. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  907. if (elements.empty()) {
  908. return MakeEmptyValueRepr();
  909. }
  910. // Find the value representation for each element, and construct a tuple
  911. // of value representations.
  912. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  913. value_rep_elements.reserve(elements.size());
  914. bool same_as_object_rep = true;
  915. for (auto element_type_id : elements) {
  916. auto element_value_rep = GetNestedValueRepr(element_type_id);
  917. if (element_value_rep.type_id != element_type_id) {
  918. same_as_object_rep = false;
  919. }
  920. value_rep_elements.push_back(element_value_rep.type_id);
  921. }
  922. auto value_rep = same_as_object_rep
  923. ? type_id
  924. : context_.GetTupleType(value_rep_elements);
  925. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  926. same_as_object_rep);
  927. }
  928. auto BuildValueReprForInst(SemIR::TypeId type_id,
  929. SemIR::ArrayType /*inst*/) const
  930. -> SemIR::ValueRepr {
  931. // For arrays, it's convenient to always use a pointer representation,
  932. // even when the array has zero or one element, in order to support
  933. // indexing.
  934. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  935. }
  936. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  937. SemIR::ClassType inst) const -> SemIR::ValueRepr {
  938. auto& class_info = context_.classes().Get(inst.class_id);
  939. // The value representation of an adapter is the value representation of
  940. // its adapted type.
  941. if (class_info.adapt_id.is_valid()) {
  942. return GetNestedValueRepr(class_info.object_repr_id);
  943. }
  944. // Otherwise, the value representation for a class is a pointer to the
  945. // object representation.
  946. // TODO: Support customized value representations for classes.
  947. // TODO: Pick a better value representation when possible.
  948. return MakePointerValueRepr(class_info.object_repr_id,
  949. SemIR::ValueRepr::ObjectAggregate);
  950. }
  951. template <typename InstT>
  952. requires(InstT::Kind.template IsAnyOf<
  953. SemIR::AssociatedEntityType, SemIR::FunctionType,
  954. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  955. SemIR::InterfaceType, SemIR::UnboundElementType>())
  956. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  957. -> SemIR::ValueRepr {
  958. // These types have no runtime operations, so we use an empty value
  959. // representation.
  960. //
  961. // TODO: There is information we could model here:
  962. // - For an interface, we could use a witness.
  963. // - For an associated entity, we could use an index into the witness.
  964. // - For an unbound element, we could use an index or offset.
  965. return MakeEmptyValueRepr();
  966. }
  967. template <typename InstT>
  968. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  969. SemIR::InterfaceWitnessAccess>())
  970. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  971. -> SemIR::ValueRepr {
  972. // For symbolic types, we arbitrarily pick a copy representation.
  973. return MakeCopyValueRepr(type_id);
  974. }
  975. template <typename InstT>
  976. requires(InstT::Kind.template IsAnyOf<SemIR::FloatType, SemIR::IntType,
  977. SemIR::PointerType>())
  978. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  979. -> SemIR::ValueRepr {
  980. return MakeCopyValueRepr(type_id);
  981. }
  982. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  983. SemIR::ConstType inst) const -> SemIR::ValueRepr {
  984. // The value representation of `const T` is the same as that of `T`.
  985. // Objects are not modifiable through their value representations.
  986. return GetNestedValueRepr(inst.inner_id);
  987. }
  988. template <typename InstT>
  989. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  990. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  991. -> SemIR::ValueRepr {
  992. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  993. }
  994. // Builds and returns the value representation for the given type. All nested
  995. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  996. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  997. -> SemIR::ValueRepr {
  998. // Use overload resolution to select the implementation, producing compile
  999. // errors when BuildTypeForInst isn't defined for a given instruction.
  1000. CARBON_KIND_SWITCH(inst) {
  1001. #define CARBON_SEM_IR_INST_KIND(Name) \
  1002. case CARBON_KIND(SemIR::Name typed_inst): { \
  1003. return BuildValueReprForInst(type_id, typed_inst); \
  1004. }
  1005. #include "toolchain/sem_ir/inst_kind.def"
  1006. }
  1007. }
  1008. enum class Phase : int8_t {
  1009. // The next step is to add nested types to the list of types to complete.
  1010. AddNestedIncompleteTypes,
  1011. // The next step is to build the value representation for the type.
  1012. BuildValueRepr,
  1013. };
  1014. struct WorkItem {
  1015. SemIR::TypeId type_id;
  1016. Phase phase;
  1017. };
  1018. Context& context_;
  1019. llvm::SmallVector<WorkItem> work_list_;
  1020. std::optional<Context::BuildDiagnosticFn> diagnoser_;
  1021. };
  1022. } // namespace
  1023. auto Context::TryToCompleteType(SemIR::TypeId type_id,
  1024. std::optional<BuildDiagnosticFn> diagnoser)
  1025. -> bool {
  1026. return TypeCompleter(*this, diagnoser).Complete(type_id);
  1027. }
  1028. auto Context::TryToDefineType(SemIR::TypeId type_id,
  1029. std::optional<BuildDiagnosticFn> diagnoser)
  1030. -> bool {
  1031. if (!TryToCompleteType(type_id, diagnoser)) {
  1032. return false;
  1033. }
  1034. if (auto interface = types().TryGetAs<SemIR::InterfaceType>(type_id)) {
  1035. auto interface_id = interface->interface_id;
  1036. if (!interfaces().Get(interface_id).is_defined()) {
  1037. auto builder = (*diagnoser)();
  1038. NoteUndefinedInterface(interface_id, builder);
  1039. builder.Emit();
  1040. return false;
  1041. }
  1042. if (interface->specific_id.is_valid()) {
  1043. ResolveSpecificDefinition(*this, interface->specific_id);
  1044. }
  1045. }
  1046. return true;
  1047. }
  1048. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  1049. -> SemIR::TypeId {
  1050. CARBON_CHECK(constant_id.is_constant(),
  1051. "Canonicalizing non-constant type: {0}", constant_id);
  1052. auto type_id =
  1053. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  1054. // TODO: For now, we allow values of facet type to be used as types.
  1055. CARBON_CHECK(type_id == SemIR::TypeId::TypeType ||
  1056. types().Is<SemIR::InterfaceType>(type_id) ||
  1057. constant_id == SemIR::ConstantId::Error,
  1058. "Forming type ID for non-type constant of type {0}",
  1059. types().GetAsInst(type_id));
  1060. return SemIR::TypeId::ForTypeConstant(constant_id);
  1061. }
  1062. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  1063. template <typename InstT, typename... EachArgT>
  1064. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  1065. -> SemIR::TypeId {
  1066. // TODO: Remove inst_id parameter from TryEvalInst.
  1067. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  1068. return context.GetTypeIdForTypeConstant(
  1069. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  1070. }
  1071. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  1072. // and completes the type. This should only be used when type completion cannot
  1073. // fail.
  1074. template <typename InstT, typename... EachArgT>
  1075. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  1076. -> SemIR::TypeId {
  1077. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  1078. bool complete = context.TryToCompleteType(type_id);
  1079. CARBON_CHECK(complete, "Type completion should not fail");
  1080. return type_id;
  1081. }
  1082. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  1083. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  1084. }
  1085. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1086. -> SemIR::TypeId {
  1087. return GetTypeImpl<SemIR::TupleType>(*this,
  1088. type_blocks().AddCanonical(type_ids));
  1089. }
  1090. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  1091. SemIR::TypeId entity_type_id)
  1092. -> SemIR::TypeId {
  1093. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id,
  1094. entity_type_id);
  1095. }
  1096. auto Context::GetBuiltinType(SemIR::BuiltinInstKind kind) -> SemIR::TypeId {
  1097. CARBON_CHECK(kind != SemIR::BuiltinInstKind::Invalid);
  1098. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  1099. // To keep client code simpler, complete builtin types before returning them.
  1100. bool complete = TryToCompleteType(type_id);
  1101. CARBON_CHECK(complete, "Failed to complete builtin type");
  1102. return type_id;
  1103. }
  1104. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  1105. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1106. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  1107. }
  1108. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  1109. SemIR::SpecificId enclosing_specific_id)
  1110. -> SemIR::TypeId {
  1111. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  1112. enclosing_specific_id);
  1113. }
  1114. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  1115. SemIR::SpecificId enclosing_specific_id)
  1116. -> SemIR::TypeId {
  1117. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  1118. *this, interface_id, enclosing_specific_id);
  1119. }
  1120. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1121. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1122. }
  1123. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1124. SemIR::TypeId element_type_id)
  1125. -> SemIR::TypeId {
  1126. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1127. element_type_id);
  1128. }
  1129. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1130. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1131. return const_type->inner_id;
  1132. }
  1133. return type_id;
  1134. }
  1135. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1136. output << "Check::Context\n";
  1137. // In a stack dump, this is probably indented by a tab. We treat that as 8
  1138. // spaces then add a couple to indent past the Context label.
  1139. constexpr int Indent = 10;
  1140. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  1141. node_stack_.PrintForStackDump(formatter, Indent, output);
  1142. inst_block_stack_.PrintForStackDump(formatter, Indent, output);
  1143. param_and_arg_refs_stack_.PrintForStackDump(formatter, Indent, output);
  1144. args_type_info_stack_.PrintForStackDump(formatter, Indent, output);
  1145. }
  1146. auto Context::DumpFormattedFile() const -> void {
  1147. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  1148. formatter.Print(llvm::errs());
  1149. }
  1150. } // namespace Carbon::Check