taitan-orm-parser 0.1.10

Next Generation ORM based on sqlx
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
use crate::template_parser::to_sql::{SqlSegment, ToSqlSegment};
use nom::{
    branch::alt,
    bytes::complete::{tag, take_until},
    character::complete::multispace0,
    combinator::{map, opt},
    sequence::delimited,
    IResult,
};
use std::fmt::Display;

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Modifier {
    Plus,
    Minus,
    Tilde,
}
impl Display for Modifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Modifier::Plus => write!(f, "+"),
            Modifier::Minus => write!(f, "-"),
            Modifier::Tilde => write!(f, "~"),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct EndBlock {
    pub name: String,
    pub start_modifier: Option<Modifier>,
    pub end_modifier: Option<Modifier>,
}

impl Display for EndBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let start_modifier_str = if let Some(start_modifier) = &self.start_modifier {
            start_modifier.to_string()
        } else {
            "".to_string()
        };
        let end_modifier_str = if let Some(end_modifier) = &self.end_modifier {
            end_modifier.to_string()
        } else {
            "".to_string()
        };
        write!(
            f,
            "{{%{} {} {}%}}",
            start_modifier_str, self.name, end_modifier_str
        )
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct StartBlock {
    pub name: String,
    pub start_modifier: Option<Modifier>,
    pub end_modifier: Option<Modifier>,
    pub expr: String,
}

impl Display for StartBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let start_modifier_str = if let Some(start_modifier) = &self.start_modifier {
            start_modifier.to_string()
        } else {
            "".to_string()
        };
        let end_modifier_str = if let Some(end_modifier) = &self.end_modifier {
            end_modifier.to_string()
        } else {
            "".to_string()
        };
        write!(
            f,
            "{{%{} {} {} {}%}}",
            start_modifier_str, self.name, self.expr, end_modifier_str
        )
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum TemplatePart {
    Expression(String), // {{ }} 表达式及其过滤器
    ControlBlock {
        start_block: StartBlock,
        content: String,
        end_block: EndBlock,
    }, // {% %} 控制块,包括macro
    Call(String),       // {% call %} call 语句
    Comment(String),    // {# #}注释块
}

impl Display for TemplatePart {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TemplatePart::ControlBlock {
                start_block,
                content,
                end_block,
            } => {
                write!(f, "{}{}{}", start_block, content, end_block)
            }
            TemplatePart::Expression(expression) => {
                write!(f, "{{ {} }}", expression)
            }
            TemplatePart::Call(call_expr) => {
                write!(f, "{{% call {} %}}", call_expr)
            }
            TemplatePart::Comment(comment) => write!(f, ""),
        }
    }
}

impl TemplatePart {
    pub fn parse(input: &str) -> IResult<&str, TemplatePart> {
        let (input, part) = delimited(
            multispace0,
            alt((
                map(parse_call, |part| part),
                map(parse_comment, |part| part),
                map(parse_expression, |part| part),
                map(parse_control_block, |part| part),
            )),
            multispace0,
        )(input)?;
        Ok((input, part))
    }
}

fn parse_expression(input: &str) -> IResult<&str, TemplatePart> {
    let (input, _) = tag("{{")(input)?;
    let (input, expr) = take_until("}}")(input)?;
    let (input, _) = tag("}}")(input)?;
    Ok((input, TemplatePart::Expression(expr.trim().to_string())))
}

// 辅助函数:生成一个解析器,该解析器可以识别并消耗特定的结束标记
fn take_until_and_consume<F, R>(parser: F) -> impl Fn(&str) -> IResult<&str, String>
where
    F: Fn(&str) -> IResult<&str, R>,
{
    move |input: &str| {
        let mut buffer = String::new();
        let mut remaining = input;

        loop {
            match parser(remaining) {
                Ok((_, _)) => {
                    // 找到了结束标记,停止循环
                    break;
                }
                Err(_) => {
                    if remaining.is_empty() {
                        // 如果没有剩余输入且未找到结束标记,返回错误
                        return Err(nom::Err::Error(nom::error::Error::new(
                            input,
                            nom::error::ErrorKind::TakeUntil,
                        )));
                    }

                    // 将当前字符添加到缓冲区并继续
                    buffer.push(remaining.chars().next().unwrap());
                    remaining = &remaining[1..];
                }
            }
        }
        Ok((remaining, buffer))
    }
}
fn parse_modifier(input: &str) -> IResult<&str, Modifier> {
    let (input, modifier_str) = alt((tag("+"), tag("-"), tag("~")))(input)?;
    let modifier = match modifier_str {
        "+" => Modifier::Plus,
        "-" => Modifier::Minus,
        "~" => Modifier::Tilde,
        _ => unreachable!(),
    };
    Ok((input, modifier))
}

fn parse_start_brace(input: &str) -> IResult<&str, Option<Modifier>> {
    let (input, _) = tag("{%")(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, modifier) = opt(parse_modifier)(input)?;
    Ok((input, modifier))
}

fn parse_end_brace(input: &str) -> IResult<&str, Option<Modifier>> {
    let (input, modifier) = opt(parse_modifier)(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, _) = tag("%}")(input)?;
    Ok((input, modifier))
}

fn parse_start_block_with_name<'a>(
    input: &'a str,
    block_name: &'static str,
) -> IResult<&'a str, StartBlock> {
    let (input, start_modifier) = parse_start_brace(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, parsed_block_name) = tag(block_name)(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, expr) = take_until_and_consume(parse_end_brace)(input)?; // 表达式可以包含任意字符
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, end_modifier) = parse_end_brace(input)?; // 解析可能的结束修饰符

    Ok((
        input,
        StartBlock {
            name: parsed_block_name.to_string(),
            start_modifier,
            end_modifier,
            expr: expr.trim().to_string(),
        },
    ))
}

fn parse_start_block(input: &str) -> IResult<&str, StartBlock> {
    alt((
        |i| parse_start_block_with_name(i, "if"),
        |i| parse_start_block_with_name(i, "match"),
        |i| parse_start_block_with_name(i, "for"),
        |i| parse_start_block_with_name(i, "macro"),
        |i| parse_start_block_with_name(i, "filter"),
        |i| parse_start_block_with_name(i, "block"),
    ))(input)
}

fn parse_end_block_with_name<'a>(
    input: &'a str,
    block_name: &'static str,
) -> IResult<&'a str, EndBlock> {
    let (input, start_modifier) = parse_start_brace(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, _) = tag(block_name)(input)?;
    let (input, _) = multispace0(input)?; // 允许空格
    let (input, end_modifier) = parse_end_brace(input)?; // 表达式可以包含任意字符
    Ok((
        input,
        EndBlock {
            name: block_name.to_string(),
            start_modifier,
            end_modifier,
        },
    ))
}

fn parse_end_block(input: &str) -> IResult<&str, EndBlock> {
    alt((
        |i| parse_end_block_with_name(i, "endif"),
        |i| parse_end_block_with_name(i, "endmatch"),
        |i| parse_end_block_with_name(i, "endfor"),
        |i| parse_end_block_with_name(i, "endmacro"),
        |i| parse_end_block_with_name(i, "endfilter"),
        |i| parse_end_block_with_name(i, "endblock"),
    ))(input)
}

fn parse_control_block(input: &str) -> IResult<&str, TemplatePart> {
    // 解析控制块开始标记
    let (input, start_block) = parse_start_block(input)?;

    let (input, control_content) = take_until_and_consume(parse_end_block)(input)?;

    let (input, end_block) = parse_end_block(input)?;

    Ok((
        input,
        TemplatePart::ControlBlock {
            start_block,
            content: control_content.trim().to_string(),
            end_block,
        },
    ))
}

fn parse_call(input: &str) -> IResult<&str, TemplatePart> {
    let (input, _) = tag("{% call ")(input)?;
    let (input, expr) = take_until("%}")(input)?;
    let (input, _) = tag("%}")(input)?;
    Ok((input, TemplatePart::Call(expr.trim().to_string())))
}

fn parse_comment(input: &str) -> IResult<&str, TemplatePart> {
    let (input, _) = tag("{#")(input)?;
    let (input, comment) = take_until("#}")(input)?;
    let (input, _) = tag("#}")(input)?;
    Ok((input, TemplatePart::Comment(comment.to_string())))
}

// fn parse_template_part(input: &str) -> IResult<&str, TemplatePart> {
//     let (input, part) = delimited(
//         multispace0,
//         alt((
//             map(parse_call, |part| part),
//             map(parse_comment, |part| part),
//             map(parse_expression, |part| part),
//             map(parse_control_block, |part| part),
//         )),
//         multispace0,
//     )(input)?;
//     Ok((input, part))
// }

// fn parse_template(input: &str) -> IResult<&str, Vec<TemplatePart>> {
//     many0(parse_template_part)(input)
// }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_end_brace() {
        let template = "%}";
        let (remaining, end_block) = parse_end_brace(template).unwrap();
        assert_eq!(end_block, None);

        let template = "- %}";
        let (remaining, end_block) = parse_end_brace(template).unwrap();
        assert_eq!(end_block, Some(Modifier::Minus));

        let template = "~ %}";
        let (remaining, end_block) = parse_end_brace(template).unwrap();
        assert_eq!(end_block, Some(Modifier::Tilde));
    }

    #[test]
    fn test_parse_start_block() {
        let template = r#"{% if active %}"#;
        let (remaining, parsed) = parse_start_block(template).unwrap();
        let expected = StartBlock {
            name: "if".to_string(),
            start_modifier: None,
            end_modifier: None,
            expr: "active".to_string(),
        };
        assert_eq!(expected, parsed);
        let template = r#"{%~ for active set as test -%}"#;
        let (remaining, parsed) = parse_start_block(template).unwrap();
        let expected = StartBlock {
            name: "for".to_string(),
            start_modifier: Some(Modifier::Tilde),
            end_modifier: Some(Modifier::Minus),
            expr: "active set as test".to_string(),
        };
        assert_eq!(expected, parsed);
    }

    #[test]
    fn test_parse_end_block() {
        let template = r#"{% endif %}"#;
        let (remaining, parsed) = parse_end_block(template).unwrap();
        assert_eq!(
            parsed,
            EndBlock {
                name: String::from("endif"),
                start_modifier: None,
                end_modifier: None
            }
        );

        let template = r#"{% if active %}
            You are active.
        {% endif -%}"#;
        let (remaining, _) = parse_start_block(template).unwrap();
        assert_eq!(
            remaining,
            "\n            You are active.\n        {% endif -%}"
        );
        let (remaining, parsed) = take_until_and_consume(parse_end_block)(remaining).unwrap();
        assert_eq!(parsed, "\n            You are active.\n        ");
    }

    #[test]
    fn test_parse_template_part() {
        let template = r#"{{ name | capitalize }}"#;
        let (remaining, parsed_template_parts) = TemplatePart::parse(template).unwrap();
        let expected = TemplatePart::Expression("name | capitalize".to_string());
        assert_eq!(parsed_template_parts, expected);

        let template = r#"{% if active %}
            You are active.
        {% endif -%}"#;
        let (remaining, parsed_template_parts) = TemplatePart::parse(template).unwrap();
        let expected = TemplatePart::ControlBlock {
            start_block: StartBlock {
                name: "if".to_string(),
                start_modifier: None,
                end_modifier: None,
                expr: "active".to_string(),
            },
            content: "You are active.".to_string(),
            end_block: EndBlock {
                name: "endif".to_string(),
                start_modifier: None,
                end_modifier: Some(Modifier::Minus),
            },
        };
        assert_eq!(parsed_template_parts, expected);

        let template = r#"
        {% for item in items %}
            Item: {{ item | upper }}
        {% endfor %}"#;
        let (remaining, parsed_template_parts) = TemplatePart::parse(template).unwrap();
        let expected = TemplatePart::ControlBlock {
            start_block: StartBlock {
                name: "for".to_string(),
                start_modifier: None,
                end_modifier: None,
                expr: "item in items".to_string(),
            },
            content: "Item: {{ item | upper }}".to_string(),
            end_block: EndBlock {
                name: "endfor".to_string(),
                start_modifier: None,
                end_modifier: None,
            },
        };
        assert_eq!(parsed_template_parts, expected);

        let template = r#"{% call macro %}"#;
        let (remaining, parsed_template_parts) = TemplatePart::parse(template).unwrap();
        let expected = TemplatePart::Call("macro".to_string());
        assert_eq!(parsed_template_parts, expected);

        let template = r#"
        {# This is a comment #}"#;
        let (remaining, parsed_template_parts) = TemplatePart::parse(template).unwrap();
        let expected = TemplatePart::Comment(" This is a comment ".to_string());
        assert_eq!(parsed_template_parts, expected);
    }
}