context.cpp 50 KB

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