simplicityhl 0.7.1

Rust-like language that compiles to Simplicity bytecode.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use crate::error::{Diagnostic, DiagnosticManager, Error, WithSpan};
use crate::parse::ParseFromStr;
use crate::str::WitnessName;
use crate::types::{AliasedType, ResolvedType};
use crate::value::Value;

macro_rules! impl_name_type_map {
    ($wrapper: ident) => {
        impl $wrapper {
            /// Get the type that is assigned to the given name.
            pub fn get(&self, name: &WitnessName) -> Option<&ResolvedType> {
                self.0.get(name)
            }

            /// Create an iterator over all name-type pairs.
            pub fn iter(&self) -> impl Iterator<Item = (&WitnessName, &ResolvedType)> {
                self.0.iter()
            }

            /// Make a cheap copy of the map.
            pub fn shallow_clone(&self) -> Self {
                Self(Arc::clone(&self.0))
            }
        }

        impl From<HashMap<WitnessName, ResolvedType>> for $wrapper {
            fn from(value: HashMap<WitnessName, ResolvedType>) -> Self {
                Self(Arc::new(value))
            }
        }
    };
}

macro_rules! impl_name_value_map {
    ($wrapper: ident, $module_name: expr) => {
        impl $wrapper {
            /// Access the inner map.
            #[cfg(feature = "serde")]
            pub(crate) fn as_inner(&self) -> &HashMap<WitnessName, Value> {
                &self.0
            }

            /// Get the value that is assigned to the given name.
            pub fn get(&self, name: &WitnessName) -> Option<&Value> {
                self.0.get(name)
            }

            /// Create an iterator over all name-value pairs.
            pub fn iter(&self) -> impl Iterator<Item = (&WitnessName, &Value)> {
                self.0.iter()
            }

            /// Make a cheap copy of the map.
            pub fn shallow_clone(&self) -> Self {
                Self(Arc::clone(&self.0))
            }
        }

        impl From<HashMap<WitnessName, Value>> for $wrapper {
            fn from(value: HashMap<WitnessName, Value>) -> Self {
                Self(Arc::new(value))
            }
        }

        impl fmt::Display for $wrapper {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                use itertools::Itertools;

                writeln!(f, "mod {} {{", $module_name)?;
                for name in self.0.keys().sorted_unstable() {
                    let value = self.0.get(name).unwrap();
                    writeln!(f, "    const {name}: {} = {value};", value.ty())?;
                }
                write!(f, "}}")
            }
        }
    };
}

/// Map of witness types.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct WitnessTypes(Arc<HashMap<WitnessName, ResolvedType>>);

impl_name_type_map!(WitnessTypes);

impl AsRef<HashMap<WitnessName, ResolvedType>> for WitnessTypes {
    fn as_ref(&self) -> &HashMap<WitnessName, ResolvedType> {
        self.0.as_ref()
    }
}

/// Map of witness values.
///
/// # Serialization of enum values is one-way
///
/// Values whose type mentions an enum serialize as bare value strings
/// (`"Action::Cold"`): the self-contained `{ value, type }` form cannot
/// express them, because its type string is parsed without the program's
/// declarations. Consequently `Deserialize` for this type rejects such
/// output. The supported round-trip goes through [`UnresolvedValues`]:
/// deserialize the file into `UnresolvedValues` and resolve it against the
/// program's declared witness types.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct WitnessValues(Arc<HashMap<WitnessName, Value>>);

impl_name_value_map!(WitnessValues, "witness");

impl WitnessValues {
    /// Check if the witness values are consistent with the declared witness types.
    ///
    /// 1. Values that occur in the program are type checked.
    /// 2. Values that don't occur in the program are skipped.
    ///    The witness map may contain more values than necessary.
    ///
    /// There may be witnesses that are referenced in the program that are not assigned a value
    /// in the witness map. These witnesses may lie on pruned branches that will not be part of the
    /// finalized Simplicity program. However, before the finalization, we cannot know which
    /// witnesses will be pruned and which won't be pruned.
    pub fn is_consistent(&self, witness_types: &WitnessTypes, diagnostics: &mut DiagnosticManager) {
        let mut entries: Vec<_> = witness_types.iter().collect();
        entries.sort_unstable_by_key(|(k, _)| *k);

        for (name, declared_ty) in entries {
            let Some(value) = self.get(name) else {
                diagnostics.push(Diagnostic::global(Error::WitnessMissing {
                    name: name.shallow_clone(),
                }));
                continue;
            };

            let assigned_ty = value.ty();
            if assigned_ty != declared_ty {
                diagnostics.push(Diagnostic::global(Error::WitnessTypeMismatch {
                    name: name.clone(),
                    declared: declared_ty.clone(),
                    assigned: assigned_ty.clone(),
                }));
            }
        }
    }
}

/// A value from a witness or argument file whose type may come from the program.
#[cfg(feature = "serde")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum UnresolvedValue {
    /// A bare value string (`"NAME": "42"`), parsed against the type
    /// that the program declares for `NAME`.
    Untyped(String),
    /// A self-typed entry (`"NAME": { "value": "42", "type": "u32" }`),
    /// parsed against the type written in the file.
    Typed(Value),
}

/// Witness or argument values parsed from a file, before their types are resolved
/// against the program.
///
/// See docs Untyped and Typed variants of `UnresolvedValue` enum to understand how entries are resolved.
///
/// Call [`UnresolvedValues::resolve`] with the program's declared types to obtain
/// [`WitnessValues`] or [`Arguments`].
#[cfg(feature = "serde")]
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct UnresolvedValues(HashMap<WitnessName, UnresolvedValue>);

#[cfg(feature = "serde")]
impl UnresolvedValues {
    pub(crate) fn from_map(map: HashMap<WitnessName, UnresolvedValue>) -> Self {
        Self(map)
    }

    /// Resolve each value against the type that the program declares for its name.
    ///
    /// Bare value strings are parsed at the declared type.
    /// Names the program does not declare are skipped.
    /// Self-typed entries pass through unchanged and are type-checked later,
    /// when the program is instantiated/satisfied.
    ///
    /// ## Errors
    ///
    /// A bare value string does not parse at the declared type.
    pub fn resolve<T, M>(self, declared_types: &M) -> Result<T, String>
    where
        T: From<HashMap<WitnessName, Value>>,
        M: AsRef<HashMap<WitnessName, ResolvedType>>,
    {
        let declared_types = declared_types.as_ref();
        let mut map = HashMap::with_capacity(self.0.len());
        for (name, unresolved) in self.0 {
            let value = match unresolved {
                UnresolvedValue::Typed(value) => value,
                UnresolvedValue::Untyped(s) => {
                    let Some(ty) = declared_types.get(&name) else {
                        continue;
                    };

                    Value::parse_from_str(&s, ty)
                        .map_err(|error| format!("`{name}` is declared as `{ty}`: {error}"))?
                }
            };
            map.insert(name, value);
        }
        Ok(T::from(map))
    }
}

impl ParseFromStr for ResolvedType {
    fn parse_from_str(s: &str) -> Result<Self, Diagnostic> {
        let aliased = AliasedType::parse_from_str(s)?;
        aliased
            .resolve_builtin()
            .map_err(|name| Error::UndefinedAlias { name })
            .with_span(s)
    }
}

/// Map of parameters.
///
/// A parameter is a named variable that resolves to a value of a given type.
/// Parameters have a name and a type.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Parameters(Arc<HashMap<WitnessName, ResolvedType>>);

impl_name_type_map!(Parameters);

impl AsRef<HashMap<WitnessName, ResolvedType>> for Parameters {
    fn as_ref(&self) -> &HashMap<WitnessName, ResolvedType> {
        self.0.as_ref()
    }
}

/// Map of arguments.
///
/// An argument is the value of a parameter.
/// Arguments have a name and a value of a given type.
///
/// # Serialization of enum values is one-way
///
/// Like [`WitnessValues`], values whose type mentions an enum serialize as
/// bare value strings, which `Deserialize` for this type rejects. The
/// supported round-trip goes through [`UnresolvedValues`]: deserialize the
/// file into `UnresolvedValues` and resolve it against the program's
/// declared parameter types.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Arguments(Arc<HashMap<WitnessName, Value>>);

impl_name_value_map!(Arguments, "param");

impl Arguments {
    /// Check if the arguments are consistent with the given parameters.
    ///
    /// 1. Each parameter must be supplied with an argument.
    /// 2. The type of each parameter must match the type of its argument.
    ///
    /// Arguments without a corresponding parameter are ignored.
    pub fn is_consistent(&self, parameters: &Parameters, diagnostics: &mut DiagnosticManager) {
        let mut entries: Vec<_> = parameters.iter().collect();
        entries.sort_unstable_by_key(|(k, _)| *k);

        for (name, parameter_ty) in entries {
            let Some(argument) = self.get(name) else {
                diagnostics.push(Diagnostic::global(Error::ArgumentMissing {
                    name: name.shallow_clone(),
                }));
                continue;
            };

            if !argument.is_of_type(parameter_ty) {
                diagnostics.push(Diagnostic::global(Error::ArgumentTypeMismatch {
                    name: name.clone(),
                    declared: parameter_ty.clone(),
                    assigned: argument.ty().clone(),
                }));
            }
        }
    }
}

#[cfg(feature = "arbitrary")]
impl crate::ArbitraryOfType for Arguments {
    type Type = Parameters;

    fn arbitrary_of_type(
        u: &mut arbitrary::Unstructured,
        ty: &Self::Type,
    ) -> arbitrary::Result<Self> {
        let mut map = HashMap::new();
        for (name, parameter_ty) in ty.iter() {
            map.insert(
                name.shallow_clone(),
                Value::arbitrary_of_type(u, parameter_ty)?,
            );
        }
        Ok(Self::from(map))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::ElementsJetHinter;
    use crate::parse::ParseFromStr;
    #[cfg(feature = "serde")]
    use crate::str::Identifier;
    #[cfg(feature = "serde")]
    use crate::types::{EnumInfo, EnumVariantInfo, TypeConstructible};
    use crate::value::ValueConstructible;
    use crate::{ast, parse, CompiledProgram, SatisfiedProgram};

    #[test]
    fn witness_reuse() {
        let s = r#"fn main() {
    assert!(jet::eq_32(witness::A, witness::A));
}"#;
        let parse_program = parse::Program::parse_from_str(s).expect("parsing works");
        match ast::Program::analyze(&parse_program, Box::new(ElementsJetHinter::new()))
            .map_err(Error::from)
        {
            Ok(_) => panic!("Witness reuse was falsely accepted"),
            Err(Error::WitnessReused { .. }) => {}
            Err(error) => panic!("Unexpected error: {error}"),
        }
    }

    #[test]
    fn witness_type_mismatch() {
        let s = r#"fn main() {
    assert!(jet::is_zero_32(witness::A));
}"#;

        let witness = WitnessValues::from(HashMap::from([(
            WitnessName::from_str_unchecked("A"),
            Value::u16(42),
        )]));
        match SatisfiedProgram::new(
            s,
            Arguments::default(),
            witness,
            false,
            Box::new(ElementsJetHinter::new()),
        ) {
            Ok(_) => panic!("Ill-typed witness assignment was falsely accepted"),
            Err(error) => assert_eq!(
                "Witness `A` was declared with type `u32` but its assigned value is of type `u16`\n",
                error
            ),
        }
    }

    #[test]
    fn witness_outside_main() {
        let s = r#"fn f() -> u32 {
    witness::OUTPUT_OF_F
}

fn main() {
    assert!(jet::is_zero_32(f()));
}"#;

        match CompiledProgram::new(
            s,
            Arguments::default(),
            false,
            Box::new(ElementsJetHinter::new()),
        ) {
            Ok(_) => panic!("Witness outside main was falsely accepted"),
            Err(error) => {
                assert!(error
                    .contains("Witness expressions are not allowed outside the `main` function"))
            }
        }
    }

    #[test]
    #[cfg(feature = "serde")]
    fn unresolved_values_resolve_against_declared_types() {
        let u32_ty = ResolvedType::parse_from_str("u32").unwrap();
        let sig_ty = ResolvedType::parse_from_str("Signature").unwrap();
        let witness_types = WitnessTypes::from(HashMap::from([
            (WitnessName::from_str_unchecked("A"), u32_ty.clone()),
            (WitnessName::from_str_unchecked("SIG"), sig_ty),
        ]));

        let unresolved = UnresolvedValues::from_map(HashMap::from([
            (
                WitnessName::from_str_unchecked("A"),
                UnresolvedValue::Untyped("42".to_string()),
            ),
            (
                WitnessName::from_str_unchecked("B"),
                UnresolvedValue::Typed(Value::u16(7)),
            ),
        ]));
        let resolved: WitnessValues = unresolved.resolve(&witness_types).unwrap();
        assert_eq!(
            resolved.get(&WitnessName::from_str_unchecked("A")),
            Some(&Value::u32(42))
        );
        assert_eq!(
            resolved.get(&WitnessName::from_str_unchecked("B")),
            Some(&Value::u16(7))
        );

        // Entries the program does not declare are skipped (consistent with `WitnessValues::is_consistent`)
        let extra = UnresolvedValues::from_map(HashMap::from([(
            WitnessName::from_str_unchecked("UNUSED"),
            UnresolvedValue::Untyped("1".to_string()),
        )]));
        let resolved: WitnessValues = extra.resolve(&witness_types).unwrap();
        assert_eq!(
            resolved.get(&WitnessName::from_str_unchecked("UNUSED")),
            None,
            "undeclared bare entries are ignored"
        );

        let bad = UnresolvedValues::from_map(HashMap::from([(
            WitnessName::from_str_unchecked("A"),
            UnresolvedValue::Untyped("not-a-number".to_string()),
        )]));
        let err = bad.resolve::<WitnessValues, _>(&witness_types).unwrap_err();
        assert!(
            err.contains('A') && err.contains("u32"),
            "error should name the witness and its declared type: {err}"
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn unresolved_values_parse_from_json() {
        // Bare strings and legacy value/type maps may be mixed in one file.
        let s = r#"{
  "A": "42",
  "B": { "value": "7", "type": "u16" }
}"#;
        let unresolved: UnresolvedValues = serde_json::from_str(s).unwrap();
        let u32_ty = ResolvedType::parse_from_str("u32").unwrap();
        let witness_types = WitnessTypes::from(HashMap::from([(
            WitnessName::from_str_unchecked("A"),
            u32_ty,
        )]));
        let resolved: WitnessValues = unresolved.resolve(&witness_types).unwrap();
        assert_eq!(
            resolved.get(&WitnessName::from_str_unchecked("A")),
            Some(&Value::u32(42))
        );
        assert_eq!(
            resolved.get(&WitnessName::from_str_unchecked("B")),
            Some(&Value::u16(7))
        );

        // Duplicate names are rejected at parse time, as for WitnessValues.
        let dup = r#"{ "A": "1", "A": "2" }"#;
        assert!(serde_json::from_str::<UnresolvedValues>(dup).is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn enum_witness_resolves_by_variant_name() {
        let variants: Arc<[EnumVariantInfo]> = ["Inherit", "ColdSpend", "HotSpend"]
            .into_iter()
            .map(|name| EnumVariantInfo::new(Identifier::from_str_unchecked(name), Arc::from([])))
            .collect();
        let action_ty = ResolvedType::enumeration(EnumInfo::new(Arc::from("Action"), variants));
        let witness_types = WitnessTypes::from(HashMap::from([(
            WitnessName::from_str_unchecked("ACTION"),
            action_ty.clone(),
        )]));

        let resolve_one = |input: &str| -> Result<Value, String> {
            let unresolved = UnresolvedValues::from_map(HashMap::from([(
                WitnessName::from_str_unchecked("ACTION"),
                UnresolvedValue::Untyped(input.to_string()),
            )]));
            let resolved: WitnessValues = unresolved.resolve(&witness_types)?;
            Ok(resolved
                .get(&WitnessName::from_str_unchecked("ACTION"))
                .unwrap()
                .clone())
        };

        let by_name = resolve_one("Action::ColdSpend").expect("written variant resolves");
        assert!(by_name.is_of_type(&action_ty));

        // The bare form is no longer a value: variants are written with
        // their enum's name, the same syntax as in source code.
        assert!(resolve_one("ColdSpend").is_err());

        let err = resolve_one("Action::Withdraw").unwrap_err();
        assert!(
            err.contains("Withdraw") && err.contains("ColdSpend"),
            "error names the bad value and the variants: {err}"
        );

        assert!(resolve_one("2").is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn enum_witness_resolves_inside_composite_types() {
        let variants: Arc<[EnumVariantInfo]> = ["Hot", "Cold"]
            .into_iter()
            .map(|name| EnumVariantInfo::new(Identifier::from_str_unchecked(name), Arc::from([])))
            .collect();
        let action_ty = ResolvedType::enumeration(EnumInfo::new(Arc::from("Action"), variants));
        let option_ty = ResolvedType::option(action_ty.clone());
        let tuple_ty = ResolvedType::tuple([
            action_ty.clone(),
            ResolvedType::parse_from_str("u32").unwrap(),
        ]);
        let witness_types = WitnessTypes::from(HashMap::from([
            (WitnessName::from_str_unchecked("MAYBE"), option_ty),
            (WitnessName::from_str_unchecked("PAIR"), tuple_ty),
        ]));

        let unresolved = UnresolvedValues::from_map(HashMap::from([
            (
                WitnessName::from_str_unchecked("MAYBE"),
                UnresolvedValue::Untyped("Some(Action::Cold)".to_string()),
            ),
            (
                WitnessName::from_str_unchecked("PAIR"),
                UnresolvedValue::Untyped("(Action::Hot, 42)".to_string()),
            ),
        ]));
        let resolved: WitnessValues = unresolved
            .resolve(&witness_types)
            .expect("variants resolve inside options and tuples");
        let maybe = resolved
            .get(&WitnessName::from_str_unchecked("MAYBE"))
            .unwrap();
        assert_eq!("Some(Action::Cold)", &maybe.to_string());
        let pair = resolved
            .get(&WitnessName::from_str_unchecked("PAIR"))
            .unwrap();
        assert_eq!("(Action::Hot, 42)", &pair.to_string());

        // A bare variant name in source code stays undefined: only files parse enum values.
        let err = ast::Expression::analyze_const(
            &parse::Expression::parse_from_str("Cold").unwrap(),
            &action_ty,
        );
        assert!(err.is_err(), "bare variants are not source syntax");
    }

    #[test]
    fn witness_to_string() {
        let witness = WitnessValues::from(HashMap::from([
            (WitnessName::from_str_unchecked("A"), Value::u32(1)),
            (WitnessName::from_str_unchecked("B"), Value::u32(2)),
            (WitnessName::from_str_unchecked("C"), Value::u32(3)),
        ]));
        let expected_string = r#"mod witness {
    const A: u32 = 1;
    const B: u32 = 2;
    const C: u32 = 3;
}"#;
        assert_eq!(expected_string, witness.to_string());
    }
}