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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
|
use std::path::Path;
use mlua::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: mlua::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::<mlua::Value>() {
match child? {
mlua::Value::Table(child) => table_to_html(child, f)?,
mlua::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, mlua::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 mlua::Value::Table(attrs) = attrs {
for pair in attrs.pairs::<String, mlua::LuaString>() {
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 mlua::Value::Table(children) = children {
for child in children.sequence_values::<mlua::Value>() {
match child? {
mlua::Value::Table(child) => table_to_html(child, f)?,
mlua::Value::String(s) => write!(f, "{}", s.to_str()?)?,
mlua::Value::Boolean(b) => write!(f, "{}", b)?,
mlua::Value::Number(n) => write!(f, "{}", n)?,
_ => return Err(LuaXError::NonTableChildren.into()),
}
}
} else {
return Err(LuaXError::NonTableChildren.into());
}
}
write!(f, "</{}>", type_name)?;
Ok(())
}
pub fn table_to_json<W: std::io::Write>(table: mlua::Table, f: &mut W) -> Result<()> {
let mut first = true;
write!(f, "{{")?;
for pair in table.pairs::<String, mlua::Value>() {
let (key, value) = pair?;
if !first {
write!(f, ",")?;
}
first = false;
write!(f, "\"{}\":", key)?;
match value {
mlua::Value::Table(t) => table_to_json(t, f)?,
mlua::Value::String(s) => write!(f, "\"{}\"", s.to_str()?)?,
mlua::Value::Boolean(b) => write!(f, "{}", b)?,
mlua::Value::Number(n) => write!(f, "{}", n)?,
mlua::Value::Nil => write!(f, "null")?,
_ => return Err(LuaXError::NonJsonType.into()),
}
}
write!(f, "}}")?;
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;
let absolute_output_path = output_path.canonicalize()?;
for entry in std::fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
if path.canonicalize()? == absolute_output_path {
continue;
}
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)?;
}
let inner_path = output_path.join(path.file_name().unwrap());
preprocessed += preprocess_dir(&path, &inner_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 = 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
let reluax = lua.create_table()?;
let url_matches = lua.create_function(utils::url_matches)?;
reluax.set("url_matches", url_matches)?;
let url_extract = lua.create_function(utils::url_extract)?;
reluax.set("url_extract", url_extract)?;
let html = lua.create_function(utils::wrap_html)?;
reluax.set("html", html)?;
let html_page = lua.create_function(utils::wrap_html_page)?;
reluax.set("html_page", html_page)?;
let json = lua.create_function(utils::wrap_json)?;
reluax.set("json", json)?;
let headers = lua.create_function(utils::wrap_headers)?;
reluax.set("headers", headers)?;
reluax.set("dev_mode", dev_mode)?;
lua.globals().set("reluax", reluax)?;
Ok(lua)
}
mod utils {
use mlua::{Lua, 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(_: &Lua, (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: &Lua, (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);
}
}
}
/// Wrap a table in a table to signal that it should be rendered as HTML
pub fn wrap_html(_: &Lua, table: Table) -> Result<Table> {
table.set("type", "html")?;
Ok(table)
}
/// Wrap a table in a table to signal that it should be rendered as a full HTML page
pub fn wrap_html_page(_: &Lua, table: Table) -> Result<Table> {
table.set("type", "html-page")?;
Ok(table)
}
/// Wrap a table in a table to signal that it should be rendered as JSON
pub fn wrap_json(_: &Lua, table: Table) -> Result<Table> {
table.set("type", "json")?;
Ok(table)
}
/// Wrap a table to add headers to the response
pub fn wrap_headers(_: &Lua, (table, headers): (Table, Table)) -> Result<Table> {
table.set("headers", headers)?;
Ok(table)
}
#[cfg(test)]
mod tests {
use mlua::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 =
super::url_matches(&lua, (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());
let res = super::url_extract(&lua, (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
);
}
}
}
}
}
|