summaryrefslogtreecommitdiff
path: root/src/parser.rs
blob: aff64f6918e7dfb98dfae13526ce4675b108de08 (plain)
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
use crate::lexer::*;
use crate::*;

use core::error::Error;
use std::fmt;

#[derive(Debug)]
pub struct ParseError {
    position: Position,
    what: String,
}

impl ParseError {
    pub fn new( position: Position, what: &str ) -> Self {
        ParseError {
            position,
            what: what.to_string(),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Error parsing input: {}", "yeah")
    }
}

impl Error for ParseError { }

pub type ParseResult<T> = Result<T, ParseError>;

struct Context<'a> {
    cur: [Option<Symbol<'a>>;2],
    icur: usize,
    ll: Lexer<'a>,
}

impl<'a> Context<'a> {
    pub fn new( mut ll: Lexer<'a> ) -> Self {
        let cur = [ll.next(), ll.next()];
        //println!(" - cur: {:?}, peek: {:?}", cur[0], cur[1] );
        Self {
            cur,
            icur: 0,
            ll
        }
    }
    
    pub fn next(&mut self) -> Option<Symbol<'a>> {
        self.cur[self.icur] = self.ll.next();
        self.icur = (self.icur+1)%2;
        //println!(" - cur: {:?}, peek: {:?}", self.cur(), self.peek() );
        self.cur[self.icur]
    }

    pub fn cur(&self) -> Option<Symbol<'a>> {
        self.cur[self.icur]
    }

    pub fn peek(&self) -> Option<Symbol<'a>> {
        self.cur[(self.icur+1)%2]
    }

    pub fn check_unwrapped<T: Fn( &SymbolType, &SymbolType ) -> bool>(&self, f: T) -> ParseResult<bool> {
        if self.cur().is_none() || self.peek().is_none() {
            Err(ParseError{
                position: Position::new(0,0),
                what: "Unexpected end of stream.".to_string()
            })
        } else  {
            Ok(f( self.cur().unwrap().symbol(), self.peek().unwrap().symbol()))
        }
    }
}

trait SymbolHelper {
    fn is<T: Fn( &SymbolType ) -> bool>(&self, f: T ) -> ParseResult<bool>;
    fn is_valid_tag_name(&self) -> ParseResult<bool>;
}

impl<'a> SymbolHelper for Option<Symbol<'a>> {
    fn is<T: Fn( &SymbolType ) -> bool>(&self, f: T ) -> ParseResult<bool> {
        if let Some(st) = self {
            Ok(f( &st.symbol() ))
        } else {
            Err(ParseError{
                position: Position::new(0,0),
                what: "Unexpected end of stream.".to_string()
            })
        }
    }
    
    fn is_valid_tag_name(&self) -> ParseResult<bool> {
        if let Some(st) = self {
            Ok(match st.symbol() {
                SymbolType::Token(_) |
                SymbolType::View |
                SymbolType::Output |
                SymbolType::Show => true,
                _ => false
            })
        } else {
            Err(ParseError{
                position: Position::new(0,0),
                what: "Unexpeceted end of stream.".to_string()
            })
        }
    }
}

pub struct Parser { 
}

/**
 * input: input tag
 *      | input tag_pair
 *      | input text
 *      |
 *      ;
 *
 * tag: '[|' tag_guts '|]'
 *    ;
 *
 * tag_pair: open_tag tag_body close_tag
 *         ;
 *
 * tag_body: tag_body tag
 *         | tag_body tag_pair
 *         | tag_body text
 *         |
 *         ;
 *
 * open_tag: '[|' tag_guts '|>'
 *         ;
 *
 * close_tag: '<|' token '|]'
 *          ;
 *
 * tag_guts: 'view' literal props
 *         | 'section' literal
 *         | 'output' literal
 *         ;
 *
 * literal: '"' [^"]* '"'
 *        ;
 *
 * props: props token '=' literal
 *      |
 *      ;
 *
 * disambiguate (tm):
 *
 * input: input tag
 *      | input text
 *      |
 *      ;
 *
 * tag: open_tag_base unary_tag
 *    | open_tag_base binary_tag
 *    ;
 *
 * open_tag_base: '[|' tag_guts
 *              ;
 *
 * unary_tag: '|]'
 *          ;
 *
 * binary_tag: '|>' tag_body close_tag
 *           ;
 *
 * tag_body: tag_body tag
 *         | tag_body text
 *         |
 *         ;
 *
 * close_tag: '<|' token '|]'
 *          ;
 *
 * tag_guts: 'view' literal props
 *         | 'section' literal
 *         | 'output' literal
 *         ;
 *
 * literal: '"' [^"]* '"'
 *        ;
 *
 * props: props token '=' literal
 *      |
 *      ;
 */
impl Parser {
    pub fn new() -> Self {
        Self {
        }
    }

    fn lex_error(&self, error: &Symbol) -> ParseResult<Token> {
        if let SymbolType::Error{what} = error.symbol() {
            Err(ParseError {
                position: error.start().clone(),
                what: format!("What: {:?}", *what)
            })
        } else {
            Err(ParseError {
                position: Position::new(0,0),
                what: "Not an error?".to_string(),
            })
        }
    }

    pub fn parse(&self, src: &str ) -> ParseResult<Token> {
        let ll = Lexer::new( src );
        let mut ctx = Context::new( ll );

        // Parse the root of the file, the input context
        self.p_input( &mut ctx )
    }

    fn p_input(&self, ctx: &mut Context ) -> ParseResult<Token> {
        let mut children = Vec::new();
        loop {
            if ctx.cur().is_none() {
                break;
            }
            match ctx.cur().unwrap().symbol() {
                SymbolType::Text(_) => { /* Skip top level text */ }
                SymbolType::StartFlat => {
                    children.push( self.parse_tag_view( ctx )? );
                }
                SymbolType::Error{..} => {
                    return self.lex_error( &ctx.cur().unwrap() );
                }
                _ => {

                }
            }
            ctx.next();
        }
        Ok(Token::Root(children))
    }

    fn parse_tag_view(&self, ctx: &mut Context) -> ParseResult<Token> {
        let mut tb = self.parse_open_tag( ctx )?;
        if !tb.is_name( &SymbolType::View ) {
            return Err(ParseError{
                position: tb.start_pos(),
                what: "Unexpected tag type, only frament allowed at root".to_string(),
            });
        }

        if tb.is_unary() {
            return tb.build();
        }
        let mut children = Vec::new();

        println!("--parse-tag-view-- tag parsed, next token: {:?}", ctx.cur() );
        loop {
            if ctx.cur().is_none() {
                return Err(ParseError{
                    position: Position::new(0,0),
                    what: "Unexpected end of stream.".to_string()
                });
            }
            match ctx.cur().unwrap().symbol() {
                SymbolType::Text(s) => {
                    children.push( Token::Text(s.to_string()) );
                    ctx.next();
                }
                SymbolType::StartFlat => {
                    //child.is_name(SymbolType::Output)
                    children.push( self.parse_tag_body( ctx )? );
                }
                SymbolType::StartPoint => {
                    let end = self.parse_end_tag( ctx )?;
                    println!("End tag: {:?}, open tag: {:?}", end, tb.name() );
                    if tb.is_name(end.symbol()) {
                        // They match, time to decide what we're doing.
                        let any_outputs = children.iter().any(
                            |t| matches!(t, Token::Output(..))
                            );
                        if children.iter().all(|t| matches!(t, Token::Text(..)) || matches!(t, Token::Output(..))) {
                            // Everything is either text or output
                            if !any_outputs {
                                // Special case, if it's only text then we create an implicit output.
                                tb.add_child(Token::Output("content".to_string(), Properties::new(), children ));
                            }
                            else {
                                // Standard case, outputs are included, text is
                                // skipped.
                                for token in children {
                                    if matches!(token, Token::Output(..)) {
                                        tb.add_child( token );
                                    }
                                }
                            }
                        } else {
                            // We have another mix, now check to see if there
                            // are any outptus, if so this is an error.
                            if any_outputs {
                                return Err(ParseError{
                                    position: *end.start(),
                                    what: "You cannot mix non-output and output tags in a view.".to_string()
                                });
                            } else {
                                // No outputs at all, we create an implict output
                                tb.add_child(Token::Output("content".to_string(), Properties::new(), children ));
                            }
                        }

                        return tb.build();
                    } else {
                        // They don't match, complain.
                        return Err(ParseError{
                            position: *end.start(),
                            what: "Mismatched open and closing tags.".to_string()
                        });
                    }
                }
                SymbolType::Error{..} => {
                    return self.lex_error( &ctx.cur().unwrap() );
                }
                _ => {
                    ctx.next();
                }
            }
        }
    }

    fn parse_open_tag<'a>(&self, ctx: &mut Context<'a>) -> ParseResult<TagBuilder<'a>> {
        
        println!("--> Begin parse_tag <--");

        let start_sym = ctx.cur().unwrap();
        let mut tb = TagBuilder::new(&start_sym);

        println!("--> Start sym: {:?}", start_sym );

        if ctx.next().is_some() {
            match ctx.cur().unwrap().symbol() {
                SymbolType::View | SymbolType::Show |
                SymbolType::Output => {
                    let name_sym = ctx.cur().unwrap();
                    ctx.next();
                    tb.set_name( name_sym );
                }
                _ => {
                    return Err(ParseError{position: ctx.cur().unwrap().start().clone(), what: "Unexpecetd symbol".to_string()});
                }
            }
        } else {
            return Err(ParseError{position: Position::new(0,0), what: "Unexpecetd end of stream".to_string()});
        }

        self.parse_tag_params( ctx, &mut tb )?;
        self.parse_tag_props( ctx, &mut tb )?;

        if let Some(end_sym) = ctx.cur() {
            match end_sym.symbol() {
                SymbolType::EndPoint => {
                    tb.set_type( TagType::BinaryOpen );
                }
                SymbolType::EndFlat => {
                    tb.set_type( TagType::Unary );
                }
                _ => {
                    return Err(ParseError{position: Position::new(0,0), what: "Unexpecetd end of stream".to_string()});
                }
            }
        }

        ctx.next();

        Ok(tb)
    }

    fn parse_end_tag<'a>(&self, ctx: &mut Context<'a> ) -> ParseResult<Symbol<'a>> {
        if !ctx.cur().is(|s| *s == SymbolType::StartPoint )? {
            return Err(ParseError{
                position: *ctx.cur().unwrap().start(),
                what: "Invalid end tag?".to_string(),
            });
        }
        if !ctx.next().is_valid_tag_name()? {
            return Err(ParseError{
                position: *ctx.cur().unwrap().start(),
                what: "Invalid tag name".to_string(),
            });
        }
        let name = ctx.cur().unwrap();
        if !ctx.next().is(|s| *s == SymbolType::EndFlat )? {
            return Err(ParseError{
                position: *ctx.cur().unwrap().start(),
                what: "Tag should be <| |] style end tag.".to_string(),
            });
        }
        Ok(name)
    }

    fn parse_tag_body(&self, ctx: &mut Context ) -> ParseResult<Token> {
        let mut tb = self.parse_open_tag( ctx )?;
        if tb.is_unary() {
            return tb.build();
        }

        loop {
            if ctx.cur().is_none() {
                return Err(ParseError{position: Position::new(0,0), what: "Unexpecetd end of stream".to_string()});
            }
            match ctx.cur().unwrap().symbol() {
                SymbolType::Text(s) => {
                    tb.add_child(Token:: Text(s.to_string()));
                    ctx.next();
                }
                SymbolType::StartFlat => {
                    tb.add_child( self.parse_tag_body( ctx )? );
                    println!("Following tag body: {:?} {:?}", ctx.cur(), ctx.peek() );
                }
                SymbolType::StartPoint => {
                    let end = self.parse_end_tag( ctx )?;
                    println!("End tag: {:?}, open tag: {:?}", end, tb.name() );
                    if tb.is_name(end.symbol()) {
                        // They match, end.
                        return tb.build();
                    } else {
                        // They don't match, complain.
                        return Err(ParseError{
                            position: *end.start(),
                            what: "Mismatched open and closing tags.".to_string()
                        });
                    }
                }
                SymbolType::Error{..} => {
                    self.lex_error( &ctx.cur().unwrap() )?;
                }
                _ => {

                }
            }
        }
    }

    fn parse_tag_params(&self, ctx: &mut Context, tb: &mut TagBuilder ) -> ParseResult<()> {
        loop {
            if ctx.cur().is_none() {

                return Err(ParseError{position: Position::new(0,0), what: "Unexpecetd end of stream".to_string()});
            }
            match ctx.cur().unwrap().symbol() {
                SymbolType::Literal(s) => {
                    tb.add_param( s.to_string() );
                }
                _ => {
                    break;
                }
            }
            ctx.next();
        }
        Ok(())
    }
    
    fn parse_tag_props(&self, ctx: &mut Context, tb: &mut TagBuilder ) -> ParseResult<()> {
        loop {
            if ctx.cur().is_none() {
                return Err(ParseError{position: Position::new(0,0), what: "Unexpecetd end of stream".to_string()});
            }
            if let SymbolType::Token(s) = ctx.cur().unwrap().symbol() {
                if ctx.peek().is_some_and(|s|s.check_type(|t| matches!(t,SymbolType::Equals))) {
                    ctx.next();
                    if let Some(sym) = ctx.next() &&
                        let SymbolType::Literal(lv) = sym.symbol() {
                        tb.add_prop( s.to_string(), lv.to_string() );
                    } else {
                        return Err(ParseError{position: Position::new(0,0), what: "Expected quoted literal string".to_string()});
                    }
                } else {
                    return Err(ParseError{position:Position::new(0,0), what: "Expected = ".to_string()});
                }
            } else {
                break;
            }
            ctx.next();
        }
        Ok(())
    }
}

#[derive(PartialEq,Copy,Clone,Debug)]
enum TagType {
    Unknown,
    Unary,
    BinaryOpen,
    BinaryClose,
}

struct TagBuilder<'a> {
    name: Option<Symbol<'a>>,
    params: Vec<String>,
    props: Properties,
    children: Vec<Token>,
    tag_type: TagType,
    start_pos: Position,
}

impl<'a> TagBuilder<'a> {
    pub fn new(start: &Symbol) -> TagBuilder<'a> {
        TagBuilder {
            name: None,
            params: Vec::new(),
            props: Properties::new(),
            children: Vec::new(),
            tag_type: TagType::Unknown,
            start_pos: *start.start(),
        }
    }

    pub fn start_pos(&self) -> Position {
        self.start_pos
    }

    pub fn is_unary(&self) -> bool {
        if self.tag_type == TagType::Unary {
            true
        } else {
            false
        }
    }

    pub fn can_have_children(&self) -> bool {
        if self.tag_type == TagType::BinaryOpen {
            true
        } else {
            false
        }
    }

    pub fn is_name(&self, name: &SymbolType<'a>) -> bool {
        if let Some(a) = self.name {
            a.symbol() == name
        } else {
            false
        }
    }

    pub fn name(&self) -> Option<Symbol<'a>> {
        self.name
    }

    pub fn set_name(&mut self, name: Symbol<'a>) {
        self.name = Some(name);
        println!("Tag name: {:?}", self.name );
    }

    pub fn add_param(&mut self, param: String) {
        println!("Add param: {:?}", param );
        self.params.push( param );
    }

    pub fn add_prop(&mut self, key: String, value: String) {
        println!("Add prop: {:?} = {:?}", key, value );
        self.props.insert( key, value );
    }

    pub fn add_child(&mut self, token: Token) {
        self.children.push( token );
    }

    pub fn append_children(&mut self, children: &mut Vec::<Token>) {
        self.children.append( children );
    }

    pub fn set_type(&mut self, tag_type: TagType) {
        self.tag_type = tag_type;
    }

    pub fn tag_type(&self) -> TagType {
        self.tag_type
    }

    pub fn build(mut self) -> ParseResult<Token> {
        if let Some(sym) = self.name {
            match sym.symbol() {
                SymbolType::View => {
                    Ok(Token::View(self.params.swap_remove(0), self.props, self.children))
                }
                SymbolType::Output => {
                    Ok(Token::Output(self.params.swap_remove(0), self.props, self.children))
                }
                SymbolType::Show => {
                    Ok(Token::Show(self.params.swap_remove(0), self.props))
                }
                _ => {
                    println!("Unkown tag type");
                    Err(ParseError {
                        position: self.start_pos,
                        what: "Bad tag type".to_string(),
                    })
                }
            }
        } else {
                    Err(ParseError {
                        position: self.start_pos,
                        what: "Bad tag type".to_string(),
                    })
        }
    }
}