diff options
author | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2016-12-24 11:05:01 +0100 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2016-12-24 11:05:01 +0100 |
commit | c238e53ffe41ab54142c798ff4dbe5592ec5ed99 (patch) | |
tree | 559e1732e70d7bc290ea2d56557f46137b4a8d6f | |
parent | 760752e79da94511862cb1cc4d73e881d77ccbf9 (diff) | |
download | askama-c238e53ffe41ab54142c798ff4dbe5592ec5ed99.tar.gz askama-c238e53ffe41ab54142c798ff4dbe5592ec5ed99.tar.bz2 askama-c238e53ffe41ab54142c798ff4dbe5592ec5ed99.zip |
Introduce code generator impl
Diffstat (limited to '')
-rw-r--r-- | askama_codegen/src/generator.rs | 42 |
1 files changed, 29 insertions, 13 deletions
diff --git a/askama_codegen/src/generator.rs b/askama_codegen/src/generator.rs index 7689af5..971e2e2 100644 --- a/askama_codegen/src/generator.rs +++ b/askama_codegen/src/generator.rs @@ -1,23 +1,39 @@ use parser::Node; use std::str; +struct Generator { + buf: String, +} + +impl Generator { + fn new() -> Generator { + Generator { buf: String::new() } + } + fn write(&mut self, s: &str) { + self.buf.push_str(s); + } + fn result(self) -> String { + self.buf + } +} + pub fn generate(ctx_name: &str, tokens: &Vec<Node>) -> String { - let mut code = String::new(); - code.push_str("impl askama::Template for "); - code.push_str(ctx_name); - code.push_str(" {\n"); - code.push_str(" fn render(&self) -> String {\n"); - code.push_str(" let mut buf = String::new();\n"); + let mut gen = Generator::new(); + gen.write("impl askama::Template for "); + gen.write(ctx_name); + gen.write(" {\n"); + gen.write(" fn render(&self) -> String {\n"); + gen.write(" let mut buf = String::new();\n"); for n in tokens { - code.push_str(" buf.push_str("); - code.push_str(&match n { + gen.write(" buf.push_str("); + gen.write(&match n { &Node::Lit(val) => format!("{:#?}", str::from_utf8(val).unwrap()), &Node::Expr(val) => format!("&self.{}", str::from_utf8(val).unwrap()), }); - code.push_str(");\n"); + gen.write(");\n"); } - code.push_str(" buf"); - code.push_str(" }\n"); - code.push_str("}\n\n"); - code + gen.write(" buf"); + gen.write(" }\n"); + gen.write("}\n\n"); + gen.result() } |