summaryrefslogtreecommitdiff
path: root/src/parser.rs
blob: 54b77acc20621fc1942b53d6fcb114f5b84d3dcc (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
use crate::lexer::*;
use crate::*;

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

#[derive(Debug)]
struct ParseError {
    line: u32,
    row: u32,
    what: 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 { }

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()];
        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 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: 'fragment' 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: 'fragment' literal props
 *         | 'section' literal
 *         | 'output' literal
 *         ;
 *
 * literal: '"' [^"]* '"'
 *        ;
 *
 * props: props token '=' literal
 *      |
 *      ;
 */
impl Parser {
    pub fn new() -> Self {
        Self {
        }
    }

    fn lex_error(&self, error: &Symbol) -> Result<(),Box<dyn Error>> {
        if let Symbol::Error{line,row,what} = error {
            Err(Box::new(ParseError {
                line: *line,
                row: *row,
                what: format!("What: {:?}", *what)
            }))
        } else {
            Err(Box::new(ParseError {
                line: 0, row: 0, what: "Not an error?".to_string()
            }))
        }
    }

    pub fn parse(&mut self, crim: &mut Crimtag, src: &str ) -> Result<(),Box<dyn Error>> {
        let mut ll = Lexer::new( src );
        let mut ctx = Context::new( ll );

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

        Ok(())
    }

    fn p_input(&mut self, ctx: &mut Context ) -> Result<(), Box<dyn Error>> {
        loop {
            if ctx.cur().is_none() {
                break;
            }
            match ctx.cur() {
                Some(Symbol::Text(_)) => { /* Skip top level text */ }
                Some(Symbol::StartFlat) => {
                    self.parse_tag( ctx );
                }
                Some(Symbol::Error{..}) => {
                    return self.lex_error( &ctx.cur().unwrap() );
                }
                _ => {

                }
            }
            ctx.next();
        }
        Ok(())
    }

    fn parse_tag(&mut self, ctx: &mut Context) -> Result<(), Box<dyn Error>> {
        let mut tb = TagBuilder::new();

        let start_sym = ctx.cur().unwrap();

        if let Some(Symbol::Token(s)) = ctx.next() {
            tb.set_name( s.to_string() );
        } else {
            return Err(Box::new(ParseError{line: 0, row: 0, what: "Unexpecetd symbol".to_string()}));
        }

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

        Ok(())
    }

    fn parse_tag_params(&mut self, ctx: &mut Context, tb: &mut TagBuilder ) -> Result<(), Box<dyn Error>> {
        loop {
            if let Some(Symbol::Token(s)) = ctx.cur() {
                if matches!(ctx.peek(), Some(Symbol::Equals)) {
                    // Done with parameters
                    break;
                }
                else {
                    tb.add_param( s.to_string() );
                }
            }
            ctx.next();
        }
        Ok(())
    }
    
    fn parse_tag_props(&mut self, ctx: &mut Context, tb: &mut TagBuilder ) -> Result<(), Box<dyn Error>> {
        loop {
            if let Some(Symbol::Token(s)) = ctx.cur() {
                if matches!(ctx.peek(), Some(Symbol::Equals)) {
                    ctx.next();
                    if let Some(Symbol::Literal(lv)) = ctx.next() {
                        tb.add_prop( s.to_string(), lv.to_string() );
                    } else {
                        return Err(Box::new(ParseError{line: 0, row: 0, what: "Expected quoted literal string".to_string()}));
                    }
                } else {
                    return Err(Box::new(ParseError{line: 0, row: 0, what: "Expected = ".to_string()}));
                }
            } else {
                break;
            }
            ctx.next();
        }
        Ok(())
    }
}

enum TagType {
    Unknown,
    Unary,
    BinaryOpen,
    BinaryClose,
}

struct TagBuilder {
    name: String,
    params: Vec<String>,
    props: Vec<(String,String)>,
    tag_type: TagType,
}

impl TagBuilder {
    pub fn new() -> TagBuilder {
        TagBuilder {
            name: String::new(),
            params: Vec::new(),
            props: Vec::new(),
            tag_type: TagType::Unknown,
        }
    }

    pub fn set_name(&mut self, name: String) {
        self.name = name;
    }

    pub fn add_param(&mut self, param: String) {
        self.params.push( param );
    }

    pub fn add_prop(&mut self, key: String, value: String) {
        self.props.push( (key, value) );
    }

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