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
use crate::operations::{helpers::handle_id_error, NormalForm, Normalize, Substitute};
use crate::{FunDef, Op, Term};
use scop::Defs;
use weresocool_error::Error;

pub fn insert_function_args(f: &Term, args: &[Term], defs: &mut Defs<Term>) -> Result<(), Error> {
    match f {
        Term::FunDef(fun) => {
            let FunDef { vars, .. } = fun;
            let new_scope = defs.create_uuid_scope();
            for (var, arg) in vars.iter().zip(args.iter()) {
                defs.insert(&new_scope, var.to_string(), arg.clone());
            }
        }
        _ => {
            println!("FunctionCall does not point to FunctionDef");
            return Err(Error::with_msg(
                "FunctionCall does not point to FunctionDef",
            ));
        }
    }

    Ok(())
}

impl Substitute<Term> for Op {
    fn substitute(
        &self,
        normal_form: &mut NormalForm,
        defs: &mut Defs<Term>,
    ) -> Result<Term, Error> {
        match self {
            Op::Id(id) => handle_id_error(id, defs),

            Op::WithLengthRatioOf {
                main,
                with_length_of,
            } => {
                let with_length_of = with_length_of.substitute(normal_form, defs)?;
                let main = match main.as_ref() {
                    Some(m) => m.substitute(normal_form, defs)?,
                    None => Term::Nf(NormalForm::init()),
                };

                Ok(Term::Op(Op::WithLengthRatioOf {
                    main: Some(Box::new(main)),
                    with_length_of: Box::new(with_length_of),
                }))
            }

            Op::Focus {
                name,
                main,
                op_to_apply,
            } => {
                let mut nf = NormalForm::init();
                let m = main.substitute(normal_form, defs)?;
                m.apply_to_normal_form(&mut nf, defs)?;
                let (named, rest) = nf.partition(name.to_string());

                let op_to_apply = op_to_apply.substitute(normal_form, defs)?;

                let mut nf = NormalForm::init();
                op_to_apply.apply_to_normal_form(&mut nf, defs)?;
                let named_applied = nf * named;

                let mut result = NormalForm::init();

                Op::Overlay {
                    operations: vec![Term::Nf(named_applied), Term::Nf(rest)],
                }
                .apply_to_normal_form(&mut result, defs)?;

                Ok(Term::Nf(result))
            }
            Op::FunctionCall { name, args } => Ok(Term::Op(Op::FunctionCall {
                name: name.to_string(),
                args: substitute_operations(args.to_vec(), normal_form, defs)?,
            })),
            Op::Sequence { operations } => Ok(Term::Op(Op::Sequence {
                operations: substitute_operations(operations.to_vec(), normal_form, defs)?,
            })),
            Op::Overlay { operations } => Ok(Term::Op(Op::Overlay {
                operations: substitute_operations(operations.to_vec(), normal_form, defs)?,
            })),
            Op::Compose { operations } => Ok(Term::Op(Op::Compose {
                operations: substitute_operations(operations.to_vec(), normal_form, defs)?,
            })),
            Op::ModulateBy { operations } => Ok(Term::Op(Op::ModulateBy {
                operations: substitute_operations(operations.to_vec(), normal_form, defs)?,
            })),
            Op::Lambda {
                term,
                input_name,
                scope,
            } => {
                if let Some(name) = input_name {
                    defs.insert(scope, name, Term::Nf(normal_form.to_owned()));
                }
                Ok(Term::Op(Op::Lambda {
                    input_name: input_name.to_owned(),
                    term: Box::new(term.substitute(normal_form, defs)?),
                    scope: scope.into(),
                }))
            }
            _ => Ok(Term::Op(self.clone())),
        }
    }
}

pub fn substitute_operations(
    operations: Vec<Term>,
    normal_form: &mut NormalForm,
    defs: &mut Defs<Term>,
) -> Result<Vec<Term>, Error> {
    let mut result = vec![];
    for term in operations {
        match term {
            Term::Nf(nf) => result.push(Term::Nf(nf)),
            Term::Op(op) => {
                let subbed = op.substitute(normal_form, defs)?;
                result.push(subbed)
            }
            Term::FunDef(_fun) => {
                return Err(Error::with_msg("Cannot get length_ratio of FunDef."))
            }
            Term::Lop(lop) => {
                let subbed = lop.substitute(normal_form, defs)?;
                result.push(subbed)
            }
            Term::Gen(gen) => {
                let subbed = gen.substitute(normal_form, defs)?;
                result.push(subbed)
            }
        }
    }

    Ok(result)
}