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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use crate::{
    custom_types::CustomTypesMetadata,
    function::FunctionMetadata,
    module::{
        error::AutodocsError,
        options::{Options, RHAI_ITEM_INDEX_PATTERN},
    },
    ItemsOrder, MarkdownProcessor,
};

/// Generic representation of documentation for a specific item. (a function, a custom type, etc.)
#[derive(Debug, Clone)]
pub enum DocItem {
    Function {
        metadata: Vec<FunctionMetadata>,
        name: String,
        index: usize,
        docs: String,
    },
    CustomType {
        metadata: CustomTypesMetadata,
        index: usize,
        docs: String,
    },
}

impl DocItem {
    pub fn new_function(
        metadata: &[FunctionMetadata],
        name: &str,
        namespace: &str,
        options: &Options,
    ) -> Result<Self, AutodocsError> {
        // Takes the first valid comments found for a function group.
        let root = metadata
            .iter()
            .find(|metadata| metadata.doc_comments.is_some());

        match root {
            // Anonymous functions are ignored.
            Some(root) if !name.starts_with("anon$") => {
                let root_definition = root.generate_function_definition();
                let index = if matches!(options.items_order, ItemsOrder::ByIndex) {
                    Self::find_index(
                        name,
                        namespace,
                        root.doc_comments.as_ref().unwrap_or(&vec![]),
                    )?
                } else {
                    0
                };
                let docs = match options.markdown_processor {
                    MarkdownProcessor::MdBook => {
                        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(),
                            metadata
                                .iter()
                                .map(|metadata| metadata.generate_function_definition().display())
                                .collect::<Vec<_>>()
                                .join("\n"),
                            Self::format_comments(
                                &root.name,
                                root.doc_comments.as_ref().unwrap_or(&vec![]),
                                options
                            )
                        )
                    }
                    MarkdownProcessor::Docusaurus => {
                        format!(
                            r#"## <code>{}</code> {}
```js
{}
```
{}
"#,
                            // Add a specific prefix for the function type documented.
                            root_definition.type_to_str(),
                            root_definition.name(),
                            metadata
                                .iter()
                                .map(|metadata| metadata.generate_function_definition().display())
                                .collect::<Vec<_>>()
                                .join("\n"),
                            Self::format_comments(
                                &root.name,
                                root.doc_comments.as_ref().unwrap_or(&vec![]),
                                options
                            )
                        )
                    }
                };

                Ok(Self::Function {
                    metadata: metadata.to_vec(),
                    name: name.to_string(),
                    index,
                    docs,
                })
            }
            _ => Err(AutodocsError::Metadata(format!(
                "No documentation was found for item {namespace}/{name}"
            ))),
        }
    }

    pub fn new_custom_type(
        metadata: CustomTypesMetadata,
        namespace: &str,
        options: &Options,
    ) -> Result<Self, AutodocsError> {
        let index = if matches!(options.items_order, ItemsOrder::ByIndex) {
            Self::find_index(
                &metadata.display_name,
                namespace,
                metadata.doc_comments.as_ref().unwrap_or(&vec![]),
            )?
        } else {
            0
        };
        let docs = match options.markdown_processor {
            MarkdownProcessor::MdBook => {
                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>type</code> {} </h2>

{}
</div>
</br>
"#,
                    // Add a specific prefix for the function type documented.
                    metadata.display_name,
                    Self::format_comments(
                        metadata.display_name.as_str(),
                        metadata.doc_comments.as_ref().unwrap_or(&vec![]),
                        options
                    )
                )
            }
            MarkdownProcessor::Docusaurus => {
                format!(
                    r#"## <code>type</code> {}
{}
"#,
                    // Add a specific prefix for the function type documented.
                    metadata.display_name,
                    Self::format_comments(
                        metadata.display_name.as_str(),
                        metadata.doc_comments.as_ref().unwrap_or(&vec![]),
                        options
                    )
                )
            }
        };

        Ok(Self::CustomType {
            metadata,
            index,
            docs,
        })
    }

    pub fn index(&self) -> usize {
        match self {
            DocItem::CustomType { index, .. } | DocItem::Function { index, .. } => *index,
        }
    }

    pub fn name(&self) -> &str {
        match self {
            DocItem::CustomType { metadata, .. } => metadata.display_name.as_str(),
            DocItem::Function { name, .. } => name,
        }
    }

    pub fn docs(&self) -> &str {
        match self {
            DocItem::CustomType { docs, .. } | DocItem::Function { docs, .. } => docs,
        }
    }

    /// Find the order index of the item by searching for the index pattern.
    pub fn find_index(
        name: &str,
        namespace: &str,
        doc_comments: &[String],
    ) -> Result<usize, AutodocsError> {
        if let Some((_, index)) = doc_comments
            .iter()
            .find_map(|line| line.rsplit_once(RHAI_ITEM_INDEX_PATTERN))
        {
            index.parse::<usize>().map_err(|err| {
                AutodocsError::PreProcessing(format!("failed to parsed order metadata: {err}"))
            })
        } else {
            Err(AutodocsError::PreProcessing(format!(
                "missing order metadata in item {}/{}",
                namespace, name
            )))
        }
    }

    /// Format the function doc comments to make them
    /// into readable markdown.
    pub fn format_comments(name: &str, doc_comments: &[String], options: &Options) -> String {
        let doc_comments = doc_comments.to_vec();
        let removed_extra_tokens = Self::remove_extra_tokens(doc_comments).join("\n");
        let remove_comments = Self::fmt_doc_comments(removed_extra_tokens);
        let remove_test_code = Self::remove_test_code(&remove_comments);

        options
            .sections_format
            .fmt_sections(name, &options.markdown_processor, remove_test_code)
    }

    /// Remove crate specific comments, like `rhai-autodocs:index`.
    pub fn remove_extra_tokens(dc: Vec<String>) -> Vec<String> {
        dc.into_iter()
            .map(|s| {
                s.lines()
                    .filter(|l| !l.contains(RHAI_ITEM_INDEX_PATTERN))
                    .collect::<Vec<_>>()
                    .join("\n")
            })
            .collect::<Vec<_>>()
    }

    /// Remove doc comments identifiers.
    pub fn fmt_doc_comments(dc: String) -> String {
        dc.replace("/// ", "")
            .replace("///", "")
            .replace("/**", "")
            .replace("**/", "")
            .replace("**/", "")
    }

    /// NOTE: mdbook handles this automatically, but other
    ///       markdown processors might not.
    /// Remove lines of code that starts with the '#' token,
    /// which are removed on rust docs automatically.
    pub fn remove_test_code(doc_comments: &str) -> String {
        let mut formatted = vec![];
        let mut in_code_block = false;
        for line in doc_comments.lines() {
            if line.starts_with("```") {
                in_code_block = !in_code_block;
                formatted.push(line);
                continue;
            }

            if !(in_code_block && line.starts_with("# ")) {
                formatted.push(line);
            }
        }

        formatted.join("\n")
    }
}

#[cfg(test)]
pub mod test {
    use super::*;

    #[test]
    fn test_remove_test_code_simple() {
        pretty_assertions::assert_eq!(
            DocItem::remove_test_code(
                r#"
# Not removed.
```
fn my_func(a: int) -> () {}
do stuff ...
# Please hide this.
do something else ...
# Also this.
```
# Not removed either.
"#,
            ),
            r#"
# Not removed.
```
fn my_func(a: int) -> () {}
do stuff ...
do something else ...
```
# Not removed either."#,
        )
    }

    #[test]
    fn test_remove_test_code_multiple_blocks() {
        pretty_assertions::assert_eq!(
            DocItem::remove_test_code(
                r#"
```ignore
block 1
# Please hide this.
```

# A title

```
block 2
# Please hide this.
john
doe
# To hide.
```
"#,
            ),
            r#"
```ignore
block 1
```

# A title

```
block 2
john
doe
```"#,
        )
    }

    #[test]
    fn test_remove_test_code_with_rhai_map() {
        pretty_assertions::assert_eq!(
            DocItem::remove_test_code(
                r#"
```rhai
#{
    "a": 1,
    "b": 2,
    "c": 3,
};
# Please hide this.
```

# A title

```
# Please hide this.
let map = #{
    "hello": "world"
# To hide.
};
# To hide.
```
"#,
            ),
            r#"
```rhai
#{
    "a": 1,
    "b": 2,
    "c": 3,
};
```

# A title

```
let map = #{
    "hello": "world"
};
```"#,
        )
    }
}