facet_type.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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/import_ref.h"
  8. #include "toolchain/check/inst.h"
  9. #include "toolchain/check/interface.h"
  10. #include "toolchain/check/subst.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Check {
  15. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  16. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  17. auto info = SemIR::FacetTypeInfo{};
  18. info.extend_constraints.push_back({interface_id, specific_id});
  19. info.Canonicalize();
  20. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  21. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  22. }
  23. auto FacetTypeFromNamedConstraint(Context& context,
  24. SemIR::NamedConstraintId named_constraint_id,
  25. SemIR::SpecificId specific_id)
  26. -> SemIR::FacetType {
  27. auto info = SemIR::FacetTypeInfo{};
  28. info.extend_named_constraints.push_back({named_constraint_id, specific_id});
  29. info.Canonicalize();
  30. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  31. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  32. }
  33. auto GetImplWitnessAccessWithoutSubstitution(Context& context,
  34. SemIR::InstId inst_id)
  35. -> SemIR::InstId {
  36. if (auto inst = context.insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  37. inst_id)) {
  38. return inst->impl_witness_access_id;
  39. }
  40. return inst_id;
  41. }
  42. // A mapping of each associated constant (represented as `ImplWitnessAccess`) to
  43. // its value (represented as an `InstId`). Used to track rewrite constraints,
  44. // with the LHS mapping to the resolved value of the RHS.
  45. class AccessRewriteValues {
  46. public:
  47. enum State {
  48. NotRewritten,
  49. BeingRewritten,
  50. FullyRewritten,
  51. };
  52. struct Value {
  53. State state;
  54. SemIR::InstId inst_id;
  55. };
  56. auto InsertNotRewritten(
  57. Context& context, SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id,
  58. SemIR::InstId inst_id) -> void {
  59. map_.Insert(context.constant_values().Get(access_id),
  60. {NotRewritten, inst_id});
  61. }
  62. // Finds and returns a pointer into the cache for a given ImplWitnessAccess.
  63. // The pointer will be invalidated by mutating the cache. Returns `nullptr`
  64. // if `access` is not found.
  65. auto FindRef(Context& context,
  66. SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id)
  67. -> Value* {
  68. auto result = map_.Lookup(context.constant_values().Get(access_id));
  69. if (!result) {
  70. return nullptr;
  71. }
  72. return &result.value();
  73. }
  74. auto SetBeingRewritten(Value& value) -> void {
  75. if (value.state == NotRewritten) {
  76. value.state = BeingRewritten;
  77. }
  78. }
  79. auto SetFullyRewritten(Context& context, Value& value, SemIR::InstId inst_id)
  80. -> void {
  81. if (value.state == FullyRewritten) {
  82. CARBON_CHECK(context.constant_values().Get(value.inst_id) ==
  83. context.constant_values().Get(inst_id));
  84. }
  85. value = {FullyRewritten, inst_id};
  86. }
  87. private:
  88. // Try avoid heap allocations in the common case where there are a small
  89. // number of rewrite rules referring to each other by keeping up to 16 on
  90. // the stack.
  91. //
  92. // TODO: Revisit if 16 is an appropriate number when we can measure how deep
  93. // rewrite constraint chains go in practice.
  94. Map<SemIR::ConstantId, Value, 16> map_;
  95. };
  96. // To be used for substituting into the RHS of a rewrite constraint.
  97. //
  98. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  99. // associated constant) with the RHS of another rewrite constraint that writes
  100. // to the same associated constant. For example:
  101. // ```
  102. // Z where .X = () and .Y = .X
  103. // ```
  104. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  105. // finding the first rewrite constraint, where the LHS is for the same
  106. // associated constant and using its RHS. So the substitution would produce:
  107. // ```
  108. // Z where .X = () and .Y = ()
  109. // ```
  110. //
  111. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  112. // from the same rewrite constraint, and is thus assigning to the associated
  113. // constant a value that refers to the same associated constant, such as with `Z
  114. // where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  115. // replaced with `ErrorInst` so that further evaluation of the
  116. // `ImplWitnessAccess` will not loop infinitely.
  117. //
  118. // The `rewrite_values` given to the constructor must be set up initially with
  119. // each rewrite rule of an associated constant inserted with its unresolved
  120. // value via `InsertNotRewritten`. Then for each rewrite rule of an associated
  121. // constant, the LHS access should be set as being rewritten with its state
  122. // changed to `BeingRewritten` in order to detect cycles before performing
  123. // SubstInst. The result of SubstInst should be preserved afterward by changing
  124. // the state and value for the LHS to `FullyRewritten` and the subst output
  125. // instruction, respectively, to avoid duplicating work.
  126. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  127. public:
  128. explicit SubstImplWitnessAccessCallbacks(Context* context,
  129. SemIR::LocId loc_id,
  130. AccessRewriteValues* rewrite_values)
  131. : SubstInstCallbacks(context),
  132. loc_id_(loc_id),
  133. rewrite_values_(rewrite_values) {}
  134. auto Subst(SemIR::InstId& rhs_inst_id) -> SubstResult override {
  135. auto rhs_access =
  136. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(rhs_inst_id);
  137. if (!rhs_access) {
  138. // We only want to substitute ImplWitnessAccesses written directly on the
  139. // RHS of the rewrite constraint, not when they are nested inside facet
  140. // types that are part of the RHS, like `.X = C as (I where .Y = {})`.
  141. if (context().insts().Is<SemIR::FacetType>(rhs_inst_id)) {
  142. return SubstResult::FullySubstituted;
  143. }
  144. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  145. // There's no ImplWitnessAccess that we care about inside this
  146. // instruction.
  147. return SubstResult::FullySubstituted;
  148. }
  149. if (auto subst =
  150. context().insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  151. rhs_inst_id)) {
  152. // The reference to an associated constant was eagerly replaced with the
  153. // value of an earlier rewrite constraint, but may need further
  154. // substitution if it contains an `ImplWitnessAccess`.
  155. rhs_inst_id = subst->value_id;
  156. substs_in_progress_.push_back(rhs_inst_id);
  157. return SubstResult::SubstAgain;
  158. }
  159. // SubstOperands will result in a Rebuild or ReuseUnchanged callback, so
  160. // push the non-ImplWitnessAccess to get proper bracketing, allowing us
  161. // to pop it in the paired callback.
  162. substs_in_progress_.push_back(rhs_inst_id);
  163. return SubstResult::SubstOperands;
  164. }
  165. // If the access is going through a nested `ImplWitnessAccess`, that
  166. // access needs to be resolved to a facet value first. If it can't be
  167. // resolved then the outer one can not be either.
  168. if (auto lookup = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  169. rhs_access->inst.witness_id)) {
  170. if (context().insts().Is<SemIR::ImplWitnessAccess>(
  171. lookup->query_self_inst_id)) {
  172. substs_in_progress_.push_back(rhs_inst_id);
  173. return SubstResult::SubstOperandsAndRetry;
  174. }
  175. }
  176. auto* rewrite_value =
  177. rewrite_values_->FindRef(context(), rhs_access->inst_id);
  178. if (!rewrite_value) {
  179. // The RHS refers to an associated constant for which there is no rewrite
  180. // rule.
  181. return SubstResult::FullySubstituted;
  182. }
  183. // Diagnose a cycle if the RHS refers to something that depends on the value
  184. // of the RHS.
  185. if (rewrite_value->state == AccessRewriteValues::BeingRewritten) {
  186. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  187. "found cycle in facet type constraint for {0}",
  188. InstIdAsConstant);
  189. // TODO: It would be nice to note the places where the values are
  190. // assigned but rewrite constraint instructions are from canonical
  191. // constant values, and have no locations. We'd need to store a location
  192. // along with them in the rewrite constraints, and track propagation of
  193. // locations here, which may imply heap allocations.
  194. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle, rhs_inst_id);
  195. rhs_inst_id = SemIR::ErrorInst::InstId;
  196. return SubstResult::FullySubstituted;
  197. } else if (rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  198. rhs_inst_id = rewrite_value->inst_id;
  199. return SubstResult::FullySubstituted;
  200. }
  201. // We have a non-rewritten RHS. We need to recurse on rewriting it. Reuse
  202. // the previous lookup by mutating it in place.
  203. rewrite_values_->SetBeingRewritten(*rewrite_value);
  204. // The ImplWitnessAccess was replaced with some other instruction, which may
  205. // contain or be another ImplWitnessAccess. Keep track of the associated
  206. // constant we are now computing the value of.
  207. substs_in_progress_.push_back(rhs_inst_id);
  208. rhs_inst_id = rewrite_value->inst_id;
  209. return SubstResult::SubstAgain;
  210. }
  211. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst)
  212. -> SemIR::InstId override {
  213. auto inst_id = RebuildNewInst(loc_id_, new_inst);
  214. auto subst_inst_id = substs_in_progress_.pop_back_val();
  215. if (auto access =
  216. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  217. subst_inst_id)) {
  218. if (auto* rewrite_value =
  219. rewrite_values_->FindRef(context(), access->inst_id)) {
  220. rewrite_values_->SetFullyRewritten(context(), *rewrite_value, inst_id);
  221. }
  222. }
  223. return inst_id;
  224. }
  225. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  226. auto subst_inst_id = substs_in_progress_.pop_back_val();
  227. if (auto access =
  228. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  229. subst_inst_id)) {
  230. if (auto* rewrite_value =
  231. rewrite_values_->FindRef(context(), access->inst_id)) {
  232. rewrite_values_->SetFullyRewritten(context(), *rewrite_value,
  233. orig_inst_id);
  234. }
  235. }
  236. return orig_inst_id;
  237. }
  238. private:
  239. struct SubstInProgress {
  240. // The associated constant whose value is being determined, represented as
  241. // an ImplWitnessAccess. Or another instruction that we are recursing
  242. // through.
  243. SemIR::InstId inst_id;
  244. };
  245. // The location of the rewrite constraints as a whole.
  246. SemIR::LocId loc_id_;
  247. // Tracks the resolved value of each rewrite constraint, keyed by the
  248. // `ImplWitnessAccess` of the associated constant on the LHS of the
  249. // constraint. The value of each associated constant may be changed during
  250. // substitution, replaced with a fully resolved value for the RHS. This allows
  251. // us to cache work; when a value for an associated constant is found once it
  252. // can be reused cheaply, avoiding exponential runtime when rewrite rules
  253. // refer to each other in ways that create exponential references.
  254. AccessRewriteValues* rewrite_values_;
  255. // A stack of instructions being replaced in Subst(). When it's an associated
  256. // constant, then it represents the constant value is being determined,
  257. // represented as an ImplWitnessAccess.
  258. //
  259. // Avoid heap allocations in common cases, if there are chains of instructions
  260. // in associated constants with a depth at most 16.
  261. llvm::SmallVector<SemIR::InstId, 16> substs_in_progress_;
  262. };
  263. auto ResolveFacetTypeRewriteConstraints(
  264. Context& context, SemIR::LocId loc_id,
  265. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  266. -> bool {
  267. if (rewrites.empty()) {
  268. return true;
  269. }
  270. AccessRewriteValues rewrite_values;
  271. for (auto& constraint : rewrites) {
  272. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  273. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  274. if (!lhs_access) {
  275. continue;
  276. }
  277. rewrite_values.InsertNotRewritten(context, lhs_access->inst_id,
  278. constraint.rhs_id);
  279. }
  280. for (auto& constraint : rewrites) {
  281. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  282. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  283. if (!lhs_access) {
  284. continue;
  285. }
  286. auto* lhs_rewrite_value =
  287. rewrite_values.FindRef(context, lhs_access->inst_id);
  288. // Every LHS was added with InsertNotRewritten above.
  289. CARBON_CHECK(lhs_rewrite_value);
  290. rewrite_values.SetBeingRewritten(*lhs_rewrite_value);
  291. auto replace_witness_callbacks =
  292. SubstImplWitnessAccessCallbacks(&context, loc_id, &rewrite_values);
  293. auto rhs_subst_inst_id =
  294. SubstInst(context, constraint.rhs_id, replace_witness_callbacks);
  295. if (rhs_subst_inst_id == SemIR::ErrorInst::InstId) {
  296. return false;
  297. }
  298. if (lhs_rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  299. auto rhs_existing_const_id =
  300. context.constant_values().Get(lhs_rewrite_value->inst_id);
  301. auto rhs_subst_const_id =
  302. context.constant_values().Get(rhs_subst_inst_id);
  303. if (rhs_subst_const_id != rhs_existing_const_id) {
  304. if (rhs_existing_const_id != SemIR::ErrorInst::ConstantId) {
  305. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  306. "associated constant {0} given two different "
  307. "values {1} and {2}",
  308. InstIdAsConstant, InstIdAsConstant,
  309. InstIdAsConstant);
  310. // Use inst id ordering as a simple proxy for source ordering, to
  311. // try to name the values in the same order they appear in the facet
  312. // type.
  313. auto source_order1 =
  314. lhs_rewrite_value->inst_id.index < rhs_subst_inst_id.index
  315. ? lhs_rewrite_value->inst_id
  316. : rhs_subst_inst_id;
  317. auto source_order2 =
  318. lhs_rewrite_value->inst_id.index >= rhs_subst_inst_id.index
  319. ? lhs_rewrite_value->inst_id
  320. : rhs_subst_inst_id;
  321. // TODO: It would be nice to note the places where the values are
  322. // assigned but rewrite constraint instructions are from canonical
  323. // constant values, and have no locations. We'd need to store a
  324. // location along with them in the rewrite constraints.
  325. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  326. GetImplWitnessAccessWithoutSubstitution(
  327. context, constraint.lhs_id),
  328. source_order1, source_order2);
  329. }
  330. return false;
  331. }
  332. }
  333. rewrite_values.SetFullyRewritten(context, *lhs_rewrite_value,
  334. rhs_subst_inst_id);
  335. }
  336. // Rebuild the `rewrites` vector with resolved values for the RHS. Drop any
  337. // duplicate rewrites in the `rewrites` vector by walking through the
  338. // `rewrite_values` map and dropping the computed RHS value for each LHS the
  339. // first time we see it, and erasing the constraint from the vector if we see
  340. // the same LHS again.
  341. size_t keep_size = rewrites.size();
  342. for (size_t i = 0; i < keep_size;) {
  343. auto& constraint = rewrites[i];
  344. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  345. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  346. if (!lhs_access) {
  347. ++i;
  348. continue;
  349. }
  350. auto& rewrite_value = *rewrite_values.FindRef(context, lhs_access->inst_id);
  351. auto rhs_id = std::exchange(rewrite_value.inst_id, SemIR::InstId::None);
  352. if (rhs_id == SemIR::InstId::None) {
  353. std::swap(rewrites[i], rewrites[keep_size - 1]);
  354. --keep_size;
  355. } else {
  356. rewrites[i].rhs_id = rhs_id;
  357. ++i;
  358. }
  359. }
  360. rewrites.erase(rewrites.begin() + keep_size, rewrites.end());
  361. return true;
  362. }
  363. auto GetEmptyFacetType(Context& context) -> SemIR::TypeId {
  364. SemIR::FacetTypeId facet_type_id =
  365. context.facet_types().Add(SemIR::FacetTypeInfo{});
  366. auto const_id = EvalOrAddInst<SemIR::FacetType>(
  367. context, SemIR::LocId::None,
  368. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  369. return context.types().GetTypeIdForTypeConstantId(const_id);
  370. }
  371. auto GetConstantFacetValueForType(Context& context,
  372. SemIR::TypeInstId type_inst_id)
  373. -> SemIR::ConstantId {
  374. // We use an empty facet type because values of type `type` do not provide any
  375. // witnesses of their own.
  376. auto type_facet_type = GetEmptyFacetType(context);
  377. return EvalOrAddInst<SemIR::FacetValue>(
  378. context, SemIR::LocId::None,
  379. {.type_id = type_facet_type,
  380. .type_inst_id = type_inst_id,
  381. .witnesses_block_id = SemIR::InstBlockId::Empty});
  382. }
  383. auto GetConstantFacetValueForTypeAndInterface(
  384. Context& context, SemIR::TypeInstId type_inst_id,
  385. SemIR::SpecificInterface specific_interface, SemIR::InstId witness_id)
  386. -> SemIR::ConstantId {
  387. // Get the type of the inner `Self`, which is the facet type of the interface.
  388. auto interface_facet_type = EvalOrAddInst(
  389. context, SemIR::LocId::None,
  390. FacetTypeFromInterface(context, specific_interface.interface_id,
  391. specific_interface.specific_id));
  392. auto self_facet_type_in_generic_without_self =
  393. context.types().GetTypeIdForTypeConstantId(interface_facet_type);
  394. auto witnesses_block_id = context.inst_blocks().AddCanonical({witness_id});
  395. auto self_value_const_id = EvalOrAddInst<SemIR::FacetValue>(
  396. context, SemIR::LocId::None,
  397. {.type_id = self_facet_type_in_generic_without_self,
  398. .type_inst_id = type_inst_id,
  399. .witnesses_block_id = witnesses_block_id});
  400. return self_value_const_id;
  401. }
  402. } // namespace Carbon::Check