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
use std::fmt::{self, Display};

use crate::{ident::Ident, Docs, Type};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub struct Params {
    items: Vec<(Ident, Type)>,
}

impl<N> From<(N, Type)> for Params
where
    N: Into<Ident>,
{
    fn from(value: (N, Type)) -> Self {
        Self {
            items: vec![(value.0.into(), value.1)],
        }
    }
}

impl<N> FromIterator<(N, Type)> for Params
where
    N: Into<Ident>,
{
    fn from_iter<T: IntoIterator<Item = (N, Type)>>(iter: T) -> Self {
        Self {
            items: iter.into_iter().map(|(n, t)| (n.into(), t)).collect(),
        }
    }
}

impl Display for Params {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut peekable = self.items.iter().peekable();
        while let Some((name, type_)) = peekable.next() {
            write!(f, "{}: {}", name, type_)?;
            if peekable.peek().is_some() {
                write!(f, ", ")?;
            }
        }
        Ok(())
    }
}

impl Params {
    pub fn empty() -> Self {
        Self::default()
    }

    pub fn push(&mut self, name: impl Into<Ident>, ty: Type) {
        self.items.push((name.into(), ty));
    }

    pub fn item(&mut self, name: impl Into<Ident>, item: impl Into<Type>) {
        self.items.push((name.into(), item.into()));
    }

    pub fn items(&self) -> &Vec<(Ident, Type)> {
        &self.items
    }

    pub fn items_mut(&mut self) -> &mut Vec<(Ident, Type)> {
        &mut self.items
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum Results {
    Named(Params),
    Anon(Type),
}

impl Display for Results {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Results::Anon(type_) => type_.fmt(f)?,
            Results::Named(vals) => {
                if !vals.items.is_empty() {
                    write!(f, "(")?;
                    let mut peekable = vals.items.iter().peekable();
                    while let Some((name, type_)) = peekable.next() {
                        write!(f, "{}: {}", name, type_)?;
                        if peekable.peek().is_some() {
                            write!(f, ", ")?;
                        }
                    }
                    write!(f, ")")?;
                }
            }
        };
        Ok(())
    }
}

impl Default for Results {
    fn default() -> Self {
        Results::empty()
    }
}

impl From<Type> for Results {
    fn from(value: Type) -> Self {
        Results::Anon(value)
    }
}

impl<N> FromIterator<(N, Type)> for Results
where
    N: Into<Ident>,
{
    fn from_iter<T: IntoIterator<Item = (N, Type)>>(iter: T) -> Self {
        Results::Named(Params::from_iter(iter))
    }
}

impl Results {
    // For the common case of an empty results list.
    pub fn empty() -> Results {
        Results::Named(Params::empty())
    }

    pub fn anon(type_: Type) -> Results {
        Results::Anon(type_)
    }

    pub fn named(types: impl IntoIterator<Item = (impl Into<Ident>, Type)>) -> Results {
        Results::Named(
            types
                .into_iter()
                .map(|(name, ty)| (name.into(), ty))
                .collect(),
        )
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn len(&self) -> usize {
        match self {
            Results::Named(params) => params.items().len(),
            Results::Anon(_) => 1,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub struct StandaloneFunc {
    pub(crate) name: Ident,
    pub(crate) params: Params,
    pub(crate) results: Results,
    pub(crate) docs: Option<Docs>,
}

impl StandaloneFunc {
    pub fn new(name: impl Into<Ident>) -> Self {
        Self {
            name: name.into(),
            params: Params::empty(),
            results: Results::empty(),
            docs: None,
        }
    }

    pub fn set_name(&self) -> &Ident {
        &self.name
    }

    pub fn name(&self) -> &Ident {
        &self.name
    }

    pub fn name_mut(&mut self) -> &mut Ident {
        &mut self.name
    }

    pub fn set_params(&mut self, params: impl Into<Params>) {
        self.params = params.into();
    }

    pub fn params(&self) -> &Params {
        &self.params
    }

    pub fn params_mut(&mut self) -> &mut Params {
        &mut self.params
    }

    pub fn results(&self) -> &Results {
        &self.results
    }

    pub fn set_results(&mut self, results: impl Into<Results>) {
        self.results = results.into();
    }

    pub fn results_mut(&mut self) -> &mut Results {
        &mut self.results
    }

    pub fn set_docs(&mut self, docs: Option<impl Into<Docs>>) {
        self.docs = docs.map(|d| d.into());
    }

    pub fn docs(&self) -> &Option<Docs> {
        &self.docs
    }
}

#[cfg(test)]
mod test {
    use crate::Results;

    #[test]
    fn is_empty() {
        let res = Results::empty();
        assert!(res.is_empty());
    }
}