puffin/algebra/
mod.rs

1//! The *term* module defines typed[`DYTerm`]s of the form `fn_add(x: u8, fn_square(y: u16)) → u16`.
2//!
3//! Each function like `fn_add` or `fn_square` has a shape. The variables `x` and `y` each have a
4//! type. These types allow type checks during the runtime of the fuzzer.
5//! These checks restrict how[`DYTerm`]scan be mutated in the *fuzzer* module.
6
7// Code in this directory is derived from https://github.com/joshrule/term-rewriting-rs/
8// and is licensed under:
9//
10// The MIT License (MIT)
11// Copyright (c) 2018--2021
12// Maximilian Ammann <max@maxammann.org>, Joshua S. Rule <joshua.s.rule@gmail.com>
13//
14// Permission is hereby granted, free of charge, to any person obtaining a copy
15// of this software and associated documentation files (the "Software"), to deal
16// in the Software without restriction, including without limitation the rights
17// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18// copies of the Software, and to permit persons to whom the Software is
19// furnished to do so, subject to the following conditions:
20//
21// The above copyright notice and this permission notice shall be included in all
22// copies or substantial portions of the Software.
23//
24// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30// SOFTWARE.
31
32use std::fmt;
33use std::hash::Hash;
34
35use serde::de::DeserializeOwned;
36use serde::{Deserialize, Serialize};
37
38pub use self::term::*;
39
40pub mod atoms;
41pub mod bitstrings;
42pub mod dynamic_function;
43pub mod error;
44pub mod macros;
45pub mod signature;
46pub mod term;
47
48impl<T> Matcher for Option<T>
49where
50    T: Matcher,
51{
52    fn matches(&self, matcher: &Self) -> bool {
53        match (self, matcher) {
54            (Some(inner), Some(inner_matcher)) => inner.matches(inner_matcher),
55            (Some(_), None) => true, // None matches everything as query -> True
56            (None, None) => true,    // None == None => True
57            (None, Some(_)) => false, // None != Some => False
58        }
59    }
60
61    fn specificity(&self) -> u32 {
62        if let Some(matcher) = self {
63            1 + matcher.specificity()
64        } else {
65            0
66        }
67    }
68}
69
70/// Determines whether two instances match. We can also ask it how specific it is.
71pub trait Matcher:
72    fmt::Debug + Clone + Hash + serde::Serialize + DeserializeOwned + PartialEq
73{
74    fn matches(&self, matcher: &Self) -> bool;
75
76    fn specificity(&self) -> u32;
77}
78
79#[derive(Debug, Clone, Hash, PartialEq, Serialize, Deserialize)]
80pub struct AnyMatcher;
81
82impl Matcher for AnyMatcher {
83    fn matches(&self, _matcher: &Self) -> bool {
84        true
85    }
86
87    fn specificity(&self) -> u32 {
88        0
89    }
90}
91
92#[cfg(test)]
93#[allow(clippy::ptr_arg)]
94pub mod test_signature {
95    use std::any::TypeId;
96    use std::fmt;
97    use std::io::Read;
98
99    use comparable::Comparable;
100    use puffin_build::puffin;
101    use serde::{Deserialize, Serialize};
102
103    use crate::agent::{AgentDescriptor, AgentName, ProtocolDescriptorConfig};
104    use crate::algebra::dynamic_function::{FunctionAttributes, TypeShape};
105    use crate::algebra::error::FnError;
106    use crate::algebra::{AnyMatcher, Term};
107    use crate::claims::{Claim, GlobalClaimList, SecurityViolationPolicy};
108    use crate::codec::{CodecP, Reader};
109    use crate::error::Error;
110    use crate::protocol::{
111        EvaluatedTerm, Extractable, OpaqueProtocolMessage, OpaqueProtocolMessageFlight,
112        ProtocolBehavior, ProtocolMessage, ProtocolMessageDeframer, ProtocolMessageFlight,
113        ProtocolTypes,
114    };
115    use crate::put::{Put, PutOptions};
116    use crate::put_registry::Factory;
117    use crate::trace::{Action, InputAction, Knowledge, Source, Step, StepNumber, Trace};
118    use crate::{
119        codec, define_signature, dummy_codec, dummy_extract_knowledge,
120        dummy_extract_knowledge_codec, term,
121    };
122
123    #[derive(Debug, Clone, Comparable)]
124    pub struct HmacKey;
125    #[derive(Debug, Clone, Comparable)]
126    pub struct HandshakeMessage;
127    #[derive(Debug, Clone, Comparable)]
128    pub struct Encrypted;
129    #[derive(Debug, Clone, Comparable)]
130    pub struct ProtocolVersion;
131    #[derive(Debug, Clone, Comparable)]
132    pub struct Random;
133    #[derive(Debug, Clone, Comparable)]
134    pub struct ClientExtension;
135    #[derive(Debug, Clone, Comparable)]
136    pub struct ClientExtensions;
137    #[derive(Debug, Clone, Comparable)]
138    pub struct Group;
139    #[derive(Debug, Clone, Comparable)]
140    pub struct SessionID;
141    #[derive(Debug, Clone, Comparable)]
142    pub struct CipherSuites;
143    #[derive(Debug, Clone, Comparable)]
144    pub struct CipherSuite;
145    #[derive(Debug, Clone, Comparable)]
146    pub struct Compression;
147    #[derive(Debug, Clone, Comparable)]
148    pub struct Compressions;
149
150    dummy_extract_knowledge_codec!(TestProtocolTypes, HmacKey);
151    dummy_extract_knowledge_codec!(TestProtocolTypes, HandshakeMessage);
152    dummy_extract_knowledge_codec!(TestProtocolTypes, Encrypted);
153    dummy_extract_knowledge_codec!(TestProtocolTypes, ProtocolVersion);
154    dummy_extract_knowledge_codec!(TestProtocolTypes, Random);
155    dummy_extract_knowledge_codec!(TestProtocolTypes, ClientExtension);
156    dummy_extract_knowledge_codec!(TestProtocolTypes, ClientExtensions);
157    dummy_extract_knowledge_codec!(TestProtocolTypes, Group);
158    dummy_extract_knowledge_codec!(TestProtocolTypes, SessionID);
159    dummy_extract_knowledge_codec!(TestProtocolTypes, CipherSuites);
160    dummy_extract_knowledge_codec!(TestProtocolTypes, CipherSuite);
161    dummy_extract_knowledge_codec!(TestProtocolTypes, Compression);
162    dummy_extract_knowledge_codec!(TestProtocolTypes, Compressions);
163    dummy_extract_knowledge!(TestProtocolTypes, u8);
164    dummy_extract_knowledge!(TestProtocolTypes, u16);
165    dummy_extract_knowledge!(TestProtocolTypes, u32);
166    dummy_extract_knowledge!(TestProtocolTypes, u64);
167
168    pub fn fn_hmac256_new_key() -> Result<HmacKey, FnError> {
169        Ok(HmacKey)
170    }
171
172    pub fn fn_hmac256(_key: &HmacKey, _msg: &Vec<u8>) -> Result<Vec<u8>, FnError> {
173        Ok(Vec::new())
174    }
175
176    pub fn fn_client_hello(
177        _version: &ProtocolVersion,
178        _random: &Random,
179        _id: &SessionID,
180        _suites: &CipherSuites,
181        _compressions: &Compressions,
182        _extensions: &ClientExtensions,
183    ) -> Result<HandshakeMessage, FnError> {
184        Ok(HandshakeMessage)
185    }
186
187    pub fn fn_finished() -> Result<HandshakeMessage, FnError> {
188        Ok(HandshakeMessage)
189    }
190
191    pub fn fn_protocol_version12() -> Result<ProtocolVersion, FnError> {
192        Ok(ProtocolVersion)
193    }
194    pub fn fn_new_session_id() -> Result<SessionID, FnError> {
195        Ok(SessionID)
196    }
197
198    pub fn fn_new_random() -> Result<Random, FnError> {
199        Ok(Random)
200    }
201
202    pub fn fn_client_extensions_append(
203        _extensions: &ClientExtensions,
204        _extension: &ClientExtension,
205    ) -> Result<ClientExtensions, FnError> {
206        Ok(ClientExtensions)
207    }
208
209    pub fn fn_client_extensions_new() -> Result<ClientExtensions, FnError> {
210        Ok(ClientExtensions)
211    }
212    pub fn fn_support_group_extension(_group: &Group) -> Result<ClientExtension, FnError> {
213        Ok(ClientExtension)
214    }
215
216    pub fn fn_signature_algorithm_extension() -> Result<ClientExtension, FnError> {
217        Ok(ClientExtension)
218    }
219    pub fn fn_ec_point_formats_extension() -> Result<ClientExtension, FnError> {
220        Ok(ClientExtension)
221    }
222    pub fn fn_signed_certificate_timestamp_extension() -> Result<ClientExtension, FnError> {
223        Ok(ClientExtension)
224    }
225    pub fn fn_renegotiation_info_extension(_info: &Vec<u8>) -> Result<ClientExtension, FnError> {
226        Ok(ClientExtension)
227    }
228    pub fn fn_signature_algorithm_cert_extension() -> Result<ClientExtension, FnError> {
229        Ok(ClientExtension)
230    }
231
232    pub fn fn_empty_bytes_vec() -> Result<Vec<u8>, FnError> {
233        Ok(Vec::new())
234    }
235
236    pub fn fn_named_group_secp384r1() -> Result<Group, FnError> {
237        Ok(Group)
238    }
239
240    pub fn fn_client_key_exchange() -> Result<HandshakeMessage, FnError> {
241        Ok(HandshakeMessage)
242    }
243
244    pub fn fn_new_cipher_suites() -> Result<CipherSuites, FnError> {
245        Ok(CipherSuites)
246    }
247
248    pub fn fn_append_cipher_suite(
249        _suites: &CipherSuites,
250        _suite: &CipherSuite,
251    ) -> Result<CipherSuites, FnError> {
252        Ok(CipherSuites)
253    }
254    pub fn fn_cipher_suite12() -> Result<CipherSuite, FnError> {
255        Ok(CipherSuite)
256    }
257
258    pub fn fn_compressions() -> Result<Compressions, FnError> {
259        Ok(Compressions)
260    }
261
262    pub fn fn_encrypt12(_finished: &HandshakeMessage, _seq: &u32) -> Result<Encrypted, FnError> {
263        Ok(Encrypted)
264    }
265
266    pub fn fn_seq_0() -> Result<u32, FnError> {
267        Ok(0)
268    }
269
270    pub fn fn_seq_1() -> Result<u32, FnError> {
271        Ok(1)
272    }
273
274    pub fn example_op_c(a: &u8) -> Result<u16, FnError> {
275        Ok(u16::from(a + 1))
276    }
277
278    fn create_client_hello() -> TestTerm {
279        term! {
280              fn_client_hello(
281                fn_protocol_version12,
282                fn_new_random,
283                fn_new_session_id,
284                (fn_append_cipher_suite(
285                    (fn_new_cipher_suites()),
286                    fn_cipher_suite12
287                )),
288                fn_compressions,
289                (fn_client_extensions_append(
290                    (fn_client_extensions_append(
291                        (fn_client_extensions_append(
292                            (fn_client_extensions_append(
293                                (fn_client_extensions_append(
294                                    (fn_client_extensions_append(
295                                        fn_client_extensions_new,
296                                        (fn_support_group_extension(fn_named_group_secp384r1))
297                                    )),
298                                    fn_signature_algorithm_extension
299                                )),
300                                fn_ec_point_formats_extension
301                            )),
302                            fn_signed_certificate_timestamp_extension
303                        )),
304                         // Enable Renegotiation
305                        (fn_renegotiation_info_extension(fn_empty_bytes_vec))
306                    )),
307                    // Add signature cert extension
308                    fn_signature_algorithm_cert_extension
309                ))
310            )
311        }
312    }
313
314    #[must_use]
315    pub fn setup_simple_trace() -> TestTrace {
316        let server = AgentName::first();
317        let client_hello = create_client_hello();
318
319        Trace {
320            prior_traces: vec![],
321            descriptors: vec![AgentDescriptor::from_name(server)],
322            steps: vec![
323                Step {
324                    agent: server,
325                    action: Action::Input(InputAction {
326                        precomputations: vec![],
327                        recipe: client_hello,
328                    }),
329                },
330                Step {
331                    agent: server,
332                    action: Action::Input(InputAction {
333                        precomputations: vec![],
334                        recipe: term! {fn_client_key_exchange},
335                    }),
336                },
337                Step {
338                    agent: server,
339                    action: Action::Input(InputAction {
340                        precomputations: vec![],
341                        recipe: term! {fn_encrypt12(fn_finished,fn_seq_0)},
342                    }),
343                },
344            ],
345            ..Default::default()
346        }
347    }
348
349    define_signature!(
350        TEST_SIGNATURE<TestProtocolTypes>,
351        fn_hmac256_new_key
352        fn_hmac256
353        fn_client_hello
354        fn_finished
355        fn_protocol_version12
356        fn_new_session_id
357        fn_new_random
358        fn_client_extensions_append
359        fn_client_extensions_new
360        fn_support_group_extension
361        fn_signature_algorithm_extension
362        fn_ec_point_formats_extension
363        fn_signed_certificate_timestamp_extension
364        fn_renegotiation_info_extension
365        fn_signature_algorithm_cert_extension
366        fn_empty_bytes_vec
367        fn_named_group_secp384r1
368        fn_client_key_exchange
369        fn_new_cipher_suites
370        fn_append_cipher_suite
371        fn_cipher_suite12
372        fn_compressions
373        fn_encrypt12
374        fn_seq_0
375        fn_seq_1
376    );
377
378    pub type TestTrace = Trace<TestProtocolTypes>;
379    pub type TestTerm = Term<TestProtocolTypes>;
380
381    #[derive(Clone, Comparable, PartialEq)]
382    pub struct TestClaim;
383
384    dummy_extract_knowledge_codec!(TestProtocolTypes, TestClaim);
385
386    impl fmt::Debug for TestClaim {
387        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
388            panic!("Not implemented for test stub");
389        }
390    }
391
392    impl Claim for TestClaim {
393        type PT = TestProtocolTypes;
394
395        fn agent_name(&self) -> AgentName {
396            panic!("Not implemented for test stub");
397        }
398
399        fn id(&self) -> TypeShape<TestProtocolTypes> {
400            panic!("Not implemented for test stub");
401        }
402
403        fn inner(&self) -> Box<dyn EvaluatedTerm<TestProtocolTypes>> {
404            panic!("Not implemented for test stub");
405        }
406
407        fn set_step(&mut self, _step: Option<StepNumber>) {}
408
409        fn get_step(&self) -> Option<StepNumber> {
410            None
411        }
412    }
413
414    #[derive(Comparable)]
415    pub struct TestOpaqueMessage;
416
417    impl Clone for TestOpaqueMessage {
418        fn clone(&self) -> Self {
419            panic!("Not implemented for test stub");
420        }
421    }
422
423    impl fmt::Debug for TestOpaqueMessage {
424        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
425            panic!("Not implemented for test stub");
426        }
427    }
428
429    impl CodecP for TestOpaqueMessage {
430        fn encode(&self, _bytes: &mut Vec<u8>) {
431            panic!("Not implemented for test stub");
432        }
433
434        fn read(&mut self, _: &mut Reader) -> Result<(), Error> {
435            panic!("Not implemented for test stub");
436        }
437    }
438
439    impl OpaqueProtocolMessage<TestProtocolTypes> for TestOpaqueMessage {
440        fn debug(&self, _info: &str) {
441            panic!("Not implemented for test stub");
442        }
443    }
444
445    dummy_extract_knowledge!(TestProtocolTypes, TestOpaqueMessage);
446
447    #[derive(Comparable)]
448    pub struct TestMessage;
449
450    impl Clone for TestMessage {
451        fn clone(&self) -> Self {
452            panic!("Not implemented for test stub");
453        }
454    }
455
456    impl fmt::Debug for TestMessage {
457        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
458            panic!("Not implemented for test stub");
459        }
460    }
461
462    impl ProtocolMessage<TestProtocolTypes, TestOpaqueMessage> for TestMessage {
463        fn create_opaque(&self) -> TestOpaqueMessage {
464            panic!("Not implemented for test stub");
465        }
466
467        fn debug(&self, _info: &str) {
468            panic!("Not implemented for test stub");
469        }
470    }
471
472    dummy_extract_knowledge_codec!(TestProtocolTypes, TestMessage);
473
474    pub struct TestMessageDeframer;
475
476    impl ProtocolMessageDeframer<TestProtocolTypes> for TestMessageDeframer {
477        type OpaqueProtocolMessage = TestOpaqueMessage;
478
479        fn pop_frame(&mut self) -> Option<TestOpaqueMessage> {
480            panic!("Not implemented for test stub");
481        }
482
483        fn read(&mut self, _rd: &mut dyn Read) -> std::io::Result<usize> {
484            panic!("Not implemented for test stub");
485        }
486    }
487
488    pub struct TestSecurityViolationPolicy;
489    impl SecurityViolationPolicy for TestSecurityViolationPolicy {
490        type C = TestClaim;
491
492        fn check_violation(_claims: &[TestClaim]) -> Option<&'static str> {
493            panic!("Not implemented for test stub");
494        }
495    }
496
497    #[derive(Debug, Clone, Comparable)]
498    pub struct TestMessageFlight;
499
500    impl
501        ProtocolMessageFlight<
502            TestProtocolTypes,
503            TestMessage,
504            TestOpaqueMessage,
505            TestOpaqueMessageFlight,
506        > for TestMessageFlight
507    {
508        fn new() -> Self {
509            Self {}
510        }
511
512        fn push(&mut self, _msg: TestMessage) {
513            panic!("Not implemented for test stub");
514        }
515
516        fn debug(&self, _info: &str) {
517            panic!("Not implemented for test stub");
518        }
519    }
520
521    impl TryFrom<TestOpaqueMessageFlight> for TestMessageFlight {
522        type Error = ();
523
524        fn try_from(_value: TestOpaqueMessageFlight) -> Result<Self, Self::Error> {
525            Ok(Self)
526        }
527    }
528
529    dummy_extract_knowledge_codec!(TestProtocolTypes, TestMessageFlight);
530
531    impl From<TestMessage> for TestMessageFlight {
532        fn from(_value: TestMessage) -> Self {
533            Self {}
534        }
535    }
536
537    #[derive(Debug, Clone, Default, Comparable)]
538    pub struct TestOpaqueMessageFlight;
539
540    impl OpaqueProtocolMessageFlight<TestProtocolTypes, TestOpaqueMessage> for TestOpaqueMessageFlight {
541        fn new() -> Self {
542            Self {}
543        }
544
545        fn push(&mut self, _msg: TestOpaqueMessage) {
546            panic!("Not implemented for test stub");
547        }
548
549        fn debug(&self, _info: &str) {
550            panic!("Not implemented for test stub");
551        }
552    }
553
554    dummy_extract_knowledge!(TestProtocolTypes, TestOpaqueMessageFlight);
555
556    impl From<TestOpaqueMessage> for TestOpaqueMessageFlight {
557        fn from(_value: TestOpaqueMessage) -> Self {
558            Self {}
559        }
560    }
561
562    impl codec::Codec for TestOpaqueMessageFlight {
563        fn encode(&self, _bytes: &mut Vec<u8>) {
564            panic!("Not implemented for test stub");
565        }
566
567        fn read(_: &mut Reader) -> Option<Self> {
568            panic!("Not implemented for test stub");
569        }
570    }
571
572    impl From<TestMessageFlight> for TestOpaqueMessageFlight {
573        fn from(_value: TestMessageFlight) -> Self {
574            Self {}
575        }
576    }
577
578    #[derive(Clone, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)]
579    pub struct TestProtocolTypes;
580
581    impl ProtocolTypes for TestProtocolTypes {
582        type Matcher = AnyMatcher;
583        type PUTConfig = TestPUTConfig;
584
585        fn signature() -> &'static Signature<Self> {
586            &TEST_SIGNATURE
587        }
588
589        fn differential_fuzzing_whitelist() -> Option<Vec<TypeId>> {
590            None
591        }
592
593        fn differential_fuzzing_terms_to_eval(
594            _agents: &Vec<AgentDescriptor<Self::PUTConfig>>,
595        ) -> Vec<crate::algebra::Term<Self>> {
596            vec![]
597        }
598
599        fn differential_fuzzing_claims_blacklist() -> Option<Vec<TypeId>> {
600            None
601        }
602
603        fn differential_fuzzing_uniformise_put_config(trace: Trace<Self>) -> Trace<Self> {
604            trace
605        }
606
607        fn differential_fuzzing_filter_diff(_diff: &crate::differential::TraceDifference) -> bool {
608            true
609        }
610    }
611
612    #[derive(Default, Clone, Debug, Hash, Serialize, Deserialize)]
613    pub struct TestPUTConfig;
614
615    impl ProtocolDescriptorConfig for TestPUTConfig {
616        fn is_reusable_with(&self, _other: &Self) -> bool {
617            false
618        }
619    }
620
621    impl fmt::Display for TestProtocolTypes {
622        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623            write!(f, "")
624        }
625    }
626
627    #[derive(Debug, PartialEq, Eq)]
628    pub struct TestProtocolBehavior;
629
630    impl ProtocolBehavior for TestProtocolBehavior {
631        type Claim = TestClaim;
632        type OpaqueProtocolMessage = TestOpaqueMessage;
633        type OpaqueProtocolMessageFlight = TestOpaqueMessageFlight;
634        type ProtocolMessage = TestMessage;
635        type ProtocolMessageFlight = TestMessageFlight;
636        type ProtocolTypes = TestProtocolTypes;
637        type SecurityViolationPolicy = TestSecurityViolationPolicy;
638
639        fn try_read_bytes(
640            _bitstring: &[u8],
641            _ty: TypeId,
642        ) -> Result<Box<dyn EvaluatedTerm<Self::ProtocolTypes>>, Error> {
643            Err(Error::Codec("try_read_bytes not implemented".to_owned()))
644        }
645    }
646
647    pub struct TestFactory;
648
649    impl Factory<TestProtocolBehavior> for TestFactory {
650        fn create(
651            &self,
652            _agent_descriptor: &AgentDescriptor<TestPUTConfig>,
653            _claims: &GlobalClaimList<<TestProtocolBehavior as ProtocolBehavior>::Claim>,
654            _options: &PutOptions,
655        ) -> Result<Box<dyn Put<TestProtocolBehavior>>, Error> {
656            panic!("Not implemented for test stub");
657        }
658
659        fn name(&self) -> String {
660            String::from("TESTSTUB_RUST_PUT")
661        }
662
663        fn versions(&self) -> Vec<(String, String)> {
664            vec![(
665                "harness".to_string(),
666                format!("{} {}", self.name(), puffin::full_version()),
667            )]
668        }
669
670        fn supports(&self, _capability: &str) -> bool {
671            false
672        }
673
674        fn clone_factory(&self) -> Box<dyn Factory<TestProtocolBehavior>> {
675            Box::new(TestFactory {})
676        }
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use super::test_signature::*;
683    use crate::agent::AgentName;
684    use crate::algebra::atoms::Variable;
685    use crate::algebra::dynamic_function::{DescribableFunction, TypeShape};
686    use crate::algebra::signature::Signature;
687    use crate::algebra::term::TermType;
688    use crate::algebra::{AnyMatcher, DYTerm, Term};
689    use crate::put::{PutDescriptor, PutOptions};
690    use crate::put_registry::{Factory, PutRegistry};
691    use crate::term;
692    use crate::trace::{Source, Spawner, TraceContext};
693
694    #[allow(dead_code)]
695    fn test_compilation() {
696        // reminds me of Lisp, lol
697        let client = AgentName::first();
698        let _test_nested_with_variable: TestTerm = term! {
699           fn_client_hello(
700                (fn_client_hello(
701                    fn_protocol_version12,
702                    fn_new_random,
703                    (fn_client_hello(fn_protocol_version12,
704                        fn_new_random,
705                        fn_new_random,
706                        ((client,0)/ProtocolVersion)
707                    ))
708                )),
709                fn_new_random
710            )
711        };
712
713        let _set_simple_function2: TestTerm = term! {
714           fn_client_hello((fn_protocol_version12()), fn_new_random, fn_new_random)
715        };
716
717        let _test_simple_function2: TestTerm = term! {
718           fn_new_random(((client,0)))
719        };
720        let _test_simple_function1: TestTerm = term! {
721           fn_protocol_version12
722        };
723        let _test_simple_function: TestTerm = term! {
724           fn_new_random(((client,0)/ProtocolVersion))
725        };
726        let _test_variable: TestTerm = term! {
727            (client,0)/ProtocolVersion
728        };
729        let _set_nested_function: TestTerm = term! {
730           fn_client_extensions_append(
731                (fn_client_extensions_append(
732                    fn_client_extensions_new,
733                    (fn_support_group_extension(fn_named_group_secp384r1))
734                )),
735                (fn_support_group_extension(fn_named_group_secp384r1))
736            )
737        };
738    }
739
740    #[test_log::test]
741    fn example() {
742        let hmac256_new_key = Signature::new_function(&fn_hmac256_new_key);
743        let hmac256 = Signature::new_function(&fn_hmac256);
744        let _client_hello = Signature::new_function(&fn_client_hello);
745
746        let data = "hello".as_bytes().to_vec();
747
748        // log::debug!("TypeId of vec array {:?}", data.type_id());
749
750        let variable: Variable<TestProtocolTypes> = Signature::new_var(
751            TypeShape::of::<Vec<u8>>(),
752            Some(Source::Agent(AgentName::first())),
753            None,
754            0,
755        );
756
757        let generated_term = Term::from(DYTerm::Application(
758            hmac256,
759            vec![
760                Term::from(DYTerm::Application(hmac256_new_key, vec![])),
761                Term::from(DYTerm::Variable(variable)),
762            ],
763        ));
764
765        log::debug!("Generated term: {}", generated_term);
766
767        fn dummy_factory() -> Box<dyn Factory<TestProtocolBehavior>> {
768            Box::new(TestFactory)
769        }
770
771        let registry = PutRegistry::<TestProtocolBehavior>::new(
772            [("teststub", dummy_factory())],
773            PutDescriptor::new("teststub", PutOptions::empty()),
774        );
775
776        let spawner = Spawner::new(registry);
777        let mut context = TraceContext::new(spawner);
778        context.knowledge_store.add_raw_knowledge(
779            data,
780            None,
781            Source::Agent(AgentName::first()),
782            None,
783        );
784
785        log::trace!("New knowledge: {:?}", context.knowledge_store);
786
787        let _string = generated_term
788            .evaluate_dy(&context)
789            .as_ref()
790            .unwrap()
791            .as_any()
792            .downcast_ref::<Vec<u8>>()
793            .unwrap();
794        // log::debug!("{:?}", string);
795    }
796
797    #[test_log::test]
798    fn playground() {
799        let _var_data = fn_new_session_id();
800
801        //println!("vec {:?}", TypeId::of::<Vec<u8>>());
802        //println!("vec {:?}", TypeId::of::<Vec<u16>>());
803
804        ////println!("{:?}", var_data.type_id());
805
806        let func = Signature::new_function(&example_op_c);
807        let dynamic_fn = func.dynamic_fn();
808        let _string = dynamic_fn(&vec![Box::new(1u8)])
809            .unwrap()
810            .as_any()
811            .downcast_ref::<u16>()
812            .unwrap();
813        //println!("{:?}", string);
814        let _string = Signature::new_function(&example_op_c).shape();
815        //println!("{}", string);
816
817        let constructed_term = Term::<TestProtocolTypes>::from(DYTerm::Application(
818            Signature::new_function(&example_op_c),
819            vec![
820                Term::from(DYTerm::Application(
821                    Signature::new_function(&example_op_c),
822                    vec![
823                        Term::from(DYTerm::Application(
824                            Signature::new_function(&example_op_c),
825                            vec![
826                                Term::from(DYTerm::Application(
827                                    Signature::new_function(&example_op_c),
828                                    vec![],
829                                )),
830                                Term::from(DYTerm::Variable(Signature::new_var_with_type::<
831                                    SessionID,
832                                    AnyMatcher,
833                                >(
834                                    Some(Source::Agent(AgentName::first())),
835                                    None,
836                                    0,
837                                ))),
838                            ],
839                        )),
840                        Term::from(DYTerm::Variable(Signature::new_var_with_type::<
841                            SessionID,
842                            AnyMatcher,
843                        >(
844                            Some(Source::Agent(AgentName::first())),
845                            None,
846                            0,
847                        ))),
848                    ],
849                )),
850                Term::from(DYTerm::Application(
851                    Signature::new_function(&example_op_c),
852                    vec![
853                        Term::from(DYTerm::Application(
854                            Signature::new_function(&example_op_c),
855                            vec![
856                                Term::from(DYTerm::Variable(Signature::new_var_with_type::<
857                                    SessionID,
858                                    _,
859                                >(
860                                    Some(Source::Agent(AgentName::first())),
861                                    None,
862                                    0,
863                                ))),
864                                Term::from(DYTerm::Application(
865                                    Signature::new_function(&example_op_c),
866                                    vec![],
867                                )),
868                            ],
869                        )),
870                        Term::from(DYTerm::Variable(
871                            Signature::new_var_with_type::<SessionID, _>(
872                                Some(Source::Agent(AgentName::first())),
873                                None,
874                                0,
875                            ),
876                        )),
877                    ],
878                )),
879            ],
880        ));
881
882        //println!("{}", constructed_term);
883        let _graph = constructed_term.dot_subgraph(true, 0, "test");
884        //println!("{}", graph);
885    }
886
887    /// The `term!` macro accepts nested applications both with wrapping parentheses (legacy) and
888    /// without, and both spellings produce structurally equal terms.
889    #[test_log::test]
890    fn term_macro_optional_parentheses() {
891        let with_parens: TestTerm = term! {
892            fn_client_extensions_append(
893                (fn_client_extensions_append(
894                    fn_client_extensions_new,
895                    (fn_support_group_extension(fn_named_group_secp384r1))
896                )),
897                (fn_support_group_extension(fn_named_group_secp384r1))
898            )
899        };
900        let without_parens: TestTerm = term! {
901            fn_client_extensions_append(
902                fn_client_extensions_append(
903                    fn_client_extensions_new,
904                    fn_support_group_extension(fn_named_group_secp384r1)
905                ),
906                fn_support_group_extension(fn_named_group_secp384r1)
907            )
908        };
909        // Legacy and new spelling can also be freely mixed.
910        let mixed: TestTerm = term! {
911            fn_client_extensions_append(
912                (fn_client_extensions_append(
913                    fn_client_extensions_new,
914                    fn_support_group_extension(fn_named_group_secp384r1)
915                )),
916                fn_support_group_extension(fn_named_group_secp384r1)
917            )
918        };
919
920        assert_eq!(with_parens, without_parens);
921        assert_eq!(with_parens, mixed);
922        assert_eq!(with_parens.size(), without_parens.size());
923    }
924
925    /// Nested applications without wrapping parentheses still work next to variable and constant
926    /// arguments (variables keep their parentheses), and empty argument lists are accepted.
927    #[test_log::test]
928    fn term_macro_mixed_argument_kinds() {
929        let client = AgentName::first();
930        let term: TestTerm = term! {
931            fn_client_hello(
932                fn_protocol_version12(),
933                ((client, 0) / Random),
934                fn_new_session_id,
935                fn_append_cipher_suite(fn_new_cipher_suites(), fn_cipher_suite12),
936                fn_compressions,
937                fn_client_extensions_append(
938                    fn_client_extensions_new,
939                    fn_support_group_extension(fn_named_group_secp384r1)
940                )
941            )
942        };
943
944        // fn_client_hello has 6 arguments, one of which is a variable.
945        assert_eq!(term.get(&[0]).unwrap().name(), fn_protocol_version12.name());
946        assert!(term.has_variable());
947    }
948}