context.cpp 56 KB

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