tirbofish/dropbear
main / crates / magna-carta / src / generator / mod.rs · 2663 bytes
crates/magna-carta/src/generator/mod.rs
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
use crate::ScriptManifest;
use std::path::Path;
pub mod jvm;
pub mod native;
/// A trait that can generate code from a manifest.
pub trait Generator {
/// Generate code from a manifest.
///
/// # Returns
/// [`anyhow::Result<String>`] - The code from the manifest into that specific language.
fn generate(&self, manifest: &ScriptManifest) -> anyhow::Result<String>;
/// Writes to a file using the std library.
fn write_to_file(
&self,
manifest: &ScriptManifest,
path: impl AsRef<Path>,
) -> anyhow::Result<()> {
let content = self.generate(manifest)?;
std::fs::write(path, content)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ManifestItem;
use crate::generator::jvm::KotlinJVMGenerator;
use crate::generator::native::KotlinNativeGenerator;
use std::path::PathBuf;
#[test]
fn test_native_generator() {
let mut manifest = ScriptManifest::new();
manifest.add_item(ManifestItem::new(
"com.game.Player".to_string(),
"Player".to_string(),
vec!["player".to_string(), "movement".to_string()],
PathBuf::from("src/Player.kt"),
));
manifest.add_item(ManifestItem::new(
"com.game.GlobalLogger".to_string(),
"GlobalLogger".to_string(),
vec![],
PathBuf::from("src/GlobalLogger.kt"),
));
let generator = KotlinNativeGenerator;
let output = generator.generate(&manifest).unwrap();
assert!(output.contains("import com.game.Player"));
assert!(output.contains("import com.game.GlobalLogger"));
assert!(output.contains("tags = listOf(\"player\", \"movement\")"));
assert!(output.contains("tags = listOf()"));
assert!(output.contains("script = Player()"));
assert!(output.contains("script = GlobalLogger()"));
assert!(output.contains("@CName(\"dropbear_load\")"));
assert!(output.contains("@CName(\"dropbear_update\")"));
assert!(output.contains("@CName(\"dropbear_destroy\")"));
}
#[test]
fn test_jvm_generator() {
let mut manifest = ScriptManifest::new();
manifest.add_item(ManifestItem::new(
"com.game.Player".to_string(),
"Player".to_string(),
vec!["player".to_string()],
PathBuf::from("src/Player.kt"),
));
let generator = KotlinJVMGenerator;
let output = generator.generate(&manifest).unwrap();
assert!(output.contains("import com.game.*"));
assert!(output.contains("Player::class"));
}
}