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
extern crate clap;
use clap::{Parser, ValueEnum};

use super::ast::{Node::*, *};

#[derive(Debug, Clone, PartialEq, Eq, ValueEnum)]
pub enum FunctionTagStyle {
    Dollar = 1,
    SelfClosing,
}

#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
pub struct Options {
    #[arg(short, long, default_value = "mt:")]
    prefix: String,
    #[arg(short, long, value_enum, default_value = "dollar")]
    function_tag_style: FunctionTagStyle,
}

/// Serialize AST to MTML document.
///
/// # Examples
///
/// ```
/// use mtml_parser::{parse, serialize};
///
/// let node = match parse("<body><mt:Entries><mt:EntryTitle /></mt:Entries></body>") {
///   Ok(node) => node,
///   Err(err) => panic!("{}", err),
/// };
/// serialize(node, None);
/// ```
pub fn serialize(node: Node, options: Option<&Options>) -> String {
    let mut s = String::new();
    let default_opts = Options {
        prefix: "mt:".to_string(),
        function_tag_style: FunctionTagStyle::Dollar,
    };
    let options = options.unwrap_or(&default_opts);

    match node {
        Root(RootNode { children }) => {
            for child in children {
                s.push_str(&serialize(child, Some(options)));
            }
        }
        Text(TextNode { value, .. }) => {
            s.push_str(value);
        }
        FunctionTag(FunctionTagNode {
            name, attributes, ..
        }) => {
            let pre_sign = if options.function_tag_style == FunctionTagStyle::Dollar {
                "$"
            } else {
                ""
            };
            let post_sign = if options.function_tag_style == FunctionTagStyle::Dollar {
                "$"
            } else {
                "/"
            };
            s.push_str(&format!("<{}{}{}", pre_sign, options.prefix, name));
            for attr in attributes {
                s.push_str(&format!(r#" {}="{}""#, attr.name, attr.values[0].value));
            }
            s.push_str(&format!("{}>", post_sign));
        }
        BlockTag(BlockTagNode {
            name,
            children,
            attributes,
            ..
        }) => {
            s.push_str(&format!("<{}{}", options.prefix, name));
            for attr in attributes {
                s.push_str(&format!(r#" {}="{}""#, attr.name, attr.values[0].value));
            }
            s.push_str(">");
            for child in children {
                s.push_str(&serialize(child, Some(options)));
            }
            s.push_str(&format!("</{}{}>", options.prefix, name));
        }
    }

    return s;
}

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

    const INPUT: &str = r#"
<html>
  <body>
    <mt:Entries    limit="10\"20">
      <mtEntryTitle encode_html="1"/>
    </mt:Entries>
  </body>
</html>"#;
    
    #[test]
    fn test_serialize() {
        let root = parse(INPUT).unwrap();
        let serialized = serialize(root, None);
        assert_eq!(
            serialized,
            r#"
<html>
  <body>
    <mt:Entries limit="10\"20">
      <$mt:EntryTitle encode_html="1"$>
    </mt:Entries>
  </body>
</html>"#
        )
    }
    
    #[test]
    fn test_serialize_self_closing() {
        let root = parse(INPUT).unwrap();
        let serialized = serialize(root, Some(&Options {
            prefix: "mt:".to_string(),
            function_tag_style: FunctionTagStyle::SelfClosing,
        }));
        assert_eq!(
            serialized,
            r#"
<html>
  <body>
    <mt:Entries limit="10\"20">
      <mt:EntryTitle encode_html="1"/>
    </mt:Entries>
  </body>
</html>"#
        )
    }
    
    #[test]
    fn test_serialize_prefix() {
        let root = parse(INPUT).unwrap();
        let serialized = serialize(root, Some(&Options {
            prefix: "MT".to_string(),
            function_tag_style: FunctionTagStyle::Dollar,
        }));
        assert_eq!(
            serialized,
            r#"
<html>
  <body>
    <MTEntries limit="10\"20">
      <$MTEntryTitle encode_html="1"$>
    </MTEntries>
  </body>
</html>"#
        )
    }
}