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
//! Functions for generating docs for our stdlib functions.

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::std::Primitive;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct StdLibFnData {
    /// The name of the function.
    pub name: String,
    /// The summary of the function.
    pub summary: String,
    /// The description of the function.
    pub description: String,
    /// The tags of the function.
    pub tags: Vec<String>,
    /// The args of the function.
    pub args: Vec<StdLibFnArg>,
    /// The return value of the function.
    pub return_value: StdLibFnArg,
    /// If the function is unpublished.
    pub unpublished: bool,
    /// If the function is deprecated.
    pub deprecated: bool,
}

/// This struct defines a single argument to a stdlib function.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct StdLibFnArg {
    /// The name of the argument.
    pub name: String,
    /// The type of the argument.
    pub type_: String,
    /// The schema of the argument.
    pub schema: schemars::schema::Schema,
    /// If the argument is required.
    pub required: bool,
}

impl StdLibFnArg {
    #[allow(dead_code)]
    pub fn get_type_string(&self) -> Result<(String, bool)> {
        get_type_string_from_schema(&self.schema)
    }

    #[allow(dead_code)]
    pub fn get_autocomplete_string(&self) -> Result<String> {
        get_autocomplete_string_from_schema(&self.schema)
    }

    #[allow(dead_code)]
    pub fn description(&self) -> Option<String> {
        get_description_string_from_schema(&self.schema)
    }
}

/// This trait defines functions called upon stdlib functions to generate
/// documentation for them.
pub trait StdLibFn {
    /// The name of the function.
    fn name(&self) -> String;

    /// The summary of the function.
    fn summary(&self) -> String;

    /// The description of the function.
    fn description(&self) -> String;

    /// The tags of the function.
    fn tags(&self) -> Vec<String>;

    /// The args of the function.
    fn args(&self) -> Vec<StdLibFnArg>;

    /// The return value of the function.
    fn return_value(&self) -> StdLibFnArg;

    /// If the function is unpublished.
    fn unpublished(&self) -> bool;

    /// If the function is deprecated.
    fn deprecated(&self) -> bool;

    /// The function itself.
    fn std_lib_fn(&self) -> crate::std::StdFn;

    /// Return a JSON struct representing the function.
    fn to_json(&self) -> Result<StdLibFnData> {
        Ok(StdLibFnData {
            name: self.name(),
            summary: self.summary(),
            description: self.description(),
            tags: self.tags(),
            args: self.args(),
            return_value: self.return_value(),
            unpublished: self.unpublished(),
            deprecated: self.deprecated(),
        })
    }

    fn fn_signature(&self) -> String {
        let mut signature = String::new();
        signature.push_str(&format!("{}(", self.name()));
        for (i, arg) in self.args().iter().enumerate() {
            if i > 0 {
                signature.push_str(", ");
            }
            signature.push_str(&format!("{}: {}", arg.name, arg.type_));
        }
        signature.push_str(") -> ");
        signature.push_str(&self.return_value().type_);

        signature
    }
}

pub fn get_description_string_from_schema(schema: &schemars::schema::Schema) -> Option<String> {
    if let schemars::schema::Schema::Object(o) = schema {
        if let Some(metadata) = &o.metadata {
            if let Some(description) = &metadata.description {
                return Some(description.to_string());
            }
        }
    }

    None
}

pub fn get_type_string_from_schema(schema: &schemars::schema::Schema) -> Result<(String, bool)> {
    match schema {
        schemars::schema::Schema::Object(o) => {
            if let Some(format) = &o.format {
                if format == "uuid" {
                    return Ok((Primitive::Uuid.to_string(), false));
                } else if format == "double" || format == "uint" {
                    return Ok((Primitive::Number.to_string(), false));
                } else {
                    anyhow::bail!("unknown format: {}", format);
                }
            }

            if let Some(obj_val) = &o.object {
                let mut fn_docs = String::new();
                fn_docs.push_str("{\n");
                // Let's print out the object's properties.
                for (prop_name, prop) in obj_val.properties.iter() {
                    if prop_name.starts_with('_') {
                        continue;
                    }

                    if let Some(description) = get_description_string_from_schema(prop) {
                        fn_docs.push_str(&format!("\t// {}\n", description));
                    }
                    fn_docs.push_str(&format!(
                        "\t\"{}\": {},\n",
                        prop_name,
                        get_type_string_from_schema(prop)?.0,
                    ));
                }

                fn_docs.push('}');

                return Ok((fn_docs, true));
            }

            if let Some(array_val) = &o.array {
                if let Some(schemars::schema::SingleOrVec::Single(items)) = &array_val.items {
                    // Let's print out the object's properties.
                    return Ok((format!("[{}]", get_type_string_from_schema(items)?.0), false));
                } else if let Some(items) = &array_val.contains {
                    return Ok((format!("[{}]", get_type_string_from_schema(items)?.0), false));
                }
            }

            if let Some(subschemas) = &o.subschemas {
                let mut fn_docs = String::new();
                if let Some(items) = &subschemas.one_of {
                    for (i, item) in items.iter().enumerate() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_type_string_from_schema(item)?.0.to_string());
                        if i < items.len() - 1 {
                            fn_docs.push_str(" |\n");
                        }
                    }
                } else if let Some(items) = &subschemas.any_of {
                    for (i, item) in items.iter().enumerate() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_type_string_from_schema(item)?.0.to_string());
                        if i < items.len() - 1 {
                            fn_docs.push_str(" |\n");
                        }
                    }
                } else {
                    anyhow::bail!("unknown subschemas: {:#?}", subschemas);
                }

                return Ok((fn_docs, true));
            }

            if let Some(schemars::schema::SingleOrVec::Single(_string)) = &o.instance_type {
                return Ok((Primitive::String.to_string(), false));
            }

            anyhow::bail!("unknown type: {:#?}", o)
        }
        schemars::schema::Schema::Bool(_) => Ok((Primitive::Bool.to_string(), false)),
    }
}

pub fn get_autocomplete_string_from_schema(schema: &schemars::schema::Schema) -> Result<String> {
    match schema {
        schemars::schema::Schema::Object(o) => {
            if let Some(format) = &o.format {
                if format == "uuid" {
                    return Ok(Primitive::Uuid.to_string());
                } else if format == "double" || format == "uint" {
                    return Ok(Primitive::Number.to_string());
                } else {
                    anyhow::bail!("unknown format: {}", format);
                }
            }

            if let Some(obj_val) = &o.object {
                let mut fn_docs = String::new();
                fn_docs.push_str("{\n");
                // Let's print out the object's properties.
                for (prop_name, prop) in obj_val.properties.iter() {
                    if prop_name.starts_with('_') {
                        continue;
                    }

                    if let Some(description) = get_description_string_from_schema(prop) {
                        fn_docs.push_str(&format!("\t// {}\n", description));
                    }
                    fn_docs.push_str(&format!(
                        "\t\"{}\": {},\n",
                        prop_name,
                        get_autocomplete_string_from_schema(prop)?,
                    ));
                }

                fn_docs.push('}');

                return Ok(fn_docs);
            }

            if let Some(array_val) = &o.array {
                if let Some(schemars::schema::SingleOrVec::Single(items)) = &array_val.items {
                    // Let's print out the object's properties.
                    return Ok(format!("[{}]", get_autocomplete_string_from_schema(items)?));
                } else if let Some(items) = &array_val.contains {
                    return Ok(format!("[{}]", get_autocomplete_string_from_schema(items)?));
                }
            }

            if let Some(subschemas) = &o.subschemas {
                let mut fn_docs = String::new();
                if let Some(items) = &subschemas.one_of {
                    if let Some(item) = items.iter().next() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_autocomplete_string_from_schema(item)?);
                    }
                } else if let Some(items) = &subschemas.any_of {
                    if let Some(item) = items.iter().next() {
                        // Let's print out the object's properties.
                        fn_docs.push_str(&get_autocomplete_string_from_schema(item)?);
                    }
                } else {
                    anyhow::bail!("unknown subschemas: {:#?}", subschemas);
                }

                return Ok(fn_docs);
            }

            if let Some(schemars::schema::SingleOrVec::Single(_string)) = &o.instance_type {
                return Ok(Primitive::String.to_string());
            }

            anyhow::bail!("unknown type: {:#?}", o)
        }
        schemars::schema::Schema::Bool(_) => Ok(Primitive::Bool.to_string()),
    }
}