rustf 1.0.0

A simple MVC web framework inspired by Total.js
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std::collections::HashMap;

/// AST node types for Total.js templates
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
    /// Plain text content
    Text(String),

    /// Variable interpolation @{variable} or @{expression}
    Variable {
        name: String,
        /// `true` for the raw form `@{!variable}`, which emits the value
        /// WITHOUT HTML-escaping. SECURITY: only use raw output for values you
        /// fully trust — never wrap user/request-derived data in `@{!...}`, or
        /// you create an XSS hole. The default `@{variable}` form escapes.
        raw: bool,
        expression: Option<Expression>, // Some(expr) when name contains an expression like ternary
    },

    /// Conditional block @{if}...@{else}...@{fi}
    Conditional {
        condition: Expression,
        then_branch: Vec<Node>,
        else_if_branches: Vec<(Expression, Vec<Node>)>,
        else_branch: Option<Vec<Node>>,
    },

    /// Loop block @{foreach item in collection}...@{end}
    Loop {
        item_name: String,
        collection: Expression,
        body: Vec<Node>,
    },

    /// Break statement in loops
    Break,

    /// Continue statement in loops
    Continue,

    /// Loop index variable @{index}
    Index,

    /// Section definition @{section name}...@{end}
    SectionDef {
        name: String,
        content: Vec<Node>,
    },

    /// Section reference @{section('name')}
    SectionCall(String),

    /// Helper definition @{helper name(args)}...@{end}
    HelperDef {
        name: String,
        params: Vec<String>,
        body: Vec<Node>,
    },

    /// Helper call @{name(args)}
    HelperCall {
        name: String,
        args: Vec<Expression>,
    },

    /// View inclusion @{view('name', model)}
    View {
        name: String,
        model: Option<Expression>,
    },

    /// Import resources @{import('file1', 'file2')}
    Import(Vec<String>),

    /// Meta tags @{meta(title, description, keywords)}
    Meta {
        title: Option<String>,
        description: Option<String>,
        keywords: Option<String>,
    },

    /// Page title setter @{title('value')} — stores the title in meta data
    /// (deferred); the layout outputs it via @{title}. Renders nothing inline.
    Title(Expression),

    /// Description meta setter @{description('value')} — stores the description
    /// in meta data (deferred); read back via @{description}. Renders nothing.
    Description(Expression),

    /// Form input helper, e.g. @{text('field', { class: 'x', required: true })},
    /// @{checkbox('agree', 'I agree')}, @{radio('g', 'male', 'Male')}. Auto-binds
    /// to the model field `name`; renders the matching HTML element.
    FormField {
        kind: FormFieldKind,
        name: String,
        /// Radio button value (compared to the model field for `checked`).
        value: Option<String>,
        /// Optional label text — wraps the input in a `<label>`.
        label: Option<String>,
        attrs: Vec<(String, AttrValue)>,
    },

    /// Special placeholders
    Body,
    Head,
    Content,
    Csrf,

    /// Translation @(text) or @(#key)
    Translate {
        text: String,
        is_key: bool,
    },

    /// Configuration value @{'%config-key'}
    Config(String),

    /// Special variables
    Repository(String), // Context repository @{repository.key}
    App(String),   // Global repository @{APP.key}
    Main(String),  // Global repository @{MAIN.key} (alias)
    R(String),     // Context repository @{R.key} (alias)
    Model(String), // Model data @{model.key}
    M(String),     // Model data @{M.key} (alias)
    Session(String),
    Query(String),
    User(Option<String>),
}

/// Kind of form-input helper.
#[derive(Debug, Clone, PartialEq)]
pub enum FormFieldKind {
    /// `@{text('field', {...})}` → `<input type="text" ...>`
    Text,
    /// `@{password('field', {...})}` → `<input type="password" ...>`
    Password,
    /// `@{hidden('field', {...})}` → `<input type="hidden" ...>`
    Hidden,
    /// `@{textarea('field', {...})}` → `<textarea ...>value</textarea>`
    Textarea,
    /// `@{checkbox('field', [label])}` → `<input type="checkbox" ...>`
    Checkbox,
    /// `@{radio('field', 'value', [label])}` → `<input type="radio" ...>`
    Radio,
}

/// A parsed HTML attribute value from a form-helper object literal
/// (e.g. `{ class: 'form', maxlength: 30, required: true }`).
#[derive(Debug, Clone, PartialEq)]
pub enum AttrValue {
    /// `key: 'string'` → rendered as `key="string"`
    Str(String),
    /// `key: 30` → rendered as `key="30"`
    Number(f64),
    /// `key: true` → rendered as a boolean attribute `key`; `false` → omitted
    Bool(bool),
}

/// Expression types for conditions and values
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
    /// String literal
    String(String),

    /// Number literal
    Number(f64),

    /// Boolean literal
    Boolean(bool),

    /// Variable reference
    Variable(String),

    /// Property access (e.g., user.name)
    PropertyAccess {
        object: Box<Expression>,
        property: String,
    },

    /// Array literal
    Array(Vec<Expression>),

    /// Object literal
    Object(HashMap<String, Expression>),

    /// Function call
    FunctionCall { name: String, args: Vec<Expression> },

    /// Binary operation
    BinaryOp {
        left: Box<Expression>,
        op: BinaryOperator,
        right: Box<Expression>,
    },

    /// Unary operation
    UnaryOp {
        op: UnaryOperator,
        operand: Box<Expression>,
    },

    /// Ternary operation (condition ? then_expr : else_expr)
    Ternary {
        condition: Box<Expression>,
        then_expr: Box<Expression>,
        else_expr: Box<Expression>,
    },

    /// Null value
    Null,
}

/// Binary operators
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
    // Comparison
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,

    // Logical
    And,
    Or,

    // Arithmetic
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
}

/// Unary operators
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOperator {
    Not,
    Minus,
}

/// Complete template AST
#[derive(Debug, Clone)]
pub struct Template {
    pub nodes: Vec<Node>,
    pub sections: HashMap<String, Vec<Node>>,
    pub helpers: HashMap<String, Helper>,
}

/// Helper function definition
#[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(),
        }
    }

    /// Extract sections from the main node list
    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;
    }

    /// Extract helper definitions from the main node list
    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()
    }
}

/// Helper functions for building expressions
impl Expression {
    /// Create a property access expression from a dotted path
    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
    }

    /// Parse a simple value expression
    pub fn parse_value(value: &str) -> Self {
        let trimmed = value.trim();

        // Check for boolean literals
        if trimmed == "true" {
            return Expression::Boolean(true);
        }
        if trimmed == "false" {
            return Expression::Boolean(false);
        }

        // Check for null
        if trimmed == "null" || trimmed == "NULL" {
            return Expression::Null;
        }

        // Check for numbers
        if let Ok(num) = trimmed.parse::<f64>() {
            return Expression::Number(num);
        }

        // Check for strings (quoted)
        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());
        }

        // Check for array literals
        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);
        }

        // Otherwise, treat as variable or path
        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() {
        // Boolean
        assert_eq!(Expression::parse_value("true"), Expression::Boolean(true));
        assert_eq!(Expression::parse_value("false"), Expression::Boolean(false));

        // Number
        assert_eq!(Expression::parse_value("42"), Expression::Number(42.0));
        assert_eq!(Expression::parse_value("3.14"), Expression::Number(3.14));

        // String
        assert_eq!(
            Expression::parse_value("\"hello\""),
            Expression::String("hello".to_string())
        );
        assert_eq!(
            Expression::parse_value("'world'"),
            Expression::String("world".to_string())
        );

        // Null
        assert_eq!(Expression::parse_value("null"), Expression::Null);

        // Variable
        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"),
        }
    }
}