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
pub mod error;
pub mod options;

use serde::{Deserialize, Serialize};

use crate::function::FunctionMetadata;
use crate::{fmt_doc_comments, remove_test_code};

use self::error::AutodocsError;
use self::options::Options;

pub use self::options::options;

#[derive(Debug)]
/// Rhai module documentation in markdown format.
pub struct ModuleDocumentation {
    /// Complete path to the module.
    pub namespace: String,
    /// Name of the module.
    pub name: String,
    /// Sub modules.
    pub sub_modules: Vec<ModuleDocumentation>,
    /// Raw text documentation in markdown.
    pub documentation: String,
}

/// Intermediatory representation of the documentation.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) struct ModuleMetadata {
    /// Optional documentation for the module.
    pub doc: Option<String>,
    /// Functions metadata, if any.
    pub functions: Option<Vec<FunctionMetadata>>,
    /// Sub-modules, if any, stored as raw json values.
    pub modules: Option<serde_json::Map<String, serde_json::Value>>,
}

impl ModuleMetadata {
    /// Format the module doc comments to make them
    /// readable markdown.
    pub fn fmt_doc_comments(&self) -> Option<String> {
        self.doc
            .clone()
            .map(|dc| remove_test_code(&fmt_doc_comments(dc)))
    }
}

/// Generate documentation based on an engine instance.
/// Make sure all the functions, operators, plugins, etc. are registered inside this instance.
///
/// # Result
/// * A vector of documented modules.
///
/// # Errors
/// * Failed to generate function metadata as json.
/// * Failed to parse module metadata.
pub fn generate_module_documentation(
    engine: &rhai::Engine,
    options: &Options,
) -> Result<ModuleDocumentation, AutodocsError> {
    let json_fns = engine
        .gen_fn_metadata_to_json(options.include_standard_packages)
        .map_err(|error| AutodocsError::Metadata(error.to_string()))?;

    let metadata = serde_json::from_str::<ModuleMetadata>(&json_fns)
        .map_err(|error| AutodocsError::Metadata(error.to_string()))?;

    generate_module_documentation_inner(options, None, "global", &metadata)
}

fn generate_module_documentation_inner(
    options: &Options,
    namespace: Option<String>,
    name: impl Into<String>,
    metadata: &ModuleMetadata,
) -> Result<ModuleDocumentation, AutodocsError> {
    let name = name.into();
    let namespace = namespace.map_or(name.clone(), |namespace| namespace);

    let documentation = match options.markdown_processor {
        options::MarkdownProcessor::MdBook => {
            format!(
                r#"# {}

```Namespace: {}```

{}"#,
                &name,
                &namespace,
                metadata
                    .fmt_doc_comments()
                    .map_or_else(String::default, |doc| format!("{doc}\n\n"))
            )
        }
        options::MarkdownProcessor::Docusaurus => {
            format!(
                r#"---
title: {}
slug: /{}
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

```Namespace: {}```

{}"#,
                &name,
                &namespace,
                &namespace,
                metadata
                    .fmt_doc_comments()
                    .map_or_else(String::default, |doc| format!("{doc}\n\n"))
            )
        }
    };

    let mut md = ModuleDocumentation {
        namespace: namespace.clone(),
        name,
        sub_modules: vec![],
        documentation,
    };

    if let Some(functions) = &metadata.functions {
        let fn_groups = group_functions(options, &namespace, functions)?;

        // Generate a clean documentation for each functions.
        // Functions that share the same name will keep only
        // one documentation, the others will be dropped.
        //
        // This means that:
        // ```rust
        // /// doc 1
        // fn my_func(a: int)`
        // ```
        // and
        // ```rust
        // /// doc 2
        // fn my_func(a: int, b: int)`
        // ```
        // will be written as the following:
        // ```rust
        // /// doc 1
        // fn my_func(a: int);
        // fn my_func(a: int, b: int);
        // ```
        for (name, polymorphisms) in fn_groups {
            if let Some(fn_doc) = generate_function_documentation(
                options,
                &name.replace("get$", "").replace("set$", ""),
                &polymorphisms[..],
            ) {
                md.documentation += &fn_doc;
            }
        }
    }

    // Generate documentation for each submodule. (if any)
    if let Some(sub_modules) = &metadata.modules {
        for (sub_module, value) in sub_modules {
            md.sub_modules.push(generate_module_documentation_inner(
                options,
                Some(format!("{}/{}", namespace, sub_module)),
                sub_module,
                &serde_json::from_value::<ModuleMetadata>(value.clone())
                    .map_err(|error| AutodocsError::Metadata(error.to_string()))?,
            )?);
        }
    }

    Ok(md)
}

pub(crate) fn group_functions<'meta>(
    options: &Options,
    namespace: &str,
    functions: &'meta [FunctionMetadata],
) -> Result<Vec<(String, Vec<&'meta FunctionMetadata>)>, AutodocsError> {
    let mut function_groups =
        std::collections::HashMap::<String, Vec<&FunctionMetadata>>::default();

    // Rhai function can be polymorphes, so we group them by name.
    functions.iter().for_each(|metadata| {
        match function_groups.get_mut(&metadata.name) {
            Some(polymorphisms) => polymorphisms.push(metadata),
            None => {
                function_groups.insert(metadata.name.clone(), vec![metadata]);
            }
        };
    });

    let function_groups = function_groups
        .into_iter()
        .map(|(name, polymorphisms)| (name, polymorphisms))
        .collect::<Vec<_>>();

    let fn_groups = options
        .functions_order
        .order_function_groups(namespace, function_groups)?;

    Ok(fn_groups)
}

/// Generate markdown/html documentation for a function.
/// TODO: Add other word processors.
fn generate_function_documentation(
    options: &Options,
    name: &str,
    polymorphisms: &[&FunctionMetadata],
) -> Option<String> {
    // Takes the first valid comments found for a function group.
    let metadata = polymorphisms
        .iter()
        .find(|metadata| metadata.doc_comments.is_some())?;
    let root_definition = metadata.generate_function_definition();
    // Anonymous functions are ignored.
    if !name.starts_with("anon$") {
        match options.markdown_processor {
            options::MarkdownProcessor::MdBook => {
                Some(format!(
                    r#"
<div markdown="span" style='box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); padding: 15px; border-radius: 5px;'>

<h2 class="func-name"> <code>{}</code> {} </h2>

```rust,ignore
{}
```
{}
</div>
</br>
"#,
                    // Add a specific prefix for the function type documented.
                    root_definition.type_to_str(),
                    root_definition.name(),
                    polymorphisms
                        .iter()
                        .map(|metadata| metadata.generate_function_definition().display())
                        .collect::<Vec<_>>()
                        .join("\n"),
                    &metadata
                        .fmt_doc_comments(&options.sections_format, &options.markdown_processor)
                        .unwrap_or_default()
                ))
            }
            options::MarkdownProcessor::Docusaurus => {
                Some(format!(
                    r#"## <code>{}</code> {}
```js
{}
```
{}
"#,
                    // Add a specific prefix for the function type documented.
                    root_definition.type_to_str(),
                    root_definition.name(),
                    polymorphisms
                        .iter()
                        .map(|metadata| metadata.generate_function_definition().display())
                        .collect::<Vec<_>>()
                        .join("\n"),
                    &metadata
                        .fmt_doc_comments(&options.sections_format, &options.markdown_processor)
                        .unwrap_or_default()
                ))
            }
        }
    } else {
        None
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::module::options::FunctionOrder;
    use rhai::plugin::*;

    /// My own module.
    #[export_module]
    mod my_module {
        /// A function that prints to stdout.
        ///
        /// # rhai-autodocs:index:1
        #[rhai_fn(global)]
        pub fn hello_world() {
            println!("Hello, World!");
        }

        /// A function that adds two integers together.
        ///
        /// # rhai-autodocs:index:2
        #[rhai_fn(global)]
        pub fn add(a: rhai::INT, b: rhai::INT) -> rhai::INT {
            a + b
        }
    }

    #[test]
    fn test_order_by_index() {
        let mut engine = rhai::Engine::new();

        engine.register_static_module("my_module", rhai::exported_module!(my_module).into());

        // register custom functions and types ...
        let docs = options::options()
            .include_standard_packages(false)
            .order_functions_with(FunctionOrder::ByIndex)
            .for_markdown_processor(options::MarkdownProcessor::MdBook)
            .generate(&engine)
            .expect("failed to generate documentation");

        assert_eq!(docs.name, "global");
        assert_eq!(
            docs.documentation,
            "# global\n\n```Namespace: global```\n\n"
        );

        let my_module = &docs.sub_modules[0];

        assert_eq!(my_module.name, "my_module");
        pretty_assertions::assert_eq!(
            my_module.documentation,
            r#"# my_module

```Namespace: global/my_module```

My own module.


<div markdown="span" style='box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); padding: 15px; border-radius: 5px;'>

<h2 class="func-name"> <code>fn</code> hello_world </h2>

```rust,ignore
fn hello_world()
```

<details>
<summary markdown="span"> details </summary>

A function that prints to stdout.
</details>

</div>
</br>

<div markdown="span" style='box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); padding: 15px; border-radius: 5px;'>

<h2 class="func-name"> <code>fn</code> add </h2>

```rust,ignore
fn add(a: int, b: int) -> int
```

<details>
<summary markdown="span"> details </summary>

A function that adds two integers together.
</details>

</div>
</br>
"#
        );
    }
}