1use crate::dag::{InternalSharing, PostOrderIterItem};
4use crate::jet::Jet;
5use crate::types::{self, arrow::Arrow};
6use crate::{encode, BitIter, BitWriter, Cmr, FailEntropy, FinalizeError, RedeemNode, Value, Word};
7
8use std::io;
9use std::marker::PhantomData;
10use std::sync::Arc;
11
12use super::{
13 Commit, CommitData, CommitNode, Converter, Inner, Marker, NoDisconnect, NoWitness, Node,
14 Redeem, RedeemData,
15};
16use super::{CoreConstructible, DisconnectConstructible, JetConstructible, WitnessConstructible};
17
18#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
23pub enum ConstructId {}
24
25#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
26pub struct Construct<J> {
27 never: std::convert::Infallible,
29 phantom: std::marker::PhantomData<J>,
31}
32
33impl<J: Jet> Marker for Construct<J> {
34 type CachedData = ConstructData<J>;
35 type Witness = Option<Value>;
36 type Disconnect = Option<Arc<ConstructNode<J>>>;
37 type SharingId = ConstructId;
38 type Jet = J;
39
40 fn compute_sharing_id(_: Cmr, _: &ConstructData<J>) -> Option<ConstructId> {
41 None
42 }
43}
44
45pub type ConstructNode<J> = Node<Construct<J>>;
46
47impl<J: Jet> ConstructNode<J> {
48 pub fn arrow(&self) -> &Arrow {
50 self.data.arrow()
51 }
52
53 pub fn set_arrow_to_program(&self) -> Result<(), types::Error> {
55 let ctx = self.data.inference_context();
56 let unit_ty = types::Type::unit(ctx);
57 ctx.unify(
58 &self.arrow().source,
59 &unit_ty,
60 "setting root source to unit",
61 )?;
62 ctx.unify(
63 &self.arrow().target,
64 &unit_ty,
65 "setting root target to unit",
66 )?;
67 Ok(())
68 }
69
70 pub fn finalize_types(&self) -> Result<Arc<CommitNode<J>>, types::Error> {
77 self.set_arrow_to_program()?;
78 self.finalize_types_non_program()
79 }
80
81 pub fn finalize_types_non_program(&self) -> Result<Arc<CommitNode<J>>, types::Error> {
85 struct FinalizeTypes<J: Jet>(PhantomData<J>);
86
87 impl<J: Jet> Converter<Construct<J>, Commit<J>> for FinalizeTypes<J> {
88 type Error = types::Error;
89
90 fn convert_witness(
91 &mut self,
92 _: &PostOrderIterItem<&ConstructNode<J>>,
93 _: &Option<Value>,
94 ) -> Result<NoWitness, Self::Error> {
95 Ok(NoWitness)
96 }
97
98 fn convert_disconnect(
99 &mut self,
100 _: &PostOrderIterItem<&ConstructNode<J>>,
101 _: Option<&Arc<CommitNode<J>>>,
102 _: &Option<Arc<ConstructNode<J>>>,
103 ) -> Result<NoDisconnect, Self::Error> {
104 Ok(NoDisconnect)
105 }
106
107 fn convert_data(
108 &mut self,
109 data: &PostOrderIterItem<&ConstructNode<J>>,
110 inner: Inner<&Arc<CommitNode<J>>, J, &NoDisconnect, &NoWitness>,
111 ) -> Result<Arc<CommitData<J>>, Self::Error> {
112 let converted_data = inner.map(|node| node.cached_data());
113 CommitData::new(&data.node.data.arrow, converted_data).map(Arc::new)
114 }
115 }
116
117 self.convert::<InternalSharing, _, _>(&mut FinalizeTypes(PhantomData))
118 }
119
120 pub fn finalize_unpruned(&self) -> Result<Arc<RedeemNode<J>>, FinalizeError> {
133 struct Finalizer<J>(PhantomData<J>);
134
135 impl<J: Jet> Converter<Construct<J>, Redeem<J>> for Finalizer<J> {
136 type Error = FinalizeError;
137
138 fn convert_witness(
139 &mut self,
140 data: &PostOrderIterItem<&ConstructNode<J>>,
141 wit: &Option<Value>,
142 ) -> Result<Value, Self::Error> {
143 if let Some(ref wit) = wit {
144 Ok(wit.shallow_clone())
145 } else {
146 let ty = data
162 .node
163 .arrow()
164 .target
165 .finalize()
166 .map_err(FinalizeError::Type)?;
167 Ok(Value::zero(&ty))
168 }
169 }
170
171 fn convert_disconnect(
172 &mut self,
173 _: &PostOrderIterItem<&ConstructNode<J>>,
174 maybe_converted: Option<&Arc<RedeemNode<J>>>,
175 _: &Option<Arc<ConstructNode<J>>>,
176 ) -> Result<Arc<RedeemNode<J>>, Self::Error> {
177 if let Some(child) = maybe_converted {
178 Ok(Arc::clone(child))
179 } else {
180 Err(FinalizeError::DisconnectRedeemTime)
181 }
182 }
183
184 fn convert_data(
185 &mut self,
186 data: &PostOrderIterItem<&ConstructNode<J>>,
187 inner: Inner<&Arc<RedeemNode<J>>, J, &Arc<RedeemNode<J>>, &Value>,
188 ) -> Result<Arc<RedeemData<J>>, Self::Error> {
189 let converted_data = inner
190 .map(|node| node.cached_data())
191 .map_disconnect(|node| node.cached_data())
192 .map_witness(Value::shallow_clone);
193 Ok(Arc::new(RedeemData::new(
194 data.node.arrow().finalize().map_err(FinalizeError::Type)?,
195 converted_data,
196 )))
197 }
198 }
199
200 self.convert::<InternalSharing, _, _>(&mut Finalizer(PhantomData))
201 }
202
203 pub fn finalize_pruned(
216 &self,
217 env: &J::Environment,
218 ) -> Result<Arc<RedeemNode<J>>, FinalizeError> {
219 let unpruned = self.finalize_unpruned()?;
220 unpruned.prune(env).map_err(FinalizeError::Execution)
221 }
222
223 pub fn decode<I: Iterator<Item = u8>>(
233 mut bits: BitIter<I>,
234 ) -> Result<Arc<Self>, crate::decode::Error> {
235 let res = crate::decode::decode_expression(&mut bits)?;
236 bits.close()?;
237 Ok(res)
238 }
239
240 #[cfg(feature = "base64")]
241 #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Result<Arc<Self>, crate::ParseError> {
243 use crate::base64::engine::general_purpose;
244 use crate::base64::Engine as _;
245
246 let v = general_purpose::STANDARD
247 .decode(s)
248 .map_err(crate::ParseError::Base64)?;
249 let iter = crate::BitIter::new(v.into_iter());
250 Self::decode(iter)
251 .map_err(crate::DecodeError::Decode)
252 .map_err(crate::ParseError::Decode)
253 }
254
255 #[deprecated(since = "0.5.0", note = "use Self::encode_without_witness instead")]
257 pub fn encode<W: io::Write>(&self, w: &mut BitWriter<W>) -> io::Result<usize> {
258 let program_bits = encode::encode_program(self, w)?;
259 w.flush_all()?;
260 Ok(program_bits)
261 }
262}
263
264#[derive(Clone, Debug)]
265pub struct ConstructData<J> {
266 arrow: Arrow,
267 phantom: PhantomData<J>,
271}
272
273impl<J: Jet> ConstructData<J> {
274 pub fn new(arrow: Arrow) -> Self {
276 ConstructData {
277 arrow,
278 phantom: PhantomData,
279 }
280 }
281
282 pub fn arrow(&self) -> &Arrow {
284 &self.arrow
285 }
286}
287
288impl<J> CoreConstructible for ConstructData<J> {
289 fn iden(inference_context: &types::Context) -> Self {
290 ConstructData {
291 arrow: Arrow::iden(inference_context),
292 phantom: PhantomData,
293 }
294 }
295
296 fn unit(inference_context: &types::Context) -> Self {
297 ConstructData {
298 arrow: Arrow::unit(inference_context),
299 phantom: PhantomData,
300 }
301 }
302
303 fn injl(child: &Self) -> Self {
304 ConstructData {
305 arrow: Arrow::injl(&child.arrow),
306 phantom: PhantomData,
307 }
308 }
309
310 fn injr(child: &Self) -> Self {
311 ConstructData {
312 arrow: Arrow::injr(&child.arrow),
313 phantom: PhantomData,
314 }
315 }
316
317 fn take(child: &Self) -> Self {
318 ConstructData {
319 arrow: Arrow::take(&child.arrow),
320 phantom: PhantomData,
321 }
322 }
323
324 fn drop_(child: &Self) -> Self {
325 ConstructData {
326 arrow: Arrow::drop_(&child.arrow),
327 phantom: PhantomData,
328 }
329 }
330
331 fn comp(left: &Self, right: &Self) -> Result<Self, types::Error> {
332 Ok(ConstructData {
333 arrow: Arrow::comp(&left.arrow, &right.arrow)?,
334 phantom: PhantomData,
335 })
336 }
337
338 fn case(left: &Self, right: &Self) -> Result<Self, types::Error> {
339 Ok(ConstructData {
340 arrow: Arrow::case(&left.arrow, &right.arrow)?,
341 phantom: PhantomData,
342 })
343 }
344
345 fn assertl(left: &Self, right: Cmr) -> Result<Self, types::Error> {
346 Ok(ConstructData {
347 arrow: Arrow::assertl(&left.arrow, right)?,
348 phantom: PhantomData,
349 })
350 }
351
352 fn assertr(left: Cmr, right: &Self) -> Result<Self, types::Error> {
353 Ok(ConstructData {
354 arrow: Arrow::assertr(left, &right.arrow)?,
355 phantom: PhantomData,
356 })
357 }
358
359 fn pair(left: &Self, right: &Self) -> Result<Self, types::Error> {
360 Ok(ConstructData {
361 arrow: Arrow::pair(&left.arrow, &right.arrow)?,
362 phantom: PhantomData,
363 })
364 }
365
366 fn fail(inference_context: &types::Context, entropy: FailEntropy) -> Self {
367 ConstructData {
368 arrow: Arrow::fail(inference_context, entropy),
369 phantom: PhantomData,
370 }
371 }
372
373 fn const_word(inference_context: &types::Context, word: Word) -> Self {
374 ConstructData {
375 arrow: Arrow::const_word(inference_context, word),
376 phantom: PhantomData,
377 }
378 }
379
380 fn inference_context(&self) -> &types::Context {
381 self.arrow.inference_context()
382 }
383}
384
385impl<J: Jet> DisconnectConstructible<Option<Arc<ConstructNode<J>>>> for ConstructData<J> {
386 fn disconnect(
387 left: &Self,
388 right: &Option<Arc<ConstructNode<J>>>,
389 ) -> Result<Self, types::Error> {
390 let right = right.as_ref();
391 Ok(ConstructData {
392 arrow: Arrow::disconnect(&left.arrow, &right.map(|n| n.arrow()))?,
393 phantom: PhantomData,
394 })
395 }
396}
397
398impl<J> WitnessConstructible<Option<Value>> for ConstructData<J> {
399 fn witness(inference_context: &types::Context, _witness: Option<Value>) -> Self {
400 ConstructData {
401 arrow: Arrow::witness(inference_context, NoWitness),
402 phantom: PhantomData,
403 }
404 }
405}
406
407impl<J: Jet> JetConstructible<J> for ConstructData<J> {
408 fn jet(inference_context: &types::Context, jet: J) -> Self {
409 ConstructData {
410 arrow: Arrow::jet(inference_context, jet),
411 phantom: PhantomData,
412 }
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use crate::jet::Core;
420 use crate::types::Final;
421 use crate::Value;
422
423 #[test]
424 fn occurs_check_error() {
425 let ctx = types::Context::new();
426 let iden = Arc::<ConstructNode<Core>>::iden(&ctx);
427 let node = Arc::<ConstructNode<Core>>::disconnect(&iden, &Some(Arc::clone(&iden))).unwrap();
428
429 assert!(matches!(
430 node.finalize_types_non_program(),
431 Err(types::Error::OccursCheck { .. }),
432 ));
433 }
434
435 #[test]
436 fn occurs_check_2() {
437 let ctx = types::Context::new();
438 let iden = Arc::<ConstructNode<Core>>::iden(&ctx);
440 let injr = Arc::<ConstructNode<Core>>::injr(&iden);
441 let pair = Arc::<ConstructNode<Core>>::pair(&injr, &iden).unwrap();
442 let drop = Arc::<ConstructNode<Core>>::drop_(&pair);
443
444 let case1 = Arc::<ConstructNode<Core>>::case(&drop, &drop).unwrap();
445 let case2 = Arc::<ConstructNode<Core>>::case(&case1, &case1).unwrap();
446
447 let comp1 = Arc::<ConstructNode<Core>>::comp(&case2, &case2).unwrap();
448 let comp2 = Arc::<ConstructNode<Core>>::comp(&comp1, &case1).unwrap();
449
450 assert!(matches!(
451 comp2.finalize_types_non_program(),
452 Err(types::Error::OccursCheck { .. }),
453 ));
454 }
455
456 #[test]
457 fn occurs_check_3() {
458 let ctx = types::Context::new();
459 let wit = Arc::<ConstructNode<Core>>::witness(&ctx, None);
461 let drop = Arc::<ConstructNode<Core>>::drop_(&wit);
462
463 let comp1 = Arc::<ConstructNode<Core>>::comp(&drop, &drop).unwrap();
464 let comp2 = Arc::<ConstructNode<Core>>::comp(&comp1, &comp1).unwrap();
465 let comp3 = Arc::<ConstructNode<Core>>::comp(&comp2, &comp2).unwrap();
466 let comp4 = Arc::<ConstructNode<Core>>::comp(&comp3, &comp3).unwrap();
467 let comp5 = Arc::<ConstructNode<Core>>::comp(&comp4, &comp4).unwrap();
468
469 let case = Arc::<ConstructNode<Core>>::case(&comp5, &comp4).unwrap();
470 let drop2 = Arc::<ConstructNode<Core>>::drop_(&case);
471 let case2 = Arc::<ConstructNode<Core>>::case(&drop2, &case).unwrap();
472 let comp6 = Arc::<ConstructNode<Core>>::comp(&case2, &case2).unwrap();
473 let case3 = Arc::<ConstructNode<Core>>::case(&comp6, &comp6).unwrap();
474
475 let comp7 = Arc::<ConstructNode<Core>>::comp(&case3, &case3).unwrap();
476 let comp8 = Arc::<ConstructNode<Core>>::comp(&comp7, &comp7).unwrap();
477
478 assert!(matches!(
479 comp8.finalize_types_non_program(),
480 Err(types::Error::OccursCheck { .. }),
481 ));
482 }
483
484 #[test]
485 fn type_check_error() {
486 let ctx = types::Context::new();
487 let unit = Arc::<ConstructNode<Core>>::unit(&ctx);
488 let case = Arc::<ConstructNode<Core>>::case(&unit, &unit).unwrap();
489
490 assert!(matches!(
491 Arc::<ConstructNode<Core>>::disconnect(&case, &Some(unit)),
492 Err(types::Error::Bind { .. }),
493 ));
494 }
495
496 #[test]
497 fn scribe() {
498 let ctx = types::Context::new();
502 let unit = Arc::<ConstructNode<Core>>::unit(&ctx);
503 let bit0 = Arc::<ConstructNode<Core>>::const_word(&ctx, Word::u1(0));
504 let bit1 = Arc::<ConstructNode<Core>>::const_word(&ctx, Word::u1(1));
505
506 assert_eq!(
507 unit.cmr(),
508 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::unit()).cmr()
509 );
510 assert_eq!(
511 bit0.cmr(),
512 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::u1(0)).cmr()
513 );
514 assert_eq!(
515 bit1.cmr(),
516 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::u1(1)).cmr()
517 );
518 assert_eq!(
519 Arc::<ConstructNode<Core>>::const_word(&ctx, Word::u2(1)).cmr(),
520 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::u2(1)).cmr()
521 );
522 assert_eq!(
523 Arc::<ConstructNode<Core>>::injl(&bit0).cmr(),
524 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::left(Value::u1(0), Final::unit()))
525 .cmr()
526 );
527 assert_eq!(
528 Arc::<ConstructNode<Core>>::injr(&bit1).cmr(),
529 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::right(Final::unit(), Value::u1(1)))
530 .cmr()
531 );
532 assert_eq!(
533 Arc::<ConstructNode<Core>>::pair(&unit, &unit)
534 .unwrap()
535 .cmr(),
536 Arc::<ConstructNode<Core>>::scribe(&ctx, &Value::product(Value::unit(), Value::unit()))
537 .cmr()
538 );
539 }
540
541 #[test]
542 fn regression_286_1() {
543 let ctx = types::Context::new();
546 let cmr = Cmr::from_byte_array([0xde; 32]);
547
548 let u0 = Arc::<ConstructNode<Core>>::unit(&ctx);
549 let i1 = Arc::<ConstructNode<Core>>::injl(&u0);
550 let i2 = Arc::<ConstructNode<Core>>::injr(&i1);
551 let i3 = Arc::<ConstructNode<Core>>::injr(&i2);
552 let i4 = Arc::<ConstructNode<Core>>::injl(&i3);
553 let u5 = Arc::<ConstructNode<Core>>::unit(&ctx);
554 let i6 = Arc::<ConstructNode<Core>>::injl(&u5);
555 let i7 = Arc::<ConstructNode<Core>>::injr(&i6);
556 let p8 = Arc::<ConstructNode<Core>>::pair(&i4, &i7).unwrap();
557 let u9 = Arc::<ConstructNode<Core>>::unit(&ctx);
558 let a10 = Arc::<ConstructNode<Core>>::assertr(cmr, &u9).unwrap();
559 let u11 = Arc::<ConstructNode<Core>>::unit(&ctx);
560 let a12 = Arc::<ConstructNode<Core>>::assertr(cmr, &u11).unwrap();
561 let a13 = Arc::<ConstructNode<Core>>::assertl(&a12, cmr).unwrap();
562 let c14 = Arc::<ConstructNode<Core>>::case(&a10, &a13).unwrap();
563 let c15 = Arc::<ConstructNode<Core>>::comp(&p8, &c14).unwrap();
564
565 let finalized: Arc<CommitNode<_>> = c15.finalize_types().unwrap();
566 let prog = finalized.to_vec_without_witness();
567 assert_eq!(
569 hex::DisplayHex::as_hex(&prog).to_string(),
570 "dc920a28812b6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f243090e00b10e00680",
571 );
572
573 let prog = BitIter::from(prog);
574 let decode = CommitNode::<Core>::decode(prog).unwrap();
575
576 assert_eq!(finalized, decode);
578 }
579
580 #[test]
581 fn regression_286_2() {
582 let ctx = types::Context::new();
590
591 let w0 = Arc::<ConstructNode<Core>>::witness(&ctx, None);
592 let i1 = Arc::<ConstructNode<Core>>::iden(&ctx);
593 let d2 = Arc::<ConstructNode<Core>>::drop_(&i1);
594 let i3 = Arc::<ConstructNode<Core>>::iden(&ctx);
595 let i4 = Arc::<ConstructNode<Core>>::iden(&ctx);
596 let t5 = Arc::<ConstructNode<Core>>::take(&i4);
597 let ca6 = Arc::<ConstructNode<Core>>::case(&i3, &t5).unwrap();
598 let ca7 = Arc::<ConstructNode<Core>>::case(&d2, &ca6).unwrap();
599 let c8 = Arc::<ConstructNode<Core>>::comp(&w0, &ca7).unwrap();
600 let u9 = Arc::<ConstructNode<Core>>::unit(&ctx);
601 let c10 = Arc::<ConstructNode<Core>>::comp(&c8, &u9).unwrap();
602
603 let err = c10.finalize_types().unwrap_err();
605 assert!(matches!(err, types::Error::OccursCheck { .. }));
606 }
607}