context.cpp 54 KB

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