facet_type.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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/facet_type.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/control_flow.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/import_ref.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/interface.h"
  13. #include "toolchain/check/subst.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/sem_ir/generic.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  21. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  22. auto info = SemIR::FacetTypeInfo{};
  23. info.extend_constraints.push_back({interface_id, specific_id});
  24. info.Canonicalize();
  25. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  26. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  27. }
  28. auto FacetTypeFromNamedConstraint(Context& context,
  29. SemIR::NamedConstraintId named_constraint_id,
  30. SemIR::SpecificId specific_id)
  31. -> SemIR::FacetType {
  32. auto info = SemIR::FacetTypeInfo{};
  33. info.extend_named_constraints.push_back({named_constraint_id, specific_id});
  34. info.Canonicalize();
  35. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  36. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  37. }
  38. auto GetImplWitnessAccessWithoutSubstitution(Context& context,
  39. SemIR::InstId inst_id)
  40. -> SemIR::InstId {
  41. if (auto inst = context.insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  42. inst_id)) {
  43. return inst->impl_witness_access_id;
  44. }
  45. return inst_id;
  46. }
  47. // A mapping of each associated constant (represented as `ImplWitnessAccess`) to
  48. // its value (represented as an `InstId`). Used to track rewrite constraints,
  49. // with the LHS mapping to the resolved value of the RHS.
  50. class AccessRewriteValues {
  51. public:
  52. enum State {
  53. NotRewritten,
  54. BeingRewritten,
  55. FullyRewritten,
  56. };
  57. struct Value {
  58. State state;
  59. SemIR::InstId inst_id;
  60. };
  61. auto InsertNotRewritten(
  62. Context& context, SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id,
  63. SemIR::InstId inst_id) -> void {
  64. map_.Insert(context.constant_values().Get(access_id),
  65. {NotRewritten, inst_id});
  66. }
  67. // Finds and returns a pointer into the cache for a given ImplWitnessAccess.
  68. // The pointer will be invalidated by mutating the cache. Returns `nullptr`
  69. // if `access` is not found.
  70. auto FindRef(Context& context,
  71. SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id)
  72. -> Value* {
  73. auto result = map_.Lookup(context.constant_values().Get(access_id));
  74. if (!result) {
  75. return nullptr;
  76. }
  77. return &result.value();
  78. }
  79. auto SetBeingRewritten(Value& value) -> void {
  80. if (value.state == NotRewritten) {
  81. value.state = BeingRewritten;
  82. }
  83. }
  84. auto SetFullyRewritten(Context& context, Value& value, SemIR::InstId inst_id)
  85. -> void {
  86. if (value.state == FullyRewritten) {
  87. CARBON_CHECK(context.constant_values().Get(value.inst_id) ==
  88. context.constant_values().Get(inst_id));
  89. }
  90. value = {FullyRewritten, inst_id};
  91. }
  92. private:
  93. // Try avoid heap allocations in the common case where there are a small
  94. // number of rewrite rules referring to each other by keeping up to 16 on
  95. // the stack.
  96. //
  97. // TODO: Revisit if 16 is an appropriate number when we can measure how deep
  98. // rewrite constraint chains go in practice.
  99. Map<SemIR::ConstantId, Value, 16> map_;
  100. };
  101. // To be used for substituting into the RHS of a rewrite constraint.
  102. //
  103. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  104. // associated constant) with the RHS of another rewrite constraint that writes
  105. // to the same associated constant. For example:
  106. // ```
  107. // Z where .X = () and .Y = .X
  108. // ```
  109. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  110. // finding the first rewrite constraint, where the LHS is for the same
  111. // associated constant and using its RHS. So the substitution would produce:
  112. // ```
  113. // Z where .X = () and .Y = ()
  114. // ```
  115. //
  116. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  117. // from the same rewrite constraint, and is thus assigning to the associated
  118. // constant a value that refers to the same associated constant, such as with `Z
  119. // where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  120. // replaced with `ErrorInst` so that further evaluation of the
  121. // `ImplWitnessAccess` will not loop infinitely.
  122. //
  123. // The `rewrite_values` given to the constructor must be set up initially with
  124. // each rewrite rule of an associated constant inserted with its unresolved
  125. // value via `InsertNotRewritten`. Then for each rewrite rule of an associated
  126. // constant, the LHS access should be set as being rewritten with its state
  127. // changed to `BeingRewritten` in order to detect cycles before performing
  128. // SubstInst. The result of SubstInst should be preserved afterward by changing
  129. // the state and value for the LHS to `FullyRewritten` and the subst output
  130. // instruction, respectively, to avoid duplicating work.
  131. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  132. public:
  133. explicit SubstImplWitnessAccessCallbacks(Context* context,
  134. SemIR::LocId loc_id,
  135. AccessRewriteValues* rewrite_values)
  136. : SubstInstCallbacks(context),
  137. loc_id_(loc_id),
  138. rewrite_values_(rewrite_values) {}
  139. auto Subst(SemIR::InstId& rhs_inst_id) -> SubstResult override {
  140. auto rhs_access =
  141. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(rhs_inst_id);
  142. if (!rhs_access) {
  143. // We only want to substitute ImplWitnessAccesses written directly on the
  144. // RHS of the rewrite constraint, not when they are nested inside facet
  145. // types that are part of the RHS, like `.X = C as (I where .Y = {})`.
  146. if (context().insts().Is<SemIR::FacetType>(rhs_inst_id)) {
  147. return SubstResult::FullySubstituted;
  148. }
  149. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  150. // There's no ImplWitnessAccess that we care about inside this
  151. // instruction.
  152. return SubstResult::FullySubstituted;
  153. }
  154. if (auto subst =
  155. context().insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  156. rhs_inst_id)) {
  157. // The reference to an associated constant was eagerly replaced with the
  158. // value of an earlier rewrite constraint, but may need further
  159. // substitution if it contains an `ImplWitnessAccess`.
  160. rhs_inst_id = subst->value_id;
  161. substs_in_progress_.push_back(rhs_inst_id);
  162. return SubstResult::SubstAgain;
  163. }
  164. // SubstOperands will result in a Rebuild or ReuseUnchanged callback, so
  165. // push the non-ImplWitnessAccess to get proper bracketing, allowing us
  166. // to pop it in the paired callback.
  167. substs_in_progress_.push_back(rhs_inst_id);
  168. return SubstResult::SubstOperands;
  169. }
  170. // If the access is going through a nested `ImplWitnessAccess`, that
  171. // access needs to be resolved to a facet value first. If it can't be
  172. // resolved then the outer one can not be either.
  173. if (auto lookup = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  174. rhs_access->inst.witness_id)) {
  175. if (context().insts().Is<SemIR::ImplWitnessAccess>(
  176. lookup->query_self_inst_id)) {
  177. substs_in_progress_.push_back(rhs_inst_id);
  178. return SubstResult::SubstOperandsAndRetry;
  179. }
  180. }
  181. auto* rewrite_value =
  182. rewrite_values_->FindRef(context(), rhs_access->inst_id);
  183. if (!rewrite_value) {
  184. // The RHS refers to an associated constant for which there is no rewrite
  185. // rule.
  186. return SubstResult::FullySubstituted;
  187. }
  188. // Diagnose a cycle if the RHS refers to something that depends on the value
  189. // of the RHS.
  190. if (rewrite_value->state == AccessRewriteValues::BeingRewritten) {
  191. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  192. "found cycle in facet type constraint for {0}",
  193. InstIdAsConstant);
  194. // TODO: It would be nice to note the places where the values are
  195. // assigned but rewrite constraint instructions are from canonical
  196. // constant values, and have no locations. We'd need to store a location
  197. // along with them in the rewrite constraints, and track propagation of
  198. // locations here, which may imply heap allocations.
  199. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle, rhs_inst_id);
  200. rhs_inst_id = SemIR::ErrorInst::InstId;
  201. return SubstResult::FullySubstituted;
  202. } else if (rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  203. rhs_inst_id = rewrite_value->inst_id;
  204. return SubstResult::FullySubstituted;
  205. }
  206. // We have a non-rewritten RHS. We need to recurse on rewriting it. Reuse
  207. // the previous lookup by mutating it in place.
  208. rewrite_values_->SetBeingRewritten(*rewrite_value);
  209. // The ImplWitnessAccess was replaced with some other instruction, which may
  210. // contain or be another ImplWitnessAccess. Keep track of the associated
  211. // constant we are now computing the value of.
  212. substs_in_progress_.push_back(rhs_inst_id);
  213. rhs_inst_id = rewrite_value->inst_id;
  214. return SubstResult::SubstAgain;
  215. }
  216. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst)
  217. -> SemIR::InstId override {
  218. auto inst_id = RebuildNewInst(loc_id_, new_inst);
  219. auto subst_inst_id = substs_in_progress_.pop_back_val();
  220. if (auto access =
  221. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  222. subst_inst_id)) {
  223. if (auto* rewrite_value =
  224. rewrite_values_->FindRef(context(), access->inst_id)) {
  225. rewrite_values_->SetFullyRewritten(context(), *rewrite_value, inst_id);
  226. }
  227. }
  228. return inst_id;
  229. }
  230. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  231. auto subst_inst_id = substs_in_progress_.pop_back_val();
  232. if (auto access =
  233. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  234. subst_inst_id)) {
  235. if (auto* rewrite_value =
  236. rewrite_values_->FindRef(context(), access->inst_id)) {
  237. rewrite_values_->SetFullyRewritten(context(), *rewrite_value,
  238. orig_inst_id);
  239. }
  240. }
  241. return orig_inst_id;
  242. }
  243. private:
  244. struct SubstInProgress {
  245. // The associated constant whose value is being determined, represented as
  246. // an ImplWitnessAccess. Or another instruction that we are recursing
  247. // through.
  248. SemIR::InstId inst_id;
  249. };
  250. // The location of the rewrite constraints as a whole.
  251. SemIR::LocId loc_id_;
  252. // Tracks the resolved value of each rewrite constraint, keyed by the
  253. // `ImplWitnessAccess` of the associated constant on the LHS of the
  254. // constraint. The value of each associated constant may be changed during
  255. // substitution, replaced with a fully resolved value for the RHS. This allows
  256. // us to cache work; when a value for an associated constant is found once it
  257. // can be reused cheaply, avoiding exponential runtime when rewrite rules
  258. // refer to each other in ways that create exponential references.
  259. AccessRewriteValues* rewrite_values_;
  260. // A stack of instructions being replaced in Subst(). When it's an associated
  261. // constant, then it represents the constant value is being determined,
  262. // represented as an ImplWitnessAccess.
  263. //
  264. // Avoid heap allocations in common cases, if there are chains of instructions
  265. // in associated constants with a depth at most 16.
  266. llvm::SmallVector<SemIR::InstId, 16> substs_in_progress_;
  267. };
  268. auto ResolveFacetTypeRewriteConstraints(
  269. Context& context, SemIR::LocId loc_id,
  270. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  271. -> bool {
  272. if (rewrites.empty()) {
  273. return true;
  274. }
  275. AccessRewriteValues rewrite_values;
  276. for (auto& constraint : rewrites) {
  277. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  278. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  279. if (!lhs_access) {
  280. continue;
  281. }
  282. rewrite_values.InsertNotRewritten(context, lhs_access->inst_id,
  283. constraint.rhs_id);
  284. }
  285. for (auto& constraint : rewrites) {
  286. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  287. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  288. if (!lhs_access) {
  289. continue;
  290. }
  291. auto* lhs_rewrite_value =
  292. rewrite_values.FindRef(context, lhs_access->inst_id);
  293. // Every LHS was added with InsertNotRewritten above.
  294. CARBON_CHECK(lhs_rewrite_value);
  295. rewrite_values.SetBeingRewritten(*lhs_rewrite_value);
  296. auto replace_witness_callbacks =
  297. SubstImplWitnessAccessCallbacks(&context, loc_id, &rewrite_values);
  298. auto rhs_subst_inst_id =
  299. SubstInst(context, constraint.rhs_id, replace_witness_callbacks);
  300. if (rhs_subst_inst_id == SemIR::ErrorInst::InstId) {
  301. return false;
  302. }
  303. if (lhs_rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  304. auto rhs_existing_const_id =
  305. context.constant_values().Get(lhs_rewrite_value->inst_id);
  306. auto rhs_subst_const_id =
  307. context.constant_values().Get(rhs_subst_inst_id);
  308. if (rhs_subst_const_id != rhs_existing_const_id) {
  309. if (rhs_existing_const_id != SemIR::ErrorInst::ConstantId) {
  310. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  311. "associated constant {0} given two different "
  312. "values {1} and {2}",
  313. InstIdAsConstant, InstIdAsConstant,
  314. InstIdAsConstant);
  315. // Use inst id ordering as a simple proxy for source ordering, to
  316. // try to name the values in the same order they appear in the facet
  317. // type.
  318. auto source_order1 =
  319. lhs_rewrite_value->inst_id.index < rhs_subst_inst_id.index
  320. ? lhs_rewrite_value->inst_id
  321. : rhs_subst_inst_id;
  322. auto source_order2 =
  323. lhs_rewrite_value->inst_id.index >= rhs_subst_inst_id.index
  324. ? lhs_rewrite_value->inst_id
  325. : rhs_subst_inst_id;
  326. // TODO: It would be nice to note the places where the values are
  327. // assigned but rewrite constraint instructions are from canonical
  328. // constant values, and have no locations. We'd need to store a
  329. // location along with them in the rewrite constraints.
  330. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  331. GetImplWitnessAccessWithoutSubstitution(
  332. context, constraint.lhs_id),
  333. source_order1, source_order2);
  334. }
  335. return false;
  336. }
  337. }
  338. rewrite_values.SetFullyRewritten(context, *lhs_rewrite_value,
  339. rhs_subst_inst_id);
  340. }
  341. // Rebuild the `rewrites` vector with resolved values for the RHS. Drop any
  342. // duplicate rewrites in the `rewrites` vector by walking through the
  343. // `rewrite_values` map and dropping the computed RHS value for each LHS the
  344. // first time we see it, and erasing the constraint from the vector if we see
  345. // the same LHS again.
  346. size_t keep_size = rewrites.size();
  347. for (size_t i = 0; i < keep_size;) {
  348. auto& constraint = rewrites[i];
  349. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  350. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  351. if (!lhs_access) {
  352. ++i;
  353. continue;
  354. }
  355. auto& rewrite_value = *rewrite_values.FindRef(context, lhs_access->inst_id);
  356. auto rhs_id = std::exchange(rewrite_value.inst_id, SemIR::InstId::None);
  357. if (rhs_id == SemIR::InstId::None) {
  358. std::swap(rewrites[i], rewrites[keep_size - 1]);
  359. --keep_size;
  360. } else {
  361. rewrites[i].rhs_id = rhs_id;
  362. ++i;
  363. }
  364. }
  365. rewrites.erase(rewrites.begin() + keep_size, rewrites.end());
  366. return true;
  367. }
  368. auto MakePeriodSelfFacetValue(Context& context, SemIR::TypeId self_type_id)
  369. -> SemIR::InstId {
  370. CARBON_CHECK(self_type_id == SemIR::ErrorInst::TypeId ||
  371. context.types().Is<SemIR::FacetType>(self_type_id));
  372. auto entity_name_id = context.entity_names().AddCanonical({
  373. .name_id = SemIR::NameId::PeriodSelf,
  374. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  375. });
  376. auto inst_id = AddInst(
  377. context, SemIR::LocIdAndInst::NoLoc<SemIR::SymbolicBinding>({
  378. .type_id = self_type_id,
  379. .entity_name_id = entity_name_id,
  380. // `None` because there is no equivalent non-symbolic value.
  381. .value_id = SemIR::InstId::None,
  382. }));
  383. auto existing = context.scope_stack().LookupOrAddName(
  384. SemIR::NameId::PeriodSelf, inst_id, ScopeIndex::None,
  385. IsCurrentPositionReachable(context));
  386. // Shouldn't have any names in newly created scope.
  387. CARBON_CHECK(!existing.has_value());
  388. return inst_id;
  389. }
  390. auto GetEmptyFacetType(Context& context) -> SemIR::TypeId {
  391. SemIR::FacetTypeId facet_type_id =
  392. context.facet_types().Add(SemIR::FacetTypeInfo{});
  393. auto const_id = EvalOrAddInst<SemIR::FacetType>(
  394. context, SemIR::LocId::None,
  395. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  396. return context.types().GetTypeIdForTypeConstantId(const_id);
  397. }
  398. auto GetConstantFacetValueForType(Context& context,
  399. SemIR::TypeInstId type_inst_id)
  400. -> SemIR::ConstantId {
  401. // We use an empty facet type because values of type `type` do not provide any
  402. // witnesses of their own.
  403. auto type_facet_type = GetEmptyFacetType(context);
  404. return EvalOrAddInst<SemIR::FacetValue>(
  405. context, SemIR::LocId::None,
  406. {.type_id = type_facet_type,
  407. .type_inst_id = type_inst_id,
  408. .witnesses_block_id = SemIR::InstBlockId::Empty});
  409. }
  410. auto GetConstantFacetValueForTypeAndInterface(
  411. Context& context, SemIR::TypeInstId type_inst_id,
  412. SemIR::SpecificInterface specific_interface, SemIR::InstId witness_id)
  413. -> SemIR::ConstantId {
  414. // Get the type of the inner `Self`, which is the facet type of the interface.
  415. auto interface_facet_type = EvalOrAddInst(
  416. context, SemIR::LocId::None,
  417. FacetTypeFromInterface(context, specific_interface.interface_id,
  418. specific_interface.specific_id));
  419. auto self_facet_type_in_generic_without_self =
  420. context.types().GetTypeIdForTypeConstantId(interface_facet_type);
  421. auto witnesses_block_id = context.inst_blocks().AddCanonical({witness_id});
  422. auto self_value_const_id = EvalOrAddInst<SemIR::FacetValue>(
  423. context, SemIR::LocId::None,
  424. {.type_id = self_facet_type_in_generic_without_self,
  425. .type_inst_id = type_inst_id,
  426. .witnesses_block_id = witnesses_block_id});
  427. return self_value_const_id;
  428. }
  429. SubstPeriodSelfCallbacks::SubstPeriodSelfCallbacks(
  430. Context* context, SemIR::LocId loc_id,
  431. SemIR::ConstantId period_self_replacement_id)
  432. : SubstInstCallbacks(context),
  433. loc_id_(loc_id),
  434. period_self_replacement_id_(period_self_replacement_id) {}
  435. auto SubstPeriodSelfCallbacks::Subst(SemIR::InstId& inst_id) -> SubstResult {
  436. // FacetTypes are concrete even if they have `.Self` inside them, but we
  437. // don't recurse into FacetTypes, so we can use this as a base case. This
  438. // avoids infinite recursion on TypeType and ErrorInst.
  439. if (context().constant_values().Get(inst_id).is_concrete()) {
  440. return FullySubstituted;
  441. }
  442. // Don't recurse into nested facet types, even if they are symbolic. Leave
  443. // their `.Self` as is.
  444. if (context().insts().Is<SemIR::FacetType>(inst_id)) {
  445. return FullySubstituted;
  446. }
  447. // For `.X` (which is `.Self.X`) replace the `.Self` in the query self
  448. // position, and report it as `implicit`. Any `.Self` references in the
  449. // specific interface would be replaced later and not treated as `implicit`.
  450. //
  451. // TODO: This all goes away when eval doesn't need to know about implicit
  452. // .Self for diagnostics, once we diagnose invalid `.Self` in name lookup.
  453. if (auto access =
  454. context().insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id)) {
  455. if (auto witness = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  456. access->witness_id)) {
  457. if (auto bind = context().insts().TryGetAs<SemIR::SymbolicBinding>(
  458. witness->query_self_inst_id)) {
  459. const auto& entity_name =
  460. context().entity_names().Get(bind->entity_name_id);
  461. if (entity_name.name_id == SemIR::NameId::PeriodSelf) {
  462. auto replacement_id =
  463. GetReplacement(witness->query_self_inst_id, true);
  464. auto new_witness =
  465. Rebuild(access->witness_id,
  466. SemIR::LookupImplWitness{
  467. .type_id = witness->type_id,
  468. .query_self_inst_id = replacement_id,
  469. // Don't replace `.Self` in the interface specific
  470. // here. That is an explicit `.Self` use. We'll
  471. // revisit the instruction for that.
  472. .query_specific_interface_id =
  473. witness->query_specific_interface_id,
  474. });
  475. auto new_access = Rebuild(inst_id, SemIR::ImplWitnessAccess{
  476. .type_id = access->type_id,
  477. .witness_id = new_witness,
  478. .index = access->index,
  479. });
  480. inst_id = new_access;
  481. return SubstAgain;
  482. }
  483. }
  484. }
  485. }
  486. if (auto bind = context().insts().TryGetAs<SemIR::SymbolicBinding>(inst_id)) {
  487. const auto& entity_name =
  488. context().entity_names().Get(bind->entity_name_id);
  489. if (entity_name.name_id == SemIR::NameId::PeriodSelf) {
  490. inst_id = GetReplacement(inst_id, false);
  491. return FullySubstituted;
  492. }
  493. }
  494. return SubstOperands;
  495. }
  496. auto SubstPeriodSelfCallbacks::Rebuild(SemIR::InstId orig_inst_id,
  497. SemIR::Inst new_inst) -> SemIR::InstId {
  498. return RebuildNewInst(SemIR::LocId(orig_inst_id), new_inst);
  499. }
  500. auto SubstPeriodSelfCallbacks::GetReplacement(SemIR::InstId period_self,
  501. bool implicit) -> SemIR::InstId {
  502. if (!ShouldReplace(implicit)) {
  503. return period_self;
  504. }
  505. auto period_self_type_id = context().insts().Get(period_self).type_id();
  506. CARBON_CHECK(context().types().Is<SemIR::FacetType>(period_self_type_id));
  507. auto replacement_self_inst_id =
  508. context().constant_values().GetInstId(period_self_replacement_id_);
  509. auto replacement_type_id =
  510. context().insts().Get(replacement_self_inst_id).type_id();
  511. CARBON_CHECK(context().types().IsFacetType(replacement_type_id));
  512. // If the replacement has the same type as `.Self`, use it directly.
  513. if (replacement_type_id == period_self_type_id) {
  514. return replacement_self_inst_id;
  515. }
  516. // If we have already converted the replacement to the type of `.Self`, use
  517. // our previous conversion.
  518. if (period_self_type_id == cached_replacement_type_id_) {
  519. return cached_replacement_id_;
  520. }
  521. // Convert the replacement facet to the type of `.Self`.
  522. cached_replacement_id_ = ConvertReplacement(
  523. replacement_self_inst_id, replacement_type_id, period_self_type_id);
  524. cached_replacement_type_id_ = period_self_type_id;
  525. return cached_replacement_id_;
  526. }
  527. auto SubstPeriodSelfCallbacks::ConvertReplacement(
  528. SemIR::InstId replacement_self_inst_id, SemIR::TypeId replacement_type_id,
  529. SemIR::TypeId period_self_type_id) -> SemIR::InstId {
  530. // TODO: Replace all empty facet types with TypeType.
  531. if (period_self_type_id == GetEmptyFacetType(context())) {
  532. // Convert to an empty facet type (representing TypeType); we don't need
  533. // any witnesses.
  534. return ConvertToValueOfType(context(), loc_id_, replacement_self_inst_id,
  535. period_self_type_id);
  536. }
  537. // We have a facet or a type, but we need more interfaces in the facet type.
  538. // We will have to synthesize a symbolic witness for each interface.
  539. //
  540. // Why is this okay? The type of `.Self` comes from interfaces that are
  541. // before it (to the left of it) in the facet type. The replacement for
  542. // `.Self` will have to impl those interfaces in order to match the facet
  543. // type, so we know that it is valid to construct these witnesses.
  544. // Make the replacement into a type, which we will need for the FacetValue.
  545. if (context().types().Is<SemIR::FacetType>(replacement_type_id)) {
  546. replacement_self_inst_id = context().constant_values().GetInstId(
  547. EvalOrAddInst<SemIR::FacetAccessType>(
  548. context(), loc_id_,
  549. {.type_id = SemIR::TypeType::TypeId,
  550. .facet_value_inst_id = replacement_self_inst_id}));
  551. }
  552. auto period_self_facet_type =
  553. context().types().GetAs<SemIR::FacetType>(period_self_type_id);
  554. auto identified_period_self_type_id = RequireIdentifiedFacetType(
  555. context(), loc_id_,
  556. context().constant_values().Get(replacement_self_inst_id),
  557. period_self_facet_type, [&](auto& /*builder*/) {
  558. // The facet type containing this `.Self` should have already been
  559. // identified, which would ensure that the type of `.Self` can be
  560. // identified since it can only depend on things to the left of it
  561. // inside the same facet type.
  562. CARBON_FATAL("could not identify type of `.Self`");
  563. });
  564. const auto& identified_period_self_type =
  565. context().identified_facet_types().Get(identified_period_self_type_id);
  566. auto required_impls = identified_period_self_type.required_impls();
  567. llvm::SmallVector<SemIR::InstId> witnesses;
  568. witnesses.reserve(required_impls.size());
  569. for (const auto& req : required_impls) {
  570. witnesses.push_back(context().constant_values().GetInstId(
  571. EvalOrAddInst<SemIR::LookupImplWitness>(
  572. context(), loc_id_,
  573. {.type_id =
  574. GetSingletonType(context(), SemIR::WitnessType::TypeInstId),
  575. .query_self_inst_id =
  576. context().constant_values().GetInstId(req.self_facet_value),
  577. .query_specific_interface_id = context().specific_interfaces().Add(
  578. req.specific_interface)})));
  579. }
  580. return context().constant_values().GetInstId(EvalOrAddInst<SemIR::FacetValue>(
  581. context(), loc_id_,
  582. {
  583. .type_id = period_self_type_id,
  584. .type_inst_id =
  585. context().types().GetAsTypeInstId(replacement_self_inst_id),
  586. .witnesses_block_id = context().inst_blocks().Add(witnesses),
  587. }));
  588. }
  589. auto SubstPeriodSelf(Context& context, SubstPeriodSelfCallbacks& callbacks,
  590. SemIR::ConstantId const_id) -> SemIR::ConstantId {
  591. // Don't replace `.Self` with itself; that is cyclical.
  592. //
  593. // If the types differ, we would try to convert the replacement to a `.Self`
  594. // of the desired type in `const_id`, which is what we already have, so
  595. // there's nothing we need to do. But trying to do that conversion recurses
  596. // when the type of the `.Self` contains a `.Self`.
  597. if (auto bind_type =
  598. context.constant_values().TryGetInstAs<SemIR::SymbolicBinding>(
  599. GetCanonicalFacetOrTypeValue(
  600. context, callbacks.period_self_replacement_id()))) {
  601. if (context.entity_names().Get(bind_type->entity_name_id).name_id ==
  602. SemIR::NameId::PeriodSelf) {
  603. return const_id;
  604. }
  605. }
  606. auto subst_id = SubstInst(
  607. context, context.constant_values().GetInstId(const_id), callbacks);
  608. return context.constant_values().Get(subst_id);
  609. }
  610. static auto SubstPeriodSelfInSpecific(Context& context,
  611. SubstPeriodSelfCallbacks& callbacks,
  612. SemIR::SpecificId specific_id)
  613. -> SemIR::SpecificId {
  614. if (!specific_id.has_value()) {
  615. return specific_id;
  616. }
  617. const auto& specific = context.specifics().Get(specific_id);
  618. // Substitute into the specific without having to construct a FacetType
  619. // instruction just to hold the specific interface inside a constant id.
  620. llvm::SmallVector<SemIR::InstId> args(
  621. context.inst_blocks().Get(specific.args_id));
  622. for (auto& arg_id : args) {
  623. auto const_id = context.constant_values().Get(arg_id);
  624. const_id = SubstPeriodSelf(context, callbacks, const_id);
  625. arg_id = context.constant_values().GetInstId(const_id);
  626. }
  627. return MakeSpecific(context, callbacks.loc_id(), specific.generic_id, args);
  628. }
  629. auto SubstPeriodSelf(Context& context, SubstPeriodSelfCallbacks& callbacks,
  630. SemIR::SpecificInterface interface)
  631. -> SemIR::SpecificInterface {
  632. interface.specific_id =
  633. SubstPeriodSelfInSpecific(context, callbacks, interface.specific_id);
  634. return interface;
  635. }
  636. auto SubstPeriodSelf(Context& context, SubstPeriodSelfCallbacks& callbacks,
  637. SemIR::SpecificNamedConstraint constraint)
  638. -> SemIR::SpecificNamedConstraint {
  639. constraint.specific_id =
  640. SubstPeriodSelfInSpecific(context, callbacks, constraint.specific_id);
  641. return constraint;
  642. }
  643. } // namespace Carbon::Check