use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
Text(String),
Variable {
name: String,
raw: bool,
expression: Option<Expression>, },
Conditional {
condition: Expression,
then_branch: Vec<Node>,
else_if_branches: Vec<(Expression, Vec<Node>)>,
else_branch: Option<Vec<Node>>,
},
Loop {
item_name: String,
collection: Expression,
body: Vec<Node>,
},
Break,
Continue,
Index,
SectionDef {
name: String,
content: Vec<Node>,
},
SectionCall(String),
HelperDef {
name: String,
params: Vec<String>,
body: Vec<Node>,
},
HelperCall {
name: String,
args: Vec<Expression>,
},
View {
name: String,
model: Option<Expression>,
},
Import(Vec<String>),
Meta {
title: Option<String>,
description: Option<String>,
keywords: Option<String>,
},
Title(Expression),
Description(Expression),
FormField {
kind: FormFieldKind,
name: String,
value: Option<String>,
label: Option<String>,
attrs: Vec<(String, AttrValue)>,
},
Body,
Head,
Content,
Csrf,
Translate {
text: String,
is_key: bool,
},
Config(String),
Repository(String), App(String), Main(String), R(String), Model(String), M(String), Session(String),
Query(String),
User(Option<String>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum FormFieldKind {
Text,
Password,
Hidden,
Textarea,
Checkbox,
Radio,
}
#[derive(Debug, Clone, PartialEq)]
pub enum AttrValue {
Str(String),
Number(f64),
Bool(bool),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
String(String),
Number(f64),
Boolean(bool),
Variable(String),
PropertyAccess {
object: Box<Expression>,
property: String,
},
Array(Vec<Expression>),
Object(HashMap<String, Expression>),
FunctionCall { name: String, args: Vec<Expression> },
BinaryOp {
left: Box<Expression>,
op: BinaryOperator,
right: Box<Expression>,
},
UnaryOp {
op: UnaryOperator,
operand: Box<Expression>,
},
Ternary {
condition: Box<Expression>,
then_expr: Box<Expression>,
else_expr: Box<Expression>,
},
Null,
}
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
Equal,
NotEqual,
LessThan,
LessThanOrEqual,
GreaterThan,
GreaterThanOrEqual,
And,
Or,
Add,
Subtract,
Multiply,
Divide,
Modulo,
}
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOperator {
Not,
Minus,
}
#[derive(Debug, Clone)]
pub struct Template {
pub nodes: Vec<Node>,
pub sections: HashMap<String, Vec<Node>>,
pub helpers: HashMap<String, Helper>,
}
#[derive(Debug, Clone)]
pub struct Helper {
pub params: Vec<String>,
pub body: Vec<Node>,
}
impl Template {
pub fn new() -> Self {
Self {
nodes: Vec::new(),
sections: HashMap::new(),
helpers: HashMap::new(),
}
}
pub fn extract_sections(&mut self) {
let mut new_nodes = Vec::new();
let mut i = 0;
while i < self.nodes.len() {
match &self.nodes[i] {
Node::SectionDef { name, content } => {
self.sections.insert(name.clone(), content.clone());
}
_ => {
new_nodes.push(self.nodes[i].clone());
}
}
i += 1;
}
self.nodes = new_nodes;
}
pub fn extract_helpers(&mut self) {
let mut new_nodes = Vec::new();
let mut i = 0;
while i < self.nodes.len() {
match &self.nodes[i] {
Node::HelperDef { name, params, body } => {
self.helpers.insert(
name.clone(),
Helper {
params: params.clone(),
body: body.clone(),
},
);
}
_ => {
new_nodes.push(self.nodes[i].clone());
}
}
i += 1;
}
self.nodes = new_nodes;
}
}
impl Default for Template {
fn default() -> Self {
Self::new()
}
}
impl Expression {
pub fn from_path(path: &str) -> Self {
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return Expression::Null;
}
let mut expr = Expression::Variable(parts[0].to_string());
for part in parts.iter().skip(1) {
expr = Expression::PropertyAccess {
object: Box::new(expr),
property: part.to_string(),
};
}
expr
}
pub fn parse_value(value: &str) -> Self {
let trimmed = value.trim();
if trimmed == "true" {
return Expression::Boolean(true);
}
if trimmed == "false" {
return Expression::Boolean(false);
}
if trimmed == "null" || trimmed == "NULL" {
return Expression::Null;
}
if let Ok(num) = trimmed.parse::<f64>() {
return Expression::Number(num);
}
if (trimmed.starts_with('"') && trimmed.ends_with('"'))
|| (trimmed.starts_with('\'') && trimmed.ends_with('\''))
{
let content = &trimmed[1..trimmed.len() - 1];
return Expression::String(content.to_string());
}
if trimmed.starts_with('[') && trimmed.ends_with(']') {
let content = &trimmed[1..trimmed.len() - 1];
let items: Vec<Expression> = content
.split(',')
.map(|s| Expression::parse_value(s.trim()))
.collect();
return Expression::Array(items);
}
Expression::from_path(trimmed)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_expression_from_path() {
let expr = Expression::from_path("user.profile.name");
match expr {
Expression::PropertyAccess { object, property } => {
assert_eq!(property, "name");
match *object {
Expression::PropertyAccess {
object: inner,
property: prop,
} => {
assert_eq!(prop, "profile");
match *inner {
Expression::Variable(var) => assert_eq!(var, "user"),
_ => panic!("Expected variable"),
}
}
_ => panic!("Expected property access"),
}
}
_ => panic!("Expected property access"),
}
}
#[test]
fn test_parse_value() {
assert_eq!(Expression::parse_value("true"), Expression::Boolean(true));
assert_eq!(Expression::parse_value("false"), Expression::Boolean(false));
assert_eq!(Expression::parse_value("42"), Expression::Number(42.0));
assert_eq!(Expression::parse_value("3.14"), Expression::Number(3.14));
assert_eq!(
Expression::parse_value("\"hello\""),
Expression::String("hello".to_string())
);
assert_eq!(
Expression::parse_value("'world'"),
Expression::String("world".to_string())
);
assert_eq!(Expression::parse_value("null"), Expression::Null);
match Expression::parse_value("myVar") {
Expression::Variable(v) => assert_eq!(v, "myVar"),
_ => panic!("Expected variable"),
}
}
#[test]
fn test_template_sections() {
let mut template = Template::new();
template.nodes.push(Node::Text("Before".to_string()));
template.nodes.push(Node::SectionDef {
name: "header".to_string(),
content: vec![Node::Text("Header content".to_string())],
});
template.nodes.push(Node::Text("After".to_string()));
template.extract_sections();
assert_eq!(template.nodes.len(), 2);
assert!(template.sections.contains_key("header"));
let header = &template.sections["header"];
assert_eq!(header.len(), 1);
match &header[0] {
Node::Text(t) => assert_eq!(t, "Header content"),
_ => panic!("Expected text node"),
}
}
}