facet_type.cpp 18 KB

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