aboutsummaryrefslogtreecommitdiff
path: root/src/luax/mod.rs
blob: a7eb38f8c3e7a871d8ba580c013d6d5e75b176c4 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use crate::Result;

mod lexer;
mod preprocessor;
mod tokens;

#[derive(Debug)]
pub enum Node<'s> {
    Code(&'s str),
    Text(&'s str),
    Element(Element<'s>),
}

impl<'s> Node<'s> {
    pub fn to_table<W: std::io::Write>(&self, f: &mut W) -> Result<()> {
        match &self {
            Node::Code(s) => write!(f, "{}", s)?,
            Node::Text(s) => write!(f, "\"{}\"", s)?,
            Node::Element(element) => {
                write!(f, "{{")?;
                write!(f, "tag=\"{}\", ", element.tag)?;
                for attribute in &element.attributes {
                    match &attribute.value {
                        Value::Literal(s) => write!(f, "{}=\"{}\", ", attribute.key, s)?,
                        Value::Expression(s) => write!(f, "{}={}, ", attribute.key, s)?,
                    }
                }
                write!(f, "children={{")?;
                for child in &element.children {
                    child.to_table(f)?;
                }
                write!(f, "}}")?;
                write!(f, "}}")?;
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct Element<'s> {
    pub tag: &'s str,
    pub attributes: Vec<Attribute<'s>>,
    pub children: Vec<Node<'s>>,
}

#[derive(Debug)]
pub struct Attribute<'s> {
    pub key: &'s str,
    pub value: Value<'s>,
}

#[derive(Debug)]
pub enum Value<'s> {
    Literal(&'s str),
    Expression(&'s str),
}

#[derive(Debug)]
pub struct Template<'s> {
    pub root: Node<'s>,
}

impl<'s> Template<'s> {
    pub fn to_table<W: std::io::Write>(&self, f: &mut W) -> Result<()> {
        self.root.to_table(f)
    }
}

pub fn preprocess(s: &str) -> Result<String> {
    let mut buf = Vec::new();
    let preprocessor = preprocessor::Preprocessor::new(s, &mut buf)?;

    preprocessor.preprocess()?;

    let s = String::from_utf8(buf).unwrap();

    Ok(s)
}

pub fn preprocess_dir(path: &std::path::Path) -> Result<()> {
    for entry in std::fs::read_dir(path)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            preprocess_dir(&path)?;
        } else {
            if path.extension().unwrap_or_default() != "luax" {
                continue;
            }
            let s = std::fs::read_to_string(&path)?;
            let s = preprocess(&s)?;

            let out_path = path.with_extension("lua");

            std::fs::write(out_path, s)?;
        }
    }

    Ok(())
}