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
//! # **The C Code Generator for Rust.**
//!
//! C-Emit provides a polished Builder API for generating C Code.
//!
//! ## Example
//!
//! ```rust
//! use c_emit::{Code, CArg};
//!
//! fn main() {
//!     let mut code = Code::new();
//!
//!     code.include("stdio.h");
//!     code.call_func_with_args("printf", vec![CArg::String("Hello, world!".to_string())]);
//!
//!     assert_eq!(code.to_string(), r#"
//! #include<stdio.h>
//! int main() {
//! printf("Hello, world!",);
//! return 0;
//! }
//! "#.trim_start().to_string());
//! }
//! ```

#![deny(missing_docs)]

use std::fmt::{Display, Formatter};

/// # The Code Struct.
///
/// ## Example
///
/// ```rust
/// use c_emit::Code;
///
/// fn main() {
///     let mut code = Code::new();
///
///     code.exit(1);
///
///     assert_eq!(code.to_string(), r#"
/// int main() {
/// return 1;
/// }
/// "#.trim_start().to_string());
/// }
/// ```
pub struct Code {
    code: String,
    requires: Vec<String>,
    exit: i32
}

/// # The C Argument.
pub enum CArg {
    /// The String argument.
    String(String)
}

impl Code {
    /// # Create a new C Code object.
    ///
    /// ## Example
    /// ```rust
    /// use c_emit::Code;
    ///
    /// fn main() {
    ///     let code = Code::new();
    ///
    ///     assert_eq!(code.to_string(), r#"
    /// int main() {
    /// return 0;
    /// }
    /// "#.trim_start().to_string());
    /// }
    /// ```
    pub fn new() -> Self {
        Self {
            code: String::new(),
            requires: vec![],
            exit: 0,
        }
    }

    /// # Add the exit code to the main function.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use c_emit::Code;
    ///
    /// fn main() {
    ///     let mut code = Code::new();
    ///
    ///     code.exit(1);
    ///
    ///     assert_eq!(code.to_string(), r#"
    /// int main() {
    /// return 1;
    /// }
    /// "#.trim_start().to_string());
    /// }
    /// ```
    pub fn exit(&mut self, code: i32) {
        self.exit = code;
    }

    /// # #include < any file into the C Code. >
    ///
    /// ## Example
    ///
    /// ```rust
    /// use c_emit::Code;
    ///
    /// fn main() {
    ///     let mut code = Code::new();
    ///
    ///     code.include("stdio.h");
    ///
    ///     assert_eq!(code.to_string(), r#"
    /// #include<stdio.h>
    /// int main() {
    /// return 0;
    /// }
    /// "#.trim_start().to_string());
    /// }
    /// ```
    pub fn include(&mut self, file: &str) {
        self.requires.push(file.to_string());
    }

    /// # Call a function WITHOUT arguments.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use c_emit::Code;
    ///
    /// fn main() {
    ///     let mut code = Code::new();
    ///
    ///     code.call_func("printf");
    ///
    ///     assert_eq!(code.to_string(), r#"
    /// int main() {
    /// printf();
    /// return 0;
    /// }
    /// "#.trim_start().to_string());
    /// }
    /// ```
    pub fn call_func(&mut self, func: &str) {
        self.code.push_str(func);
        self.code.push_str("();\n")
    }

    /// # Call a function WITH arguments.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use c_emit::{Code, CArg};
    ///
    /// fn main() {
    ///     let mut code = Code::new();
    ///
    ///     code.call_func_with_args("printf", vec![CArg::String("Hello, world!".to_string())]);
    ///
    ///     assert_eq!(code.to_string(), r#"
    /// int main() {
    /// printf("Hello, world!",);
    /// return 0;
    /// }
    /// "#.trim_start().to_string());
    /// }
    /// ```
    pub fn call_func_with_args(&mut self, func: &str, args: Vec<CArg>) {
        self.code.push_str(func);
        self.code.push_str("(");

        for arg in args {
            match arg {
                CArg::String(s) => {
                    let s = s.replace("\r\n","\\r\\n");
                    let s = s.replace('\n',"\\n");
                    let s = s.replace('\t', "\\t");
                    let s = s.replace('"', "\\\"");

                    self.code.push('"');
                    self.code.push_str(s.as_str());
                    self.code.push('"');
                }
            }
            self.code.push(',');
        }

        self.code.push_str(");\n")
    }
}

impl Display for Code {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut require_string = String::new();

        for require in &self.requires {
            require_string.push_str("#include<");
            require_string.extend(require.chars());
            require_string.push_str(">\n");
        }

        writeln!(f, "{}int main() {{\n{}return {};\n}}", require_string, self.code, self.exit)
    }
}

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

    #[test]
    fn test_empty() {
        let code = Code::new();

        assert_eq!(code.to_string(), "int main() {\nreturn 0;\n}\n");
    }
    #[test]
    fn test_exit() {
        let mut code = Code::new();

        code.exit(1);

        assert_eq!(code.to_string(), "int main() {\nreturn 1;\n}\n");
    }
    #[test]
    fn test_include() {
        let mut code = Code::new();

        code.include("stdio.h");

        assert_eq!(code.to_string(), "#include<stdio.h>\nint main() {\nreturn 0;\n}\n");
    }
    #[test]
    fn test_func() {
        let mut code = Code::new();

        code.call_func("printf");

        assert_eq!(code.to_string(), "int main() {\nprintf();\nreturn 0;\n}\n");
    }
    #[test]
    fn test_func_with_args() {
        let mut code = Code::new();

        code.call_func_with_args("printf", vec![CArg::String("Hello World! \"How are you?\"\n \r\n \t".to_string()), CArg::String("Hi".to_string())]);


        assert_eq!(code.to_string(), "int main() {\nprintf(\"Hello World! \\\"How are you?\\\"\\n \\r\\n \\t\",\"Hi\",);\nreturn 0;\n}\n");
    }
}