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
//! # **The C Code Generator for Rust.**
//!
//! C-Emit provides a polished Builder API for generating C Code.
//!
//! ## Example
//!
//! ```rust
//! use c_emit::{Code, CArg};
//!
//! let mut code = Code::new();
//!
//! code.include("stdio.h");
//! code.call_func_with_args("printf", vec![CArg::String("Hello, world!")]);
//! 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;
///
/// 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<'a> {
code: String,
requires: Vec<&'a str>,
exit: i32,
}
/// # The C Argument.
pub enum CArg<'a> {
/// The String argument.
String(&'a str),
/// The identifier argument.
Ident(&'a str),
/// The i32 argument.
Int32(i32),
/// The i64 argument.
Int64(i64),
/// The float argument.
Float(f32),
/// The 'double' argument.
Double(f64),
/// The boolean argument.
Bool(bool),
}
impl Default for Code<'_> {
fn default() -> Self {
Self::new()
}
}
impl Code<'_> {
/// # Create a new C Code object.
///
/// ## Example
/// ```rust
/// use c_emit::Code;
///
/// 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;
///
/// 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;
///
/// 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: &'static str) {
if self.requires.contains(&file) {
return;
}
self.requires.push(file);
}
/// # Call a function WITHOUT arguments.
///
/// ## Example
///
/// ```rust
/// use c_emit::Code;
///
/// 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};
///
/// let mut code = Code::new();
///
/// code.call_func_with_args("printf", vec![CArg::String("Hello, world!")]);
///
/// 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('(');
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('"');
}
CArg::Ident(id) => {
self.code.push_str(id);
}
CArg::Int32(n) => {
self.code.push_str(&n.to_string());
}
CArg::Int64(n) => {
self.code.push_str(&n.to_string());
}
CArg::Float(n) => {
self.code.push_str(&n.to_string());
}
CArg::Double(n) => {
self.code.push_str(&n.to_string());
}
CArg::Bool(b) => {
self.code.push_str(&b.to_string());
}
}
self.code.push(',');
}
if self.code.ends_with(',') {
self.code = self.code.strip_suffix(',').unwrap().to_string();
}
self.code.push_str(");\n")
}
/// # Make a new string variable.
///
/// ## Example
///
/// ```rust
/// use c_emit::{Code, CArg};
///
/// let mut code = Code::new();
///
/// code.new_var_string("a", Some("hello"), None);
///
/// assert_eq!(code.to_string(), r#"
/// int main() {
/// char a[]="hello";
/// return 0;
/// }
/// "#.trim_start().to_string());
///
/// ```
/// ## NOTE:
/// Set the `initval` argument to `None` to make the variable uninitialized.
pub fn new_var_string<S: AsRef<str>>(
&mut self,
name: S,
initval: Option<S>,
size: Option<u32>,
) {
self.code.push_str("char ");
self.code.push_str(name.as_ref());
if initval.is_none() {
self.code.push('[');
self.code
.push_str(&size.expect("Expected size if uninitialized.").to_string());
self.code.push_str("];");
} else {
self.code.push_str("[]=\"");
if let Some(val) = initval {
self.code.push_str(val.as_ref());
}
self.code.push_str("\";");
}
self.code.push('\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.push_str(require);
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_zero() {
let mut code = Code::new();
code.exit(0);
assert_eq!(code.to_string(), "int main() {\nreturn 0;\n}\n");
}
#[test]
fn test_exit_non_zero() {
let mut code = Code::new();
code.exit(1);
assert_eq!(code.to_string(), "int main() {\nreturn 1;\n}\n");
}
#[test]
fn test_multiple_exits() {
let mut code = Code::new();
code.exit(0);
code.exit(1);
assert_eq!(code.to_string(), "int main() {\nreturn 1;\n}\n");
}
#[test]
fn test_include_valid() {
let mut code = Code::new();
code.include("stdio.h");
assert!(code.to_string().contains("#include<stdio.h>"));
}
#[test]
fn test_func_no_args() {
let mut code = Code::new();
code.call_func("printf");
assert!(code.to_string().contains("printf();"));
}
#[test]
fn test_func_with_args() {
let mut code = Code::new();
code.call_func_with_args("printf", vec![CArg::String("Hello")]);
assert!(code.to_string().contains("printf(\"Hello\");"));
}
#[test]
fn test_variable_string() {
let mut code = Code::new();
code.new_var_string("msg", Some("Hello"), None);
assert!(code.to_string().contains("char msg[]=\"Hello\";"));
}
}