facet_type.cpp 19 KB

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