context.cpp 54 KB

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