context.cpp 54 KB

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