context.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. SemIR::LocId loc_id, 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), loc_id, [&] {
  465. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  466. "member access into incomplete class {0}",
  467. InstIdAsType);
  468. return emitter().Build(loc_id, QualifiedExprInIncompleteClassScope,
  469. base_id);
  470. });
  471. auto& class_info = classes().Get(base_as_class->class_id);
  472. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  473. .specific_id = base_as_class->specific_id});
  474. return true;
  475. }
  476. if (auto base_as_facet_type = base.TryAs<SemIR::FacetType>()) {
  477. TryToDefineType(GetTypeIdForTypeConstant(base_const_id), loc_id, [&] {
  478. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  479. "member access into undefined interface {0}",
  480. InstIdAsType);
  481. return emitter().Build(loc_id, QualifiedExprInUndefinedInterfaceScope,
  482. base_id);
  483. });
  484. const auto& facet_type_info =
  485. facet_types().Get(base_as_facet_type->facet_type_id);
  486. for (auto interface : facet_type_info.impls_constraints) {
  487. auto& interface_info = interfaces().Get(interface.interface_id);
  488. scopes->push_back(LookupScope{.name_scope_id = interface_info.scope_id,
  489. .specific_id = interface.specific_id});
  490. }
  491. return true;
  492. }
  493. if (base_const_id == SemIR::ErrorInst::SingletonConstantId) {
  494. // Lookup into this scope should fail without producing an error.
  495. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::Invalid,
  496. .specific_id = SemIR::SpecificId::Invalid});
  497. return true;
  498. }
  499. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  500. // treat it as a name scope, even if it doesn't have members. For example,
  501. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  502. // there's no name `X` in `type`.
  503. return false;
  504. }
  505. auto Context::LookupQualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id,
  506. llvm::ArrayRef<LookupScope> lookup_scopes,
  507. bool required,
  508. std::optional<AccessInfo> access_info)
  509. -> LookupResult {
  510. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  511. // TODO: Support reporting of multiple prohibited access.
  512. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  513. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  514. .inst_id = SemIR::InstId::Invalid};
  515. bool has_error = false;
  516. bool is_parent_access = false;
  517. // Walk this scope and, if nothing is found here, the scopes it extends.
  518. while (!scopes.empty()) {
  519. auto [scope_id, specific_id] = scopes.pop_back_val();
  520. if (!scope_id.is_valid()) {
  521. has_error = true;
  522. continue;
  523. }
  524. const auto& name_scope = name_scopes().Get(scope_id);
  525. has_error |= name_scope.has_error();
  526. auto [scope_result_id, access_kind] =
  527. LookupNameInExactScope(loc_id, name_id, scope_id, name_scope);
  528. auto is_access_prohibited =
  529. IsAccessProhibited(access_info, access_kind, is_parent_access);
  530. // Keep track of prohibited accesses, this will be useful for reporting
  531. // multiple prohibited accesses if we can't find a suitable lookup.
  532. if (is_access_prohibited) {
  533. prohibited_accesses.push_back({
  534. .scope_result_id = scope_result_id,
  535. .access_kind = access_kind,
  536. .is_parent_access = is_parent_access,
  537. });
  538. }
  539. if (!scope_result_id.is_valid() || is_access_prohibited) {
  540. // If nothing is found in this scope or if we encountered an invalid
  541. // access, look in its extended scopes.
  542. const auto& extended = name_scope.extended_scopes();
  543. scopes.reserve(scopes.size() + extended.size());
  544. for (auto extended_id : llvm::reverse(extended)) {
  545. // Substitute into the constant describing the extended scope to
  546. // determine its corresponding specific.
  547. CARBON_CHECK(extended_id.is_valid());
  548. LoadImportRef(*this, extended_id);
  549. SemIR::ConstantId const_id =
  550. GetConstantValueInSpecific(sem_ir(), specific_id, extended_id);
  551. DiagnosticAnnotationScope annotate_diagnostics(
  552. &emitter(), [&](auto& builder) {
  553. CARBON_DIAGNOSTIC(FromExtendHere, Note,
  554. "declared as an extended scope here");
  555. builder.Note(extended_id, FromExtendHere);
  556. });
  557. if (!AppendLookupScopesForConstant(loc_id, const_id, &scopes)) {
  558. // TODO: Handle case where we have a symbolic type and instead should
  559. // look in its type.
  560. }
  561. }
  562. is_parent_access |= !extended.empty();
  563. continue;
  564. }
  565. // If this is our second lookup result, diagnose an ambiguity.
  566. if (result.inst_id.is_valid()) {
  567. CARBON_DIAGNOSTIC(
  568. NameAmbiguousDueToExtend, Error,
  569. "ambiguous use of name `{0}` found in multiple extended scopes",
  570. SemIR::NameId);
  571. emitter_->Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  572. // TODO: Add notes pointing to the scopes.
  573. return {.specific_id = SemIR::SpecificId::Invalid,
  574. .inst_id = SemIR::ErrorInst::SingletonInstId};
  575. }
  576. result.inst_id = scope_result_id;
  577. result.specific_id = specific_id;
  578. }
  579. if (required && !result.inst_id.is_valid()) {
  580. if (!has_error) {
  581. if (prohibited_accesses.empty()) {
  582. DiagnoseMemberNameNotFound(loc_id, name_id, lookup_scopes);
  583. } else {
  584. // TODO: We should report multiple prohibited accesses in case we don't
  585. // find a valid lookup. Reporting the last one should suffice for now.
  586. auto [scope_result_id, access_kind, is_parent_access] =
  587. prohibited_accesses.back();
  588. // Note, `access_info` is guaranteed to have a value here, since
  589. // `prohibited_accesses` is non-empty.
  590. DiagnoseInvalidQualifiedNameAccess(*this, loc_id, scope_result_id,
  591. name_id, access_kind,
  592. is_parent_access, *access_info);
  593. }
  594. }
  595. return {.specific_id = SemIR::SpecificId::Invalid,
  596. .inst_id = SemIR::ErrorInst::SingletonInstId};
  597. }
  598. return result;
  599. }
  600. // Returns the scope of the Core package, or Invalid if it's not found.
  601. //
  602. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  603. // name lookup to find it.
  604. static auto GetCorePackage(Context& context, SemIRLoc loc, llvm::StringRef name)
  605. -> SemIR::NameScopeId {
  606. auto core_ident_id = context.identifiers().Add("Core");
  607. auto packaging = context.parse_tree().packaging_decl();
  608. if (packaging && packaging->names.package_id == core_ident_id) {
  609. return SemIR::NameScopeId::Package;
  610. }
  611. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  612. // Look up `package.Core`.
  613. auto [core_inst_id, _] = context.LookupNameInExactScope(
  614. loc, core_name_id, SemIR::NameScopeId::Package,
  615. context.name_scopes().Get(SemIR::NameScopeId::Package));
  616. if (core_inst_id.is_valid()) {
  617. // We expect it to be a namespace.
  618. if (auto namespace_inst =
  619. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  620. // TODO: Decide whether to allow the case where `Core` is not a package.
  621. return namespace_inst->name_scope_id;
  622. }
  623. }
  624. CARBON_DIAGNOSTIC(
  625. CoreNotFound, Error,
  626. "`Core.{0}` implicitly referenced here, but package `Core` not found",
  627. std::string);
  628. context.emitter().Emit(loc, CoreNotFound, name.str());
  629. return SemIR::NameScopeId::Invalid;
  630. }
  631. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  632. -> SemIR::InstId {
  633. auto core_package_id = GetCorePackage(*this, loc, name);
  634. if (!core_package_id.is_valid()) {
  635. return SemIR::ErrorInst::SingletonInstId;
  636. }
  637. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  638. auto [inst_id, _] = LookupNameInExactScope(
  639. loc, name_id, core_package_id, name_scopes().Get(core_package_id));
  640. if (!inst_id.is_valid()) {
  641. CARBON_DIAGNOSTIC(
  642. CoreNameNotFound, Error,
  643. "name `Core.{0}` implicitly referenced here, but not found",
  644. SemIR::NameId);
  645. emitter_->Emit(loc, CoreNameNotFound, name_id);
  646. return SemIR::ErrorInst::SingletonInstId;
  647. }
  648. // Look through import_refs and aliases.
  649. return constant_values().GetConstantInstId(inst_id);
  650. }
  651. template <typename BranchNode, typename... Args>
  652. static auto AddDominatedBlockAndBranchImpl(Context& context,
  653. Parse::NodeId node_id, Args... args)
  654. -> SemIR::InstBlockId {
  655. if (!context.inst_block_stack().is_current_block_reachable()) {
  656. return SemIR::InstBlockId::Unreachable;
  657. }
  658. auto block_id = context.inst_blocks().AddDefaultValue();
  659. context.AddInst<BranchNode>(node_id, {block_id, args...});
  660. return block_id;
  661. }
  662. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  663. -> SemIR::InstBlockId {
  664. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  665. }
  666. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  667. SemIR::InstId arg_id)
  668. -> SemIR::InstBlockId {
  669. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  670. arg_id);
  671. }
  672. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  673. SemIR::InstId cond_id)
  674. -> SemIR::InstBlockId {
  675. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  676. cond_id);
  677. }
  678. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  679. -> void {
  680. CARBON_CHECK(num_blocks >= 2, "no convergence");
  681. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  682. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  683. if (inst_block_stack().is_current_block_reachable()) {
  684. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  685. new_block_id = inst_blocks().AddDefaultValue();
  686. }
  687. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  688. }
  689. inst_block_stack().Pop();
  690. }
  691. inst_block_stack().Push(new_block_id);
  692. }
  693. auto Context::AddConvergenceBlockWithArgAndPush(
  694. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  695. -> SemIR::InstId {
  696. CARBON_CHECK(block_args.size() >= 2, "no convergence");
  697. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  698. for (auto arg_id : block_args) {
  699. if (inst_block_stack().is_current_block_reachable()) {
  700. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  701. new_block_id = inst_blocks().AddDefaultValue();
  702. }
  703. AddInst<SemIR::BranchWithArg>(
  704. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  705. }
  706. inst_block_stack().Pop();
  707. }
  708. inst_block_stack().Push(new_block_id);
  709. // Acquire the result value.
  710. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  711. return AddInst<SemIR::BlockArg>(
  712. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  713. }
  714. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  715. SemIR::InstId cond_id,
  716. SemIR::InstId if_true,
  717. SemIR::InstId if_false)
  718. -> void {
  719. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  720. // Determine the constant result based on the condition value.
  721. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  722. auto cond_const_id = constant_values().Get(cond_id);
  723. if (!cond_const_id.is_template()) {
  724. // Symbolic or non-constant condition means a non-constant result.
  725. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  726. constant_values().GetInstId(cond_const_id))) {
  727. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  728. : if_false);
  729. } else {
  730. CARBON_CHECK(cond_const_id == SemIR::ErrorInst::SingletonConstantId,
  731. "Unexpected constant branch condition.");
  732. const_id = SemIR::ErrorInst::SingletonConstantId;
  733. }
  734. if (const_id.is_constant()) {
  735. CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
  736. constant_values().GetInstId(const_id));
  737. constant_values().Set(select_id, const_id);
  738. }
  739. }
  740. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  741. CARBON_CHECK(!inst_block_stack().empty(), "no current code block");
  742. if (return_scope_stack().empty()) {
  743. CARBON_CHECK(node_id.is_valid(),
  744. "No current function, but node_id not provided");
  745. TODO(node_id,
  746. "Control flow expressions are currently only supported inside "
  747. "functions.");
  748. return;
  749. }
  750. if (!inst_block_stack().is_current_block_reachable()) {
  751. // Don't include unreachable blocks in the function.
  752. return;
  753. }
  754. auto function_id =
  755. insts()
  756. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  757. .function_id;
  758. functions()
  759. .Get(function_id)
  760. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  761. }
  762. auto Context::is_current_position_reachable() -> bool {
  763. if (!inst_block_stack().is_current_block_reachable()) {
  764. return false;
  765. }
  766. // Our current position is at the end of a reachable block. That position is
  767. // reachable unless the previous instruction is a terminator instruction.
  768. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  769. if (block_contents.empty()) {
  770. return true;
  771. }
  772. const auto& last_inst = insts().Get(block_contents.back());
  773. return last_inst.kind().terminator_kind() !=
  774. SemIR::TerminatorKind::Terminator;
  775. }
  776. auto Context::Finalize() -> void {
  777. // Pop information for the file-level scope.
  778. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  779. scope_stack().Pop();
  780. // Finalizes the list of exports on the IR.
  781. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  782. // Finalizes the ImportRef inst block.
  783. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  784. // Finalizes __global_init.
  785. global_init_.Finalize();
  786. }
  787. namespace {
  788. // Worklist-based type completion mechanism.
  789. //
  790. // When attempting to complete a type, we may find other types that also need to
  791. // be completed: types nested within that type, and the value representation of
  792. // the type. In order to complete a type without recursing arbitrarily deeply,
  793. // we use a worklist of tasks:
  794. //
  795. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  796. // nested within a type to the work list.
  797. // - A `BuildValueRepr` step computes the value representation for a
  798. // type, once all of its nested types are complete, and marks the type as
  799. // complete.
  800. class TypeCompleter {
  801. public:
  802. TypeCompleter(Context& context, Context::BuildDiagnosticFn diagnoser)
  803. : context_(context), diagnoser_(diagnoser) {}
  804. // Attempts to complete the given type. Returns true if it is now complete,
  805. // false if it could not be completed.
  806. auto Complete(SemIR::TypeId type_id) -> bool {
  807. Push(type_id);
  808. while (!work_list_.empty()) {
  809. if (!ProcessStep()) {
  810. return false;
  811. }
  812. }
  813. return true;
  814. }
  815. private:
  816. // Adds `type_id` to the work list, if it's not already complete.
  817. auto Push(SemIR::TypeId type_id) -> void {
  818. if (!context_.types().IsComplete(type_id)) {
  819. work_list_.push_back(
  820. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  821. }
  822. }
  823. // Runs the next step.
  824. auto ProcessStep() -> bool {
  825. auto [type_id, phase] = work_list_.back();
  826. // We might have enqueued the same type more than once. Just skip the
  827. // type if it's already complete.
  828. if (context_.types().IsComplete(type_id)) {
  829. work_list_.pop_back();
  830. return true;
  831. }
  832. auto inst_id = context_.types().GetInstId(type_id);
  833. auto inst = context_.insts().Get(inst_id);
  834. auto old_work_list_size = work_list_.size();
  835. switch (phase) {
  836. case Phase::AddNestedIncompleteTypes:
  837. if (!AddNestedIncompleteTypes(inst)) {
  838. return false;
  839. }
  840. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  841. "AddNestedIncompleteTypes should not remove work items");
  842. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  843. break;
  844. case Phase::BuildValueRepr: {
  845. auto value_rep = BuildValueRepr(type_id, inst);
  846. context_.types().SetValueRepr(type_id, value_rep);
  847. CARBON_CHECK(old_work_list_size == work_list_.size(),
  848. "BuildValueRepr should not change work items");
  849. work_list_.pop_back();
  850. // Also complete the value representation type, if necessary. This
  851. // should never fail: the value representation shouldn't require any
  852. // additional nested types to be complete.
  853. if (!context_.types().IsComplete(value_rep.type_id)) {
  854. work_list_.push_back(
  855. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  856. }
  857. // For a pointer representation, the pointee also needs to be complete.
  858. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  859. if (value_rep.type_id == SemIR::ErrorInst::SingletonTypeId) {
  860. break;
  861. }
  862. auto pointee_type_id =
  863. context_.sem_ir().GetPointeeType(value_rep.type_id);
  864. if (!context_.types().IsComplete(pointee_type_id)) {
  865. work_list_.push_back(
  866. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  867. }
  868. }
  869. break;
  870. }
  871. }
  872. return true;
  873. }
  874. // Adds any types nested within `type_inst` that need to be complete for
  875. // `type_inst` to be complete to our work list.
  876. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  877. CARBON_KIND_SWITCH(type_inst) {
  878. case CARBON_KIND(SemIR::ArrayType inst): {
  879. Push(inst.element_type_id);
  880. break;
  881. }
  882. case CARBON_KIND(SemIR::StructType inst): {
  883. for (auto field : context_.struct_type_fields().Get(inst.fields_id)) {
  884. Push(field.type_id);
  885. }
  886. break;
  887. }
  888. case CARBON_KIND(SemIR::TupleType inst): {
  889. for (auto element_type_id :
  890. context_.type_blocks().Get(inst.elements_id)) {
  891. Push(element_type_id);
  892. }
  893. break;
  894. }
  895. case CARBON_KIND(SemIR::ClassType inst): {
  896. auto& class_info = context_.classes().Get(inst.class_id);
  897. if (!class_info.is_defined()) {
  898. if (diagnoser_) {
  899. auto builder = diagnoser_();
  900. context_.NoteIncompleteClass(inst.class_id, builder);
  901. builder.Emit();
  902. }
  903. return false;
  904. }
  905. if (inst.specific_id.is_valid()) {
  906. ResolveSpecificDefinition(context_, inst.specific_id);
  907. }
  908. if (auto adapted_type_id =
  909. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  910. adapted_type_id.is_valid()) {
  911. Push(adapted_type_id);
  912. } else {
  913. Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
  914. }
  915. break;
  916. }
  917. case CARBON_KIND(SemIR::ConstType inst): {
  918. Push(inst.inner_id);
  919. break;
  920. }
  921. default:
  922. break;
  923. }
  924. return true;
  925. }
  926. // Makes an empty value representation, which is used for types that have no
  927. // state, such as empty structs and tuples.
  928. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  929. return {.kind = SemIR::ValueRepr::None,
  930. .type_id = context_.GetTupleType({})};
  931. }
  932. // Makes a value representation that uses pass-by-copy, copying the given
  933. // type.
  934. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  935. SemIR::ValueRepr::AggregateKind aggregate_kind =
  936. SemIR::ValueRepr::NotAggregate) const
  937. -> SemIR::ValueRepr {
  938. return {.kind = SemIR::ValueRepr::Copy,
  939. .aggregate_kind = aggregate_kind,
  940. .type_id = rep_id};
  941. }
  942. // Makes a value representation that uses pass-by-address with the given
  943. // pointee type.
  944. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  945. SemIR::ValueRepr::AggregateKind aggregate_kind =
  946. SemIR::ValueRepr::NotAggregate) const
  947. -> SemIR::ValueRepr {
  948. // TODO: Should we add `const` qualification to `pointee_id`?
  949. return {.kind = SemIR::ValueRepr::Pointer,
  950. .aggregate_kind = aggregate_kind,
  951. .type_id = context_.GetPointerType(pointee_id)};
  952. }
  953. // Gets the value representation of a nested type, which should already be
  954. // complete.
  955. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  956. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  957. "Nested type should already be complete");
  958. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  959. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown,
  960. "Complete type should have a value representation");
  961. return value_rep;
  962. }
  963. template <typename InstT>
  964. requires(InstT::Kind.template IsAnyOf<
  965. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  966. SemIR::ErrorInst, SemIR::IntLiteralType, SemIR::LegacyFloatType,
  967. SemIR::NamespaceType, SemIR::SpecificFunctionType, SemIR::TypeType,
  968. SemIR::VtableType, SemIR::WitnessType>())
  969. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  970. -> SemIR::ValueRepr {
  971. return MakeCopyValueRepr(type_id);
  972. }
  973. auto BuildValueReprForInst(SemIR::TypeId type_id,
  974. SemIR::StringType /*inst*/) const
  975. -> SemIR::ValueRepr {
  976. // TODO: Decide on string value semantics. This should probably be a
  977. // custom value representation carrying a pointer and size or
  978. // similar.
  979. return MakePointerValueRepr(type_id);
  980. }
  981. auto BuildStructOrTupleValueRepr(size_t num_elements,
  982. SemIR::TypeId elementwise_rep,
  983. bool same_as_object_rep) const
  984. -> SemIR::ValueRepr {
  985. SemIR::ValueRepr::AggregateKind aggregate_kind =
  986. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  987. : SemIR::ValueRepr::ValueAggregate;
  988. if (num_elements == 1) {
  989. // The value representation for a struct or tuple with a single element
  990. // is a struct or tuple containing the value representation of the
  991. // element.
  992. // TODO: Consider doing the same whenever `elementwise_rep` is
  993. // sufficiently small.
  994. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  995. }
  996. // For a struct or tuple with multiple fields, we use a pointer
  997. // to the elementwise value representation.
  998. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  999. }
  1000. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1001. SemIR::StructType struct_type) const
  1002. -> SemIR::ValueRepr {
  1003. auto fields = context_.struct_type_fields().Get(struct_type.fields_id);
  1004. if (fields.empty()) {
  1005. return MakeEmptyValueRepr();
  1006. }
  1007. // Find the value representation for each field, and construct a struct
  1008. // of value representations.
  1009. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  1010. value_rep_fields.reserve(fields.size());
  1011. bool same_as_object_rep = true;
  1012. for (auto field : fields) {
  1013. auto field_value_rep = GetNestedValueRepr(field.type_id);
  1014. if (!field_value_rep.IsCopyOfObjectRepr(context_.sem_ir(),
  1015. field.type_id)) {
  1016. same_as_object_rep = false;
  1017. field.type_id = field_value_rep.type_id;
  1018. }
  1019. value_rep_fields.push_back(field);
  1020. }
  1021. auto value_rep =
  1022. same_as_object_rep
  1023. ? type_id
  1024. : context_.GetStructType(
  1025. context_.struct_type_fields().AddCanonical(value_rep_fields));
  1026. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  1027. same_as_object_rep);
  1028. }
  1029. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1030. SemIR::TupleType tuple_type) const
  1031. -> SemIR::ValueRepr {
  1032. // TODO: Share more code with structs.
  1033. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  1034. if (elements.empty()) {
  1035. return MakeEmptyValueRepr();
  1036. }
  1037. // Find the value representation for each element, and construct a tuple
  1038. // of value representations.
  1039. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  1040. value_rep_elements.reserve(elements.size());
  1041. bool same_as_object_rep = true;
  1042. for (auto element_type_id : elements) {
  1043. auto element_value_rep = GetNestedValueRepr(element_type_id);
  1044. if (!element_value_rep.IsCopyOfObjectRepr(context_.sem_ir(),
  1045. element_type_id)) {
  1046. same_as_object_rep = false;
  1047. }
  1048. value_rep_elements.push_back(element_value_rep.type_id);
  1049. }
  1050. auto value_rep = same_as_object_rep
  1051. ? type_id
  1052. : context_.GetTupleType(value_rep_elements);
  1053. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  1054. same_as_object_rep);
  1055. }
  1056. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1057. SemIR::ArrayType /*inst*/) const
  1058. -> SemIR::ValueRepr {
  1059. // For arrays, it's convenient to always use a pointer representation,
  1060. // even when the array has zero or one element, in order to support
  1061. // indexing.
  1062. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  1063. }
  1064. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  1065. SemIR::ClassType inst) const -> SemIR::ValueRepr {
  1066. auto& class_info = context_.classes().Get(inst.class_id);
  1067. // The value representation of an adapter is the value representation of
  1068. // its adapted type.
  1069. if (auto adapted_type_id =
  1070. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  1071. adapted_type_id.is_valid()) {
  1072. return GetNestedValueRepr(adapted_type_id);
  1073. }
  1074. // Otherwise, the value representation for a class is a pointer to the
  1075. // object representation.
  1076. // TODO: Support customized value representations for classes.
  1077. // TODO: Pick a better value representation when possible.
  1078. return MakePointerValueRepr(
  1079. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  1080. SemIR::ValueRepr::ObjectAggregate);
  1081. }
  1082. template <typename InstT>
  1083. requires(InstT::Kind.template IsAnyOf<
  1084. SemIR::AssociatedEntityType, SemIR::FacetAccessType,
  1085. SemIR::FacetType, SemIR::FunctionType, SemIR::GenericClassType,
  1086. SemIR::GenericInterfaceType, SemIR::UnboundElementType,
  1087. SemIR::WhereExpr>())
  1088. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  1089. -> SemIR::ValueRepr {
  1090. // These types have no runtime operations, so we use an empty value
  1091. // representation.
  1092. //
  1093. // TODO: There is information we could model here:
  1094. // - For an interface, we could use a witness.
  1095. // - For an associated entity, we could use an index into the witness.
  1096. // - For an unbound element, we could use an index or offset.
  1097. return MakeEmptyValueRepr();
  1098. }
  1099. template <typename InstT>
  1100. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  1101. SemIR::InterfaceWitnessAccess>())
  1102. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  1103. -> SemIR::ValueRepr {
  1104. // For symbolic types, we arbitrarily pick a copy representation.
  1105. return MakeCopyValueRepr(type_id);
  1106. }
  1107. template <typename InstT>
  1108. requires(InstT::Kind.template IsAnyOf<SemIR::FloatType, SemIR::IntType,
  1109. SemIR::PointerType>())
  1110. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  1111. -> SemIR::ValueRepr {
  1112. return MakeCopyValueRepr(type_id);
  1113. }
  1114. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  1115. SemIR::ConstType inst) const -> SemIR::ValueRepr {
  1116. // The value representation of `const T` is the same as that of `T`.
  1117. // Objects are not modifiable through their value representations.
  1118. return GetNestedValueRepr(inst.inner_id);
  1119. }
  1120. template <typename InstT>
  1121. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  1122. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  1123. -> SemIR::ValueRepr {
  1124. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  1125. }
  1126. // Builds and returns the value representation for the given type. All nested
  1127. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  1128. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  1129. -> SemIR::ValueRepr {
  1130. // Use overload resolution to select the implementation, producing compile
  1131. // errors when BuildValueReprForInst isn't defined for a given instruction.
  1132. CARBON_KIND_SWITCH(inst) {
  1133. #define CARBON_SEM_IR_INST_KIND(Name) \
  1134. case CARBON_KIND(SemIR::Name typed_inst): { \
  1135. return BuildValueReprForInst(type_id, typed_inst); \
  1136. }
  1137. #include "toolchain/sem_ir/inst_kind.def"
  1138. }
  1139. }
  1140. enum class Phase : int8_t {
  1141. // The next step is to add nested types to the list of types to complete.
  1142. AddNestedIncompleteTypes,
  1143. // The next step is to build the value representation for the type.
  1144. BuildValueRepr,
  1145. };
  1146. struct WorkItem {
  1147. SemIR::TypeId type_id;
  1148. Phase phase;
  1149. };
  1150. Context& context_;
  1151. llvm::SmallVector<WorkItem> work_list_;
  1152. Context::BuildDiagnosticFn diagnoser_;
  1153. };
  1154. } // namespace
  1155. auto Context::TryToCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  1156. BuildDiagnosticFn diagnoser,
  1157. BuildDiagnosticFn abstract_diagnoser) -> bool {
  1158. if (!TypeCompleter(*this, diagnoser).Complete(type_id)) {
  1159. return false;
  1160. }
  1161. // For a symbolic type, create an instruction to require the corresponding
  1162. // specific type to be complete.
  1163. if (diagnoser && type_id.AsConstantId().is_symbolic()) {
  1164. // TODO: Deduplicate these.
  1165. AddInstInNoBlock(SemIR::LocIdAndInst(
  1166. loc_id,
  1167. SemIR::RequireCompleteType{
  1168. .type_id = GetSingletonType(SemIR::WitnessType::SingletonInstId),
  1169. .complete_type_id = type_id}));
  1170. }
  1171. if (!abstract_diagnoser) {
  1172. return true;
  1173. }
  1174. if (auto class_type = types().TryGetAs<SemIR::ClassType>(type_id)) {
  1175. auto& class_info = classes().Get(class_type->class_id);
  1176. if (class_info.inheritance_kind !=
  1177. SemIR::Class::InheritanceKind::Abstract) {
  1178. return true;
  1179. }
  1180. auto builder = abstract_diagnoser();
  1181. if (!builder) {
  1182. return false;
  1183. }
  1184. NoteAbstractClass(class_type->class_id, builder);
  1185. builder.Emit();
  1186. return false;
  1187. }
  1188. return true;
  1189. }
  1190. auto Context::TryToDefineType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  1191. BuildDiagnosticFn diagnoser) -> bool {
  1192. if (!TryToCompleteType(type_id, loc_id, diagnoser)) {
  1193. return false;
  1194. }
  1195. if (auto facet_type = types().TryGetAs<SemIR::FacetType>(type_id)) {
  1196. const auto& facet_type_info = facet_types().Get(facet_type->facet_type_id);
  1197. for (auto interface : facet_type_info.impls_constraints) {
  1198. auto interface_id = interface.interface_id;
  1199. if (!interfaces().Get(interface_id).is_defined()) {
  1200. auto builder = diagnoser();
  1201. NoteUndefinedInterface(interface_id, builder);
  1202. builder.Emit();
  1203. return false;
  1204. }
  1205. if (interface.specific_id.is_valid()) {
  1206. ResolveSpecificDefinition(*this, interface.specific_id);
  1207. }
  1208. }
  1209. // TODO: Finish facet type resolution.
  1210. }
  1211. return true;
  1212. }
  1213. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  1214. -> SemIR::TypeId {
  1215. CARBON_CHECK(constant_id.is_constant(),
  1216. "Canonicalizing non-constant type: {0}", constant_id);
  1217. auto type_id =
  1218. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  1219. // TODO: For now, we allow values of facet type to be used as types.
  1220. CARBON_CHECK(IsFacetType(type_id) ||
  1221. constant_id == SemIR::ErrorInst::SingletonConstantId,
  1222. "Forming type ID for non-type constant of type {0}",
  1223. types().GetAsInst(type_id));
  1224. return SemIR::TypeId::ForTypeConstant(constant_id);
  1225. }
  1226. auto Context::FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  1227. SemIR::SpecificId specific_id)
  1228. -> SemIR::FacetType {
  1229. SemIR::FacetTypeId facet_type_id = facet_types().Add(
  1230. SemIR::FacetTypeInfo{.impls_constraints = {{interface_id, specific_id}},
  1231. .other_requirements = false});
  1232. return {.type_id = SemIR::TypeType::SingletonTypeId,
  1233. .facet_type_id = facet_type_id};
  1234. }
  1235. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  1236. template <typename InstT, typename... EachArgT>
  1237. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  1238. -> SemIR::TypeId {
  1239. // TODO: Remove inst_id parameter from TryEvalInst.
  1240. InstT inst = {SemIR::TypeType::SingletonTypeId, each_arg...};
  1241. return context.GetTypeIdForTypeConstant(
  1242. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  1243. }
  1244. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  1245. // and completes the type. This should only be used when type completion cannot
  1246. // fail.
  1247. template <typename InstT, typename... EachArgT>
  1248. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  1249. -> SemIR::TypeId {
  1250. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  1251. bool complete = context.TryToCompleteType(type_id);
  1252. CARBON_CHECK(complete, "Type completion should not fail");
  1253. return type_id;
  1254. }
  1255. auto Context::GetStructType(SemIR::StructTypeFieldsId fields_id)
  1256. -> SemIR::TypeId {
  1257. return GetTypeImpl<SemIR::StructType>(*this, fields_id);
  1258. }
  1259. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1260. -> SemIR::TypeId {
  1261. return GetTypeImpl<SemIR::TupleType>(*this,
  1262. type_blocks().AddCanonical(type_ids));
  1263. }
  1264. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  1265. SemIR::TypeId entity_type_id)
  1266. -> SemIR::TypeId {
  1267. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id,
  1268. entity_type_id);
  1269. }
  1270. auto Context::GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId {
  1271. CARBON_CHECK(SemIR::IsSingletonInstId(singleton_id));
  1272. auto type_id = GetTypeIdForTypeInst(singleton_id);
  1273. // To keep client code simpler, complete builtin types before returning them.
  1274. bool complete = TryToCompleteType(type_id);
  1275. CARBON_CHECK(complete, "Failed to complete builtin type");
  1276. return type_id;
  1277. }
  1278. auto Context::GetClassType(SemIR::ClassId class_id,
  1279. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1280. return GetCompleteTypeImpl<SemIR::ClassType>(*this, class_id, specific_id);
  1281. }
  1282. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  1283. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1284. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  1285. }
  1286. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  1287. SemIR::SpecificId enclosing_specific_id)
  1288. -> SemIR::TypeId {
  1289. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  1290. enclosing_specific_id);
  1291. }
  1292. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  1293. SemIR::SpecificId enclosing_specific_id)
  1294. -> SemIR::TypeId {
  1295. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  1296. *this, interface_id, enclosing_specific_id);
  1297. }
  1298. auto Context::GetInterfaceType(SemIR::InterfaceId interface_id,
  1299. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1300. return GetTypeImpl<SemIR::FacetType>(
  1301. *this, FacetTypeFromInterface(interface_id, specific_id).facet_type_id);
  1302. }
  1303. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1304. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1305. }
  1306. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1307. SemIR::TypeId element_type_id)
  1308. -> SemIR::TypeId {
  1309. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1310. element_type_id);
  1311. }
  1312. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1313. output << "Check::Context\n";
  1314. // In a stack dump, this is probably indented by a tab. We treat that as 8
  1315. // spaces then add a couple to indent past the Context label.
  1316. constexpr int Indent = 10;
  1317. node_stack_.PrintForStackDump(Indent, output);
  1318. inst_block_stack_.PrintForStackDump(Indent, output);
  1319. pattern_block_stack_.PrintForStackDump(Indent, output);
  1320. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  1321. args_type_info_stack_.PrintForStackDump(Indent, output);
  1322. }
  1323. auto Context::DumpFormattedFile() const -> void {
  1324. SemIR::Formatter formatter(sem_ir_);
  1325. formatter.Print(llvm::errs());
  1326. }
  1327. } // namespace Carbon::Check