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
use super::error::Error;
use comrak::{arena_tree::NodeEdge, format_commonmark, nodes::NodeValue, parse_document, Arena};
use convert_case::{Case, Casing};
use proc_macro2::Ident;
use quote::format_ident;
use syn::{parse_quote, Type};

const RESERVED_NAMES: &[&str] = &["name", "operation", "builder"];

pub fn generate_result_type(r#type: Type) -> Type {
    parse_quote!(Result<#r#type, ::melior::Error>)
}

pub fn generate_iterator_type(r#type: Type) -> Type {
    parse_quote!(impl Iterator<Item = #r#type>)
}

pub fn sanitize_snake_case_identifier(name: &str) -> Result<Ident, Error> {
    sanitize_name(&name.to_case(Case::Snake))
}

fn sanitize_name(name: &str) -> Result<Ident, Error> {
    // Replace any "." with "_".
    let mut name = name.replace('.', "_");

    // Add "_" suffix to avoid conflicts with existing methods.
    if RESERVED_NAMES.contains(&name.as_str())
        || name
            .chars()
            .next()
            .ok_or_else(|| Error::InvalidIdentifier(name.clone()))?
            .is_numeric()
    {
        name = format!("_{}", name);
    }

    // Try to parse the string as an ident, and prefix the identifier
    // with "r#" if it is not a valid identifier.
    Ok(syn::parse_str::<Ident>(&name).unwrap_or(format_ident!("r#{}", name)))
}

pub fn sanitize_documentation(string: &str) -> Result<String, Error> {
    let arena = Arena::new();
    let node = parse_document(&arena, &unindent::unindent(string), &Default::default());

    for node in node.traverse() {
        let NodeEdge::Start(node) = node else {
            continue;
        };
        let mut ast = node.data.borrow_mut();
        let NodeValue::CodeBlock(block) = &mut ast.value else {
            continue;
        };

        if block.info.is_empty() {
            // Mark them not in Rust to prevent documentation tests.
            block.info = "text".into();
        }
    }

    let mut buffer = Vec::with_capacity(string.len());

    format_commonmark(node, &Default::default(), &mut buffer)?;

    Ok(String::from_utf8(buffer)?)
}

pub fn capitalize_string(string: &str) -> String {
    if string.is_empty() {
        "".into()
    } else {
        string[..1].to_uppercase() + &string[1..]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn sanitize_name_with_dot() {
        assert_eq!(
            sanitize_snake_case_identifier("foo.bar").unwrap(),
            "foo_bar"
        );
    }

    #[test]
    fn sanitize_name_with_dot_and_underscore() {
        assert_eq!(
            sanitize_snake_case_identifier("foo.bar_baz").unwrap(),
            "foo_bar_baz"
        );
    }

    #[test]
    fn sanitize_reserved_name() {
        assert_eq!(
            sanitize_snake_case_identifier("builder").unwrap(),
            "_builder"
        );
    }

    #[test]
    fn sanitize_code_block() {
        assert_eq!(
            &sanitize_documentation("```\nfoo\n```\n").unwrap(),
            "``` text\nfoo\n```\n"
        );
    }

    #[test]
    fn sanitize_code_blocks() {
        assert_eq!(
            &sanitize_documentation("```\nfoo\n```\n\n```\nbar\n```\n").unwrap(),
            "``` text\nfoo\n```\n\n``` text\nbar\n```\n"
        );
    }

    #[test]
    fn capitalize() {
        assert_eq!(&capitalize_string("foo"), "Foo");
    }
}