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
385
386
387
388
389
use crate::{
    custom_types,
    export::{ItemsOrder, Options, RHAI_ITEM_INDEX_PATTERN},
    function,
    module::Error,
};
use serde::ser::SerializeStruct;

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

impl serde::Serialize for Item {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Function {
                root_metadata,
                name,
                metadata,
                ..
            } => {
                let mut state = serializer.serialize_struct("item", 4)?;
                state.serialize_field(
                    "type",
                    root_metadata.generate_function_definition().type_to_str(),
                )?;
                state.serialize_field("heading_id", &self.heading_id())?;
                state.serialize_field("name", name)?;
                state.serialize_field(
                    "signatures",
                    metadata
                        .iter()
                        .map(|metadata| metadata.generate_function_definition().display())
                        .collect::<Vec<_>>()
                        .join("\n")
                        .as_str(),
                )?;
                state.serialize_field("sections", {
                    &Section::extract_sections(
                        &root_metadata
                            .doc_comments
                            .clone()
                            .unwrap_or_default()
                            .join("\n"),
                    )
                })?;
                state.end()
            }
            Self::CustomType { metadata, .. } => {
                let mut state = serializer.serialize_struct("item", 2)?;
                state.serialize_field("name", &metadata.display_name)?;
                state.serialize_field("heading_id", &self.heading_id())?;
                state.serialize_field(
                    "sections",
                    &Section::extract_sections(
                        &metadata.doc_comments.clone().unwrap_or_default().join("\n"),
                    ),
                )?;
                state.end()
            }
        }
    }
}

impl Item {
    pub(crate) fn new_function(
        metadata: &[function::Metadata],
        name: &str,
        options: &Options,
    ) -> Result<Option<Self>, Error> {
        // 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$") => {
                if matches!(options.items_order, ItemsOrder::ByIndex) {
                    Self::find_index(root.doc_comments.as_ref().unwrap_or(&vec![]))?
                } else {
                    Some(0)
                }
                .map_or_else(
                    || Ok(None),
                    |index| {
                        Ok(Some(Self::Function {
                            root_metadata: root.clone(),
                            metadata: metadata.to_vec(),
                            name: name.to_string(),
                            index,
                        }))
                    },
                )
            }
            _ => Ok(None),
        }
    }

    pub(crate) fn new_custom_type(
        metadata: custom_types::Metadata,
        options: &Options,
    ) -> Result<Option<Self>, Error> {
        if matches!(options.items_order, ItemsOrder::ByIndex) {
            Self::find_index(metadata.doc_comments.as_ref().unwrap_or(&vec![]))?
        } else {
            Some(0)
        }
        .map_or_else(
            || Ok(None),
            |index| Ok(Some(Self::CustomType { metadata, index })),
        )
    }

    /// Get the index of the item, extracted from the `# rhai-autodocs:index` directive.
    #[must_use]
    pub const fn index(&self) -> usize {
        match self {
            Self::CustomType { index, .. } | Self::Function { index, .. } => *index,
        }
    }

    /// Get the name of the item.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::CustomType { metadata, .. } => metadata.display_name.as_str(),
            Self::Function { name, .. } => name,
        }
    }

    /// Generate a heading id for mardown, using the type and name of the item.
    #[must_use]
    pub fn heading_id(&self) -> String {
        let prefix = match self {
            Self::Function { root_metadata, .. } => root_metadata
                .generate_function_definition()
                .type_to_str()
                .replace(['/', ' '], ""),
            Self::CustomType { .. } => "type".to_string(),
        };

        format!("{prefix}-{}", self.name())
    }

    /// Find the order index of the item by searching for the index pattern.
    pub(crate) fn find_index(doc_comments: &[String]) -> Result<Option<usize>, Error> {
        for line in doc_comments {
            if let Some((_, index)) = line.rsplit_once(RHAI_ITEM_INDEX_PATTERN) {
                return index
                    .parse::<usize>()
                    .map_err(Error::ParseOrderMetadata)
                    .map(Some);
            }
        }

        Ok(None)
    }

    /// Format the function doc comments to make them
    /// into readable markdown.
    pub(crate) fn format_comments(doc_comments: &[String]) -> 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);

        Self::remove_test_code(&remove_comments)
    }

    /// Remove crate specific comments, like `rhai-autodocs:index`.
    pub(crate) 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(crate) fn fmt_doc_comments(dc: &str) -> 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(crate) 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")
    }
}

#[derive(Default, Clone, serde::Serialize)]
struct Section {
    pub name: String,
    pub body: String,
}

impl Section {
    fn extract_sections(docs: &str) -> Vec<Self> {
        let mut sections = vec![];
        let mut current_name = "Description".to_string();
        let mut current_body = vec![];
        let mut in_code_block = false;

        // Start by extracting all sections from markdown comments.
        docs.lines().for_each(|line| {
            if line.split_once("```").is_some() {
                in_code_block = !in_code_block;
            }

            match line.split_once("# ") {
                Some((_prefix, name))
                    if !in_code_block && !line.contains(RHAI_ITEM_INDEX_PATTERN) =>
                {
                    sections.push(Self {
                        name: std::mem::take(&mut current_name),
                        body: Item::format_comments(&current_body[..]),
                    });

                    current_name = name.to_string();
                    current_body = vec![];
                }
                // Do not append lines of code that starts with the '#' token,
                // which are removed on rust docs automatically.
                Some(_) => {}
                // Append regular lines.
                None => current_body.push(format!("{line}\n")),
            }
        });

        if !current_body.is_empty() {
            sections.push(Self {
                name: std::mem::take(&mut current_name),
                body: Item::format_comments(&current_body[..]),
            });
        }

        sections
    }
}

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

    #[test]
    fn test_remove_test_code_simple() {
        pretty_assertions::assert_eq!(
            Item::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!(
            Item::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!(
            Item::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"
};
```"#,
        );
    }
}