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

pub use self::options::options;

use self::{error::AutodocsError, options::Options};
use crate::custom_types::CustomTypesMetadata;
use crate::doc_item::DocItem;
use crate::function::FunctionMetadata;
use serde::{Deserialize, Serialize};

/// Rhai module documentation in markdown format.
#[derive(Debug)]
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>,
    /// Module documentation as raw text.
    pub documentation: String,
    /// Documentation items found in the module.
    pub items: Vec<DocItem>,
}

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

/// 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);
    // Format the module doc comments to make them
    // readable markdown.
    let documentation = metadata
        .doc
        .clone()
        .map(|dc| DocItem::remove_test_code(&DocItem::fmt_doc_comments(dc)))
        .unwrap_or_default();

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

    let mut items = vec![];

    if let Some(types) = &metadata.custom_types {
        for ty in types {
            items.push(DocItem::new_custom_type(ty.clone(), &namespace, options)?);
        }
    }

    if let Some(functions) = &metadata.functions {
        for (name, polymorphisms) in group_functions(functions) {
            if let Ok(doc_item) =
                DocItem::new_function(&polymorphisms[..], &name, &namespace, options)
            {
                items.push(doc_item);
            }
        }
    }

    // Remove ignored documentation.
    let items = items.into_iter().flatten().collect::<Vec<DocItem>>();

    md.items = options.items_order.order_items(items);

    // 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(
    functions: &[FunctionMetadata],
) -> std::collections::HashMap<String, Vec<FunctionMetadata>> {
    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| {
        // Remove getter/setter prefixes to group them and indexers.
        let name = metadata.generate_function_definition().name();

        match function_groups.get_mut(&name) {
            Some(polymorphisms) => polymorphisms.push(metadata.clone()),
            None => {
                function_groups.insert(name.to_string(), vec![metadata.clone()]);
            }
        };
    });

    function_groups
}

#[cfg(test)]
mod test {
    use crate::{generate_for_docusaurus, module::options::ItemsOrder};

    use super::*;
    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_items_with(ItemsOrder::ByIndex)
            .generate(&engine)
            .expect("failed to generate documentation");

        let docs = generate_for_docusaurus(&docs).unwrap();

        pretty_assertions::assert_eq!(
                docs.get("global")
                .unwrap(),
            "---\ntitle: global\nslug: /global\n---\n\nimport Tabs from '@theme/Tabs';\nimport TabItem from '@theme/TabItem';\n\n```Namespace: global```\n\n\n\n"
        );

        pretty_assertions::assert_eq!(
            docs.get("my_module").unwrap(),
            r#"---
title: my_module
slug: /my_module
---

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

```Namespace: global/my_module```

My own module.


## <code>fn</code> hello_world

```js
fn hello_world()
```

<Tabs>
    <TabItem value="Description" default>

        A function that prints to stdout.
    </TabItem>
</Tabs>

## <code>fn</code> add

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

<Tabs>
    <TabItem value="Description" default>

        A function that adds two integers together.
    </TabItem>
</Tabs>
"#
        );
    }
}