libhanzzok/codegen/
mod.rs1use std::io::{self, Write};
2
3use crate::core::{ast::HanzzokAstNode, Compiler};
4
5pub use self::context::Context;
6pub use self::html::{HtmlNode, HtmlNodeRef};
7pub use self::walker::Walker;
8
9mod context;
10mod html;
11mod walker;
12
13pub fn compile_html(
14 nodes: &[HanzzokAstNode],
15 compiler: &Compiler,
16 w: &mut impl Write,
17) -> io::Result<()> {
18 let mut context = Context::new(compiler);
19
20 let html_nodes: Vec<_> = nodes.iter().flat_map(|node| context.walk(node)).collect();
21 for html_node in html_nodes {
22 html_node.write(&context, w)?;
23 }
24
25 Ok(())
26}
27
28pub fn compile_html_nodes<'a>(
29 nodes: &'a [HanzzokAstNode],
30 compiler: &'a Compiler,
31) -> (Context<'a>, Vec<(HanzzokAstNode, Vec<HtmlNode>)>) {
32 let mut context = Context::new(compiler);
33
34 let html_nodes: Vec<_> = nodes
35 .iter()
36 .map(|node| (node.clone(), context.walk(node)))
37 .collect();
38
39 (context, html_nodes)
40}
41
42#[cfg(target_arch = "wasm32")]
43#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
44pub fn w_compile_html(
45 nodes: &crate::syntax::HanzzokParsed,
46 compiler: &Compiler,
47) -> Result<String, wasm_bindgen::JsValue> {
48 let mut cursor = io::Cursor::new(Vec::new());
49 match compile_html(
50 &nodes
51 .nodes
52 .iter()
53 .map(|node| node.handle.clone())
54 .collect::<Vec<_>>(),
55 compiler,
56 &mut cursor,
57 ) {
58 Ok(_) => Ok(String::from_utf8_lossy(&cursor.into_inner()).to_string()),
59 Err(e) => Err(wasm_bindgen::JsValue::from_str(&e.to_string())),
60 }
61}
62
63#[cfg(target_arch = "wasm32")]
64#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
65pub struct HanzzokCompiled {
66 htmls: Vec<String>,
67}
68
69#[cfg(target_arch = "wasm32")]
70#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
71impl HanzzokCompiled {
72 pub fn next(&mut self) -> Option<String> {
73 if self.htmls.len() > 0 {
74 Some(self.htmls.remove(0))
75 } else {
76 None
77 }
78 }
79}
80
81#[cfg(target_arch = "wasm32")]
82#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
83pub fn w_compile_html_nodes(
84 nodes: &crate::syntax::HanzzokParsed,
85 compiler: &Compiler,
86) -> Result<HanzzokCompiled, wasm_bindgen::JsValue> {
87 let nodes: Vec<_> = nodes.nodes.iter().map(|node| node.handle.clone()).collect();
88 let (context, nodes) = compile_html_nodes(&nodes, compiler);
89 Ok(HanzzokCompiled {
90 htmls: nodes
91 .into_iter()
92 .map(|(_, nodes)| {
93 let mut cursor = io::Cursor::new(Vec::new());
94 for node in nodes {
95 if let Err(e) = node.write(&context, &mut cursor) {
96 return Err(wasm_bindgen::JsValue::from_str(&e.to_string()));
97 }
98 }
99 Ok(String::from_utf8_lossy(&cursor.into_inner()).to_string())
100 })
101 .collect::<Result<_, _>>()?,
102 })
103}