From f45abfdf2150d8136e3da48e1daba5473030c0be Mon Sep 17 00:00:00 2001 From: Stanisław Zagórowski Date: Thu, 11 Jan 2024 16:23:45 +0100 Subject: reorganize and prettify --- src/luax/mod.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 4 deletions(-) (limited to 'src/luax') diff --git a/src/luax/mod.rs b/src/luax/mod.rs index df9f57d..2e6fe27 100644 --- a/src/luax/mod.rs +++ b/src/luax/mod.rs @@ -1,4 +1,4 @@ -use crate::Result; +use crate::{error::LuaXError, Result}; mod lexer; mod preprocessor; @@ -6,6 +6,63 @@ mod preprocessor; mod tests; mod tokens; +pub fn table_to_html(table: rlua::Table, f: &mut W) -> Result<()> { + let type_name: Option = table.get("tag").unwrap(); + + if type_name.is_none() { + return Err(LuaXError::MissingField("tag".to_string()).into()); + } + + let type_name = type_name.unwrap(); + + write!(f, "<{}", type_name)?; + let mut children = None; + let mut attrs = None; + for pair in table.pairs::() { + let (key, value) = pair?; + if key == "tag" { + continue; + } + if key == "children" { + children = Some(value); + continue; + } + if key == "attrs" { + attrs = Some(value); + continue; + } + } + if let Some(attrs) = attrs { + if let rlua::Value::Table(attrs) = attrs { + for pair in attrs.pairs::() { + let (key, value) = pair?; + write!(f, " {}=\"{}\"", key, value.to_str()?)?; + } + } else { + return Err(LuaXError::NonTableAttrs.into()); + } + } + write!(f, ">")?; + + if let Some(children) = children { + if let rlua::Value::Table(children) = children { + for child in children.sequence_values::() { + match child? { + rlua::Value::Table(child) => table_to_html(child, f)?, + rlua::Value::String(s) => write!(f, "{}", s.to_str()?)?, + _ => return Err(LuaXError::NonTableChildren.into()), + } + } + } else { + return Err(LuaXError::NonTableChildren.into()); + } + } + + write!(f, "", type_name)?; + + Ok(()) +} + pub fn preprocess(s: &str) -> Result { let mut buf = Vec::new(); let preprocessor = preprocessor::Preprocessor::new(s, &mut buf)?; @@ -17,12 +74,13 @@ pub fn preprocess(s: &str) -> Result { Ok(s) } -pub fn preprocess_dir(path: &std::path::Path) -> Result<()> { +pub fn preprocess_dir(path: &std::path::Path) -> Result { + let mut preprocessed = 0; for entry in std::fs::read_dir(path)? { let entry = entry?; let path = entry.path(); if path.is_dir() { - preprocess_dir(&path)?; + preprocessed += preprocess_dir(&path)?; } else { if path.extension().unwrap_or_default() != "luax" { continue; @@ -33,8 +91,9 @@ pub fn preprocess_dir(path: &std::path::Path) -> Result<()> { let out_path = path.with_extension("lua"); std::fs::write(out_path, s)?; + preprocessed += 1; } } - Ok(()) + Ok(preprocessed) } -- cgit v1.3.1