nom-lua 0.0.2

Lua 5.3 parser written in nom
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
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
607
608
// Copyright 2017 The nom-lua project developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt;
use std::fmt::{Debug, Display, Formatter};

#[derive(Clone, PartialEq)]
pub enum ASTNode {
    Integer(i64),
    Float(f64),
    Bool(bool),
    String(String),
    Label(String),
    Name(String),
    Paren(Box<ASTNode>),

    Block(Vec<ASTNode>, Box<Option<ASTNode>>),

    //Statements
    EmptyStatement,
    Break,
    Goto(Box<ASTNode>),
    RetStat(Box<Option<ASTNode>>),

    // ArithmeticOps
    Add(Box<ASTNode>, Box<ASTNode>),
    Sub(Box<ASTNode>, Box<ASTNode>),
    Mul(Box<ASTNode>, Box<ASTNode>),
    Div(Box<ASTNode>, Box<ASTNode>),
    Exp(Box<ASTNode>, Box<ASTNode>),
    FDiv(Box<ASTNode>, Box<ASTNode>),
    Mod(Box<ASTNode>, Box<ASTNode>),

    // LogicOps
    And(Box<ASTNode>, Box<ASTNode>),
    Or(Box<ASTNode>, Box<ASTNode>),

    // RelationalOps
    Lt(Box<ASTNode>, Box<ASTNode>),
    Le(Box<ASTNode>, Box<ASTNode>),
    Gt(Box<ASTNode>, Box<ASTNode>),
    Ge(Box<ASTNode>, Box<ASTNode>),
    Eq(Box<ASTNode>, Box<ASTNode>),
    Ne(Box<ASTNode>, Box<ASTNode>),

    // BinaryOps
    BitOr(Box<ASTNode>, Box<ASTNode>),
    BitAnd(Box<ASTNode>, Box<ASTNode>),
    BitXor(Box<ASTNode>, Box<ASTNode>),
    Rsh(Box<ASTNode>, Box<ASTNode>),
    Lsh(Box<ASTNode>, Box<ASTNode>),

    // UnaryOps
    BinNot(Box<ASTNode>),
    Not(Box<ASTNode>),
    Len(Box<ASTNode>),
    UMin(Box<ASTNode>),

    // ConcatenationOps
    Concat(Box<ASTNode>, Box<ASTNode>),

    // Expression
    /// Takes one of
    /// Var
    /// FunctionCall
    /// Exp
    PrefixExp(Box<ASTNode>),

    Nil,
    VarArg,
    TableConstructor(Box<Option<ASTNode>>),

    // Function
    /// Takes a FunctionBody
    Function(Box<ASTNode>),
    /// Takes a ParameterList and a Block
    FunctionBody(Box<Option<ASTNode>>, Box<ASTNode>),
    /// Has 3 parameters
    /// the example: log.ms:al
    /// would produce
    /// Name log
    /// Name ms
    /// Name al
    FunctionName(Box<ASTNode>, Option<Vec<ASTNode>>, Option<Box<ASTNode>>),
    /// Takes a Name and a FunctionBody
    NamedFunction(Box<ASTNode>, Box<ASTNode>),

    // Lists
    ExpList(Vec<ASTNode>),
    VarList(Vec<ASTNode>),
    NameList(Vec<ASTNode>),
    FieldList(Vec<ASTNode>),
    /// Takes a list of parameters and is vararg
    ParameterList(Box<Option<ASTNode>>, bool),

    // Field
    /// Contains an expr
    FieldSingle(Box<ASTNode>),
    /// The first node may be an expr to be resolved or a Name
    /// The second node is the assigned expr
    FieldAssign(Box<ASTNode>, Box<ASTNode>),

    // Local
    Local(Box<ASTNode>),

    // Var
    /// Takes a Name
    Var(Box<ASTNode>),
    /// Takes a prefixexp and a exp
    VarPrefixed(Box<ASTNode>, Box<ASTNode>),
    /// Takes a prefixexp and a Name
    VarListAccess(Box<ASTNode>, Box<ASTNode>),
}

impl Debug for ASTNode {
    fn fmt(&self, format: &mut Formatter) -> fmt::Result {
        use self::ASTNode::*;
        match *self {
            Integer(val) => write!(format, "{}", val),
            Float(val) => write!(format, "{}f", val),
            Bool(val) => write!(format, "{}", val),
            String(ref val) => write!(format, "\"{}\"", val),

            /// Holds a lua name, usually a function or variable name
            /// Contains `ASTNode::String`
            Name(ref val) => write!(format, "(name {})", val),

            /// Holds a lua label name
            /// Contains `ASTNode::Name`
            Label(ref val) => write!(format, "::{}::", val),
            /// Contains an expression
            Paren(ref expr) => write!(format, "({})", expr),

            // Block
            Block(ref statements, ref retstat) => {
                write!(format, "(block\n");
                for e in statements.iter() {
                    write!(format, "\t{}\n", e);
                }
                if let Some(ref ret_ast) = **retstat {
                    write!(format, "\treturn {}\n", ret_ast);
                }
                write!(format, ")")
            }

            // Statements
            EmptyStatement => write!(format, "(statement)"),
            RetStat(ref para) => write!(format, "(ret {:?})", para),
            Break => write!(format, "(break)"),
            Goto(ref loc) => write!(format, "goto {}", loc),

            // ArithmeticOps
            Add(ref left, ref right) => write!(format, "({} + {})", left, right),
            Sub(ref left, ref right) => write!(format, "({} - {})", left, right),
            Mul(ref left, ref right) => write!(format, "({} * {})", left, right),
            Div(ref left, ref right) => write!(format, "({} / {})", left, right),
            Exp(ref left, ref right) => write!(format, "({} ^ {})", left, right),
            FDiv(ref left, ref right) => write!(format, "({} // {})", left, right),
            Mod(ref left, ref right) => write!(format, "({} % {})", left, right),

            // LogicOps
            And(ref left, ref right) => write!(format, "({} and {})", left, right),
            Or(ref left, ref right) => write!(format, "({} or {})", left, right),

            // ArithmeticOps
            Lt(ref left, ref right) => write!(format, "({} < {})", left, right),
            Le(ref left, ref right) => write!(format, "({} <= {})", left, right),
            Gt(ref left, ref right) => write!(format, "({} > {})", left, right),
            Ge(ref left, ref right) => write!(format, "({} >= {})", left, right),
            Eq(ref left, ref right) => write!(format, "({} == {})", left, right),
            Ne(ref left, ref right) => write!(format, "({} ~= {})", left, right),

            // BinaryOps
            BitAnd(ref left, ref right) => write!(format, "({} & {})", left, right),
            BitOr(ref left, ref right) => write!(format, "({} | {})", left, right),
            BitXor(ref left, ref right) => write!(format, "({} ~ {})", left, right),
            Rsh(ref left, ref right) => write!(format, "({} >> {})", left, right),
            Lsh(ref left, ref right) => write!(format, "({} << {})", left, right),

            // UnaryOps
            BinNot(ref right) => write!(format, "~{}", right),
            Len(ref right) => write!(format, "#{}", right),
            UMin(ref right) => write!(format, "-{}", right),
            Not(ref right) => write!(format, "not {}", right),

            // ConcatenationOps
            Concat(ref left, ref right) => write!(format, "{} .. {}", left, right),

            // Exp
            PrefixExp(ref e) => write!(format, "{}", e),

            Nil => write!(format, "nil"),
            VarArg => write!(format, "..."),
            //TODO: Remove this debug impl
            TableConstructor(ref fieldlist) => write!(format, "{{ {:?} }}", fieldlist),

            // Function
            Function(ref f) => write!(format, "{}", f),
            FunctionBody(ref parlist, ref fbody) => write!(format, "function ({:?}) {}", parlist, fbody),
            FunctionName(ref n, ref m, ref f) => write!(format, "{}.{:?}:{:?}", n, m, f),
            NamedFunction(ref n, ref f) => write!(format, "(named {} {})", n, f),

            // Lists
            ExpList(ref explist) => {
                write!(format, "(explist\n");
                for e in explist.iter() {
                    write!(format, "\t{}\n", e);
                }
                write!(format, ")")
            },
            VarList(ref varlist) => {
                write!(format, "(varlist\n");
                for e in varlist.iter() {
                    write!(format, "\t{}\n", e);
                }
                write!(format, ")")
            },
            NameList(ref namelist) => {
                write!(format, "(namelist\n");
                for e in namelist.iter() {
                    write!(format, "\t{}\n", e);
                }
                write!(format, ")")
            },
            ParameterList(ref plist, ref va) => {
                write!(format, "(paramlist\n");
                for e in plist.iter() {
                    write!(format, "\t{}\n", e);
                }
                if *va {
                    write!(format, "\t...\n");
                }
                write!(format, ")")
            },
            FieldList(ref fieldlist) => {
                write!(format, "(fieldlist\n");
                for e in fieldlist.iter() {
                    write!(format, "\t{}\n", e);
                }
                write!(format, ")")
            },

            // Field
            FieldSingle(ref e) => write!(format, "(field {})", e),
            FieldAssign(ref n, ref e) => write!(format, "(field {} => {})", n, e),

            //Local
            Local(ref inner) => write!(format, "local {}", inner),

            //Var
            Var(ref name) => write!(format, "(var {})", name),
            VarPrefixed(ref pe, ref e) => write!(format, "{}[{}]", pe, e),
            VarListAccess(ref pe, ref n) => write!(format, "{}.{}", pe, n)
        }
    }

}

impl Display for ASTNode {
    fn fmt(&self, format: &mut Formatter) -> fmt::Result {
        use ASTNode::*;
        match *self {
            //TODO: Check if the DOT format supports ()
            Integer(a) => write!(format, "Integer_{}_", a),
            Float(a) => write!(format, "Float_{}_", a),
            Bool(a) => write!(format, "Bool_{}_", a),
            // Dot does not allow spaces and a bunch of things in the names
            // we should change some of this stuff
            String(ref a) => write!(format, "String_{}_", a),
            Label(ref a) => write!(format, "Label_{}_", a),
            Name(ref a) => write!(format, "Name_{}_", a),
            Paren(_) => write!(format, "Paren"),
            Block(_, _) => write!(format, "Block"),
            EmptyStatement => write!(format, "EmptyStatement"),
            Break => write!(format, "Break"),
            Goto(_) => write!(format, "Goto"),
            RetStat(_) => write!(format, "RetStat"),
            Add(_, _) => write!(format, "Add"),
            Sub(_, _) => write!(format, "Sub"),
            Mul(_, _) => write!(format, "Mul"),
            Div(_, _) => write!(format, "Div"),
            Exp(_, _) => write!(format, "Exp"),
            FDiv(_, _) => write!(format, "FDiv"),
            Mod(_, _) => write!(format, "Mod"),
            And(_, _) => write!(format, "And"),
            Or(_, _) => write!(format, "Or"),
            Lt(_, _) => write!(format, "Lt"),
            Le(_, _) => write!(format, "Le"),
            Gt(_, _) => write!(format, "Gt"),
            Ge(_, _) => write!(format, "Ge"),
            Eq(_, _) => write!(format, "Eq"),
            Ne(_, _) => write!(format, "Ne"),
            BitOr(_, _) => write!(format, "BitOr"),
            BitAnd(_, _) => write!(format, "BitAnd"),
            BitXor(_, _) => write!(format, "BitXor"),
            Rsh(_, _) => write!(format, "Rsh"),
            Lsh(_, _) => write!(format, "Lsh"),
            BinNot(_) => write!(format, "BinNot"),
            Not(_) => write!(format, "Not"),
            Len(_) => write!(format, "Len"),
            UMin(_) => write!(format, "UMin"),
            Concat(_, _) => write!(format, "Concat"),
            PrefixExp(_) => write!(format, "PrefixExp"),
            Nil => write!(format, "Nil"),
            VarArg => write!(format, "VarArg"),
            TableConstructor(_) => write!(format, "TableConstructor"),
            Function(_) => write!(format, "Function"),
            FunctionBody(_, _) => write!(format, "FunctionBody"),
            FunctionName(_, _, _) => write!(format, "FunctionName"),
            NamedFunction(_, _) => write!(format, "NamedFunction"),
            ExpList(_) => write!(format, "ExpList"),
            VarList(_) => write!(format, "VarList"),
            NameList(_) => write!(format, "NameList"),
            FieldList(_) => write!(format, "FieldList"),
            ParameterList(_, _) => write!(format, "ParameterList"),
            FieldSingle(_) => write!(format, "FieldSingle"),
            FieldAssign(_, _) => write!(format, "FieldAssign"),
            Local(_) => write!(format, "Local"),
            Var(_) => write!(format, "Var"),
            VarPrefixed(_, _) => write!(format, "VarPrefixed"),
            VarListAccess(_, _) => write!(format, "VarListAccess"),
        }
    }
}

//TODO: There is a bunch of cloing here that might not be necessary
//TODO: Is there a better way to do this, or do we need 6 cfg blocks
#[cfg(feature="graphviz")]
type Node = ASTNode;
#[cfg(feature="graphviz")]
type Edge = (ASTNode, ASTNode);
#[cfg(feature="graphviz")]
struct Edges(Vec<Edge>);
#[cfg(feature="graphviz")]
use dot;
#[cfg(feature="graphviz")]
use std::borrow::Cow;
#[cfg(feature="graphviz")]
use std::io::Write;


#[cfg(feature="graphviz")]
impl<'a> dot::Labeller<'a, Node, Edge> for Edges {
    fn graph_id(&'a self) -> dot::Id<'a> {
        dot::Id::new("AST").unwrap()
    }

    fn node_id(&'a self, node: &Node) -> dot::Id<'a> {
        dot::Id::new(format!("{}", node)).unwrap()
    }
}


#[cfg(feature="graphviz")]
impl<'a> dot::GraphWalk<'a, Node, Edge> for Edges {
    fn nodes(&self) -> dot::Nodes<'a,Node> {
        // (assumes that |N| \approxeq |E|)
        let &Edges(ref v) = self;
        let mut node_vec = Vec::with_capacity(v.len());
        for n in v {
            let &(ref s, ref t) = n;
            node_vec.extend(s.sub_nodes());
            node_vec.extend(t.sub_nodes());
        }
        node_vec.dedup();
        Cow::Owned(node_vec)
    }

    fn edges(&'a self) -> dot::Edges<'a,Edge> {
        let &Edges(ref edges) = self;
        Cow::Borrowed(&edges[..])
    }

    fn source(&self, e: &Edge) -> Node { let &(ref s,_) = e; s.clone() }

    fn target(&self, e: &Edge) -> Node { let &(_,ref t) = e; t.clone() }
}


#[cfg(feature="graphviz")]
impl ASTNode {
    fn generate_edges(&self) -> Vec<(ASTNode, ASTNode)> {
        use ASTNode::*;
        let mut node_vec = Vec::new();
        match (*self).clone() {

            Integer(_) |
            Float(_) |
            Bool(_) |
            String(_) |
            Label(_) |
            Name(_) |
            Nil |
            Break |
            VarArg |
            EmptyStatement => {},

            Paren(a) |
            Local(a) |
            Var(a) |
            Goto(a) |
            BinNot(a) |
            Not(a) |
            Len(a) |
            UMin(a) |
            PrefixExp(a) |
            Function(a) |
            FieldSingle(a) |
            PrefixExp(a) => {
                node_vec.push(((*self).clone(), (*a).clone()));
                node_vec.extend(a.generate_edges());
            },

            Add(a, b) |
            Sub(a, b) |
            Mul(a, b) |
            Div(a, b) |
            Exp(a, b) |
            FDiv(a, b) |
            Mod(a, b) |
            And(a, b) |
            Or(a, b) |
            Lt(a, b) |
            Le(a, b) |
            Gt(a, b) |
            Ge(a, b) |
            Eq(a, b) |
            Ne(a, b) |
            BitOr(a, b) |
            BitAnd(a, b) |
            BitXor(a, b) |
            Rsh(a, b) |
            Lsh(a, b) |
            Concat(a, b) |
            FieldAssign(a, b) |
            VarPrefixed(a, b) |
            VarListAccess(a, b) |
            NamedFunction(a, b) => {
                node_vec.push(((*self).clone(), (*a).clone()));
                node_vec.push(((*self).clone(), (*b).clone()));
                node_vec.extend(a.generate_edges());
                node_vec.extend(b.generate_edges());
            },

            RetStat(a) |
            TableConstructor(a) |
            ParameterList(a, _) => if let Some(sa) = *a {
                node_vec.push(((*self).clone(), sa.clone()));
                node_vec.extend(sa.generate_edges());
            },

            ExpList(a) |
            VarList(a) |
            NameList(a) |
            FieldList(a) => {
                a.iter().map(|ae| {
                    node_vec.push(((*self).clone(), (*ae).clone()));
                    node_vec.extend(ae.generate_edges());
                });
            },

            Block(a, b) => {
                a.iter().map(|ae| {
                    node_vec.push(((*self).clone(), (*ae).clone()));
                    node_vec.extend(ae.generate_edges());
                });
                if let Some(sb) = *b {
                    node_vec.push(((*self).clone(), sb.clone()));
                    node_vec.extend(sb.generate_edges());
                };
            },
            FunctionBody(a, b) => {
                if let Some(sa) = *a {
                    node_vec.push(((*self).clone(), sa.clone()));
                    node_vec.extend(sa.generate_edges());
                };
                node_vec.push(((*self).clone(), (*b).clone()));
                node_vec.extend(b.generate_edges());
            },
            FunctionName(a, b, c) => {
                node_vec.push(((*self).clone(), (*a).clone()));
                node_vec.extend(a.generate_edges());
                if let Some(sb) = b {
                    sb.iter().map(|sbe| {
                        node_vec.push(((*self).clone(), (*sbe).clone()));
                        node_vec.extend(sbe.generate_edges());
                    });
                };
                if let Some(sc) = c {
                    node_vec.push(((*self).clone(), (*sc).clone()));
                    node_vec.extend(sc.generate_edges());
                };
            },
            _ => panic!("Unimplemented: GenEdges"),
        }
        node_vec
    }

    fn sub_nodes(&self) -> Vec<ASTNode> {
        use ASTNode::*;
        let mut node_vec = Vec::new();

        node_vec.push((*self).clone());

        match (*self).clone() {
            Nil |
            VarArg |
            Break |
            EmptyStatement |
            Float(_) |
            Bool(_) |
            String(_) |
            Label(_) |
            Name(_) |
            Integer(_) => {},

            Goto(a) |
            BinNot(a) |
            Not(a) |
            Len(a) |
            UMin(a) |
            PrefixExp(a) |
            FieldSingle(a) |
            Local(a) |
            Var(a) |
            Function(a) |
            PrefixExp(a) |
            Paren(a) => node_vec.extend(a.sub_nodes()),

            And(a, b) |
            Or(a, b) |
            Lt(a, b) |
            Le(a, b) |
            Gt(a, b) |
            Ge(a, b) |
            Eq(a, b) |
            Ne(a, b) |
            BitOr(a, b) |
            BitAnd(a, b) |
            BitXor(a, b) |
            Rsh(a, b) |
            Lsh(a, b) |
            FieldAssign(a, b) |
            VarPrefixed(a, b) |
            VarListAccess(a, b) |
            NamedFunction(a, b) |
            Concat(a, b) |
            Add(a, b) |
            Sub(a, b) |
            Mul(a, b) |
            Div(a, b) |
            Exp(a, b) |
            FDiv(a, b) |
            Mod(a, b) => {
                node_vec.extend(a.sub_nodes());
                node_vec.extend(b.sub_nodes());
            },

            ExpList(a) |
            VarList(a) |
            NameList(a) |
            FieldList(a) => { a.iter().map(|b| node_vec.extend(b.sub_nodes())); },

            RetStat(a) |
            ParameterList(a, _) |
            TableConstructor(a) => if let Some(sa) = *a {
                node_vec.extend(sa.sub_nodes());
            },

            Block(a, b) => {
                a.iter().map(|ae| node_vec.extend(ae.sub_nodes()));
                if let Some(sb) = *b {
                    node_vec.extend(sb.sub_nodes());
                }
            },

            FunctionBody(a, b) => {
                if let Some(sa) = *a {
                    node_vec.extend(sa.sub_nodes());
                }
                node_vec.extend(b.sub_nodes());
            },

            FunctionName(a, b, c) => {
                node_vec.extend(a.sub_nodes());
                if let Some(sb) = b {
                    sb.iter().map(|sbe| node_vec.extend(sbe.sub_nodes()));
                };
                if let Some(sc) = c {
                    node_vec.extend(sc.sub_nodes());
                }
            },
            _ => panic!("Unimplemented: SubNodes"),
        };
        node_vec
    }

    #[cfg(feature="graphviz")]
    pub fn graphviz_render<W: Write>(&self, output: &mut W) {
        let edges = Edges(self.generate_edges());
        dot::render(&edges, output).unwrap()
    }
}