context.cpp 54 KB

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