blob: 13a91dd568de1fdb8b6c46e15dae349c2b3102cb (
plain) (
blame)
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
|
use parser::Node;
use std::str;
struct Generator {
buf: String,
}
impl Generator {
fn new() -> Generator {
Generator { buf: String::new() }
}
fn init(&mut self, name: &str) {
self.write("impl askama::Template for ");
self.write(name);
self.write(" {\n");
self.write(" fn render(&self) -> String {\n");
self.write(" let mut buf = String::new();\n");
}
fn write(&mut self, s: &str) {
self.buf.push_str(s);
}
fn visit_lit(&mut self, s: &[u8]) {
self.write(" buf.push_str(");
self.write(&format!("{:#?}", str::from_utf8(s).unwrap()));
self.write(");\n");
}
fn visit_expr(&mut self, s: &[u8]) {
self.write(" buf.push_str(");
self.write(&format!("&self.{}", str::from_utf8(s).unwrap()));
self.write(");\n");
}
fn handle(&mut self, tokens: &Vec<Node>) {
for n in tokens {
match n {
&Node::Lit(val) => { self.visit_lit(val); },
&Node::Expr(val) => { self.visit_expr(val); },
}
}
}
fn finalize(&mut self) {
self.write(" buf");
self.write(" }\n");
self.write("}\n\n");
}
fn result(self) -> String {
self.buf
}
}
pub fn generate(ctx_name: &str, tokens: &Vec<Node>) -> String {
let mut gen = Generator::new();
gen.init(ctx_name);
gen.handle(tokens);
gen.finalize();
gen.result()
}
|