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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
|
use std::path::Path;
use rlua::Lua;
use crate::{error::LuaXError, Result};
mod lexer;
mod preprocessor;
#[cfg(test)]
mod tests;
mod tokens;
pub fn table_to_html<W: std::io::Write>(table: rlua::Table, f: &mut W) -> Result<()> {
let tag_name: Option<String> = table.get("tag").unwrap();
if tag_name.is_none() {
// we might be in a list
for child in table.sequence_values::<rlua::Value>() {
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()),
}
}
return Ok(());
}
let type_name = tag_name.unwrap();
write!(f, "<{}", type_name)?;
let mut children = None;
let mut attrs = None;
for pair in table.pairs::<String, rlua::Value>() {
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::<String, rlua::String>() {
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::<rlua::Value>() {
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<String> {
let mut buf = Vec::new();
let preprocessor = preprocessor::Preprocessor::new(s, &mut buf)?;
match preprocessor.preprocess() {
Ok(_) => {}
Err(e) => {
println!("got up to: {}", String::from_utf8_lossy(&buf));
return Err(e);
}
}
let s = String::from_utf8(buf).unwrap();
Ok(s)
}
pub fn preprocess_dir(path: &Path, output_path: &Path) -> Result<usize> {
let mut preprocessed = 0;
for entry in std::fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let output_dir = output_path.join(path.file_name().unwrap());
if !output_dir.is_dir() && output_dir.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("{} already exists", output_dir.display()),
)
.into());
}
if !output_dir.exists() {
std::fs::create_dir(&output_dir)?;
}
preprocessed += preprocess_dir(&path, &output_path.join(path.file_name().unwrap()))?;
} else {
if path.extension().unwrap_or_default() != "luax" {
continue;
}
let s = std::fs::read_to_string(&path)?;
let s = preprocess(&s)?;
let out_path = output_path
.join(path.file_name().unwrap())
.with_extension("lua");
std::fs::write(out_path, s)?;
preprocessed += 1;
}
}
Ok(preprocessed)
}
pub fn prepare_lua(dev_mode: bool) -> Result<Lua> {
let lua = Lua::new();
// create a table called "reluax" with common utility functions
// and put it in the global scope
lua.context(|ctx| -> Result<()> {
let reluax = ctx.create_table()?;
let url_matches = ctx.create_function(utils::url_matches)?;
reluax.set("url_matches", url_matches)?;
let url_extract = ctx.create_function(utils::url_extract)?;
reluax.set("url_extract", url_extract)?;
reluax.set("dev_mode", dev_mode)?;
ctx.globals().set("reluax", reluax)?;
Ok(())
})?;
Ok(lua)
}
mod utils {
use rlua::{Context, Result, Table};
/// Check if a path matches a pattern
///
/// A pattern can contain the following:
/// - `*` matches any number of characters
/// - `{name}` matches anything except `/` and captures the value as `name`
///
/// Example patterns:
/// '/foo/bar'
/// '/foo/{bar}' -> in a case of '/foo/baz' will capture 'baz' as 'bar'
/// '/foo/*' -> in a case of '/foo/baz' will match
///
/// This function only checks if the path matches the pattern, it does not
/// capture any values.
pub fn url_matches(_: Context<'_>, (pattern, path): (String, String)) -> Result<bool> {
let mut path = path.chars();
let mut pattern = pattern.chars();
let mut path_char = path.next();
let mut pattern_char = pattern.next();
loop {
if path_char.is_none() && (pattern_char.is_none() || pattern_char == Some('*')) {
return Ok(true);
} else if path_char == pattern_char {
path_char = path.next();
pattern_char = pattern.next();
} else if pattern_char == Some('*') {
pattern_char = pattern.next();
if pattern_char.is_none() {
return Ok(true);
}
while path_char != pattern_char {
path_char = path.next();
if path_char.is_none() {
return Ok(false);
}
}
} else if pattern_char == Some('{') {
pattern_char = pattern.next();
let mut param_name = String::new();
while pattern_char != Some('}') {
param_name.push(pattern_char.unwrap());
pattern_char = pattern.next();
}
pattern_char = pattern.next();
while path_char != Some('/') && path_char.is_some() {
path_char = path.next();
}
if path_char.is_none() {
return Ok(true);
}
} else {
return Ok(false);
}
}
}
/// Extract values from a path using a pattern
///
/// A pattern can contain the following:
/// - `*` matches any number of characters
/// - `{name}` matches anything except `/` and captures the value as `name`
///
/// This function will return a table with the captured values.
pub fn url_extract(ctx: Context<'_>, (pattern, path): (String, String)) -> Result<Table> {
let mut path = path.chars();
let mut pattern = pattern.chars();
let mut path_char = path.next();
let mut pattern_char = pattern.next();
let params = ctx.create_table()?;
loop {
if path_char.is_none() && (pattern_char.is_none() || pattern_char == Some('*')) {
return Ok(params);
} else if path_char == pattern_char {
path_char = path.next();
pattern_char = pattern.next();
} else if pattern_char == Some('*') {
pattern_char = pattern.next();
if pattern_char.is_none() {
return Ok(params);
}
while path_char != pattern_char {
path_char = path.next();
if path_char.is_none() {
return Ok(params);
}
}
} else if pattern_char == Some('{') {
pattern_char = pattern.next();
let mut param_name = String::new();
while pattern_char != Some('}') {
param_name.push(pattern_char.unwrap());
pattern_char = pattern.next();
}
pattern_char = pattern.next();
let mut param_value = String::new();
while path_char != Some('/') && path_char.is_some() {
param_value.push(path_char.unwrap());
path_char = path.next();
}
params.set(param_name, param_value)?;
if path_char.is_none() {
return Ok(params);
}
} else {
return Ok(params);
}
}
}
#[cfg(test)]
mod tests {
use rlua::Lua;
#[test]
fn url_matches() {
let cases = vec![
("/", "/", true),
("/*/", "/abc/", true),
("/a/*/c", "/a/b/c", true),
("/a/*/c", "/a/b/c/d", false),
("/a/*/c", "/a/b", false),
("/a/*/c", "/a/f/c/d", false),
("/a", "/a", true),
("/a", "/b", false),
("/{name}", "/a", true),
("/{name}", "/a/b", false),
("/{name}/b", "/a/b", true),
("/{name}/b", "/a/c", false),
("/{name}/b", "/a/b/c", false),
];
let lua = Lua::new();
for (pattern, path, expected) in cases {
let res: bool = lua
.context(|ctx| super::url_matches(ctx, (pattern.to_string(), path.to_string())))
.unwrap();
if res != expected {
if expected {
panic!("expected {} to match {}", path, pattern);
} else {
panic!("expected {} to not match {}", path, pattern);
}
}
}
}
#[test]
fn url_extract() {
let cases = vec![
("/", "/", vec![]),
("/{name}", "/a", vec![("name", "a")]),
("/{name}/b", "/a/b", vec![("name", "a")]),
("/{name}/b", "/a/c", vec![]),
("/{name}/b", "/a/b/c", vec![]),
(
"/{name}/b/{name2}",
"/a/b/c",
vec![("name", "a"), ("name2", "c")],
),
(
"/{name}/b/{name2}",
"/a/b/c/d",
vec![("name", "a"), ("name2", "c")],
),
("/{name}/b/{name2}", "/a/b", vec![("name", "a")]),
];
let lua = Lua::new();
for (pattern, path, mut expected) in cases {
expected.sort_by_key(|(k, _)| k.to_owned());
lua.context(|ctx| {
let res =
super::url_extract(ctx, (pattern.to_string(), path.to_string())).unwrap();
let mut res_vec = Vec::new();
for pair in res.pairs::<String, String>() {
let (key, value) = pair.unwrap();
res_vec.push((key, value));
}
res_vec.sort_by_key(|(k, _)| k.clone());
let equal = res_vec
.iter()
.zip(expected.iter())
.all(|((k1, v1), (k2, v2))| k1 == k2 && v1 == v2);
if !equal {
panic!(
"expected {:?} to be {:?} for pattern {} and path {}",
res_vec, expected, pattern, path
);
}
})
}
}
}
}
|