facet_type.cpp 19 KB

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