nom_lua/
exp.rs

1// Copyright 2017 The nom-lua project developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use ast::ASTNode;
10use ast::ASTNode::*;
11
12use number::parse_number;
13use op::parse_op;
14use string::parse_string;
15use function::parse_functiondef;
16use field::parse_fieldlist;
17use var::parse_var;
18
19named!(parse_vararg<ASTNode>, map!(tag!("..."), |_| ast!(VarArg)));
20named!(parse_nil<ASTNode>, map!(tag!("nil"), |_| ast!(Nil)));
21named!(parse_bool<ASTNode>, alt!(map!(tag!("false"), |_| ast!(Bool, false)) |
22                                 map!(tag!("true"), |_| ast!(Bool, true))));
23
24named!(pub parse_prefixexp<ASTNode>, map!(map!(alt!(
25        //parse_functioncall |
26        delimited!(tag!("("), ws!(parse_exp), tag!(")")) |
27        parse_var
28), Box::new), ASTNode::PrefixExp)) ;
29
30named!(pub parse_explist<ASTNode>, map!(
31            map!(do_parse!(
32                   a: parse_exp
33                >> b: many0!(preceded!(ws!(tag!(",")), parse_exp))
34                >> (a,b)
35            ), |(a, mut b): (_, Vec < ASTNode >) | { b.insert(0, a); b }),
36ASTNode::ExpList));
37
38named!(pub parse_exp<ASTNode>, alt!(
39                parse_op |
40                parse_nil |
41                parse_bool |
42                parse_string |
43                parse_vararg |
44                parse_functiondef |
45                parse_prefixexp |
46                parse_tableconstructor
47));
48
49// TODO: Missing tests
50named!(parse_tableconstructor<ASTNode>,
51       map!(
52       do_parse!(
53              tag!("{")
54           >> f: ws!(opt!(parse_fieldlist))
55           >> tag!("}")
56           >> (Box::new(f))), ASTNode::TableConstructor));
57
58
59
60#[cfg(test)]
61mod tests {
62    use ast::ASTNode::*;
63
64    ast_test!(parse_nil, parse_nil, "nil", ast!(Nil));
65    ast_test!(parse_bool_t, parse_bool, "true", ast!(Bool, true));
66    ast_test!(parse_bool_f, parse_bool, "false", ast!(Bool, false));
67    ast_test!(parse_vararg, parse_vararg, "...", ast!(VarArg));
68
69    ast_test!(parse_explist_1, parse_explist, "true", ast!(ExpList, vec![
70        ast!(Bool, true)
71    ]));
72    ast_test!(parse_explist_2, parse_explist, "true , true", ast!(ExpList, vec![
73        ast!(Bool, true),
74        ast!(Bool, true)
75    ]));
76    ast_test!(parse_explist_3, parse_explist, "true , false, false", ast!(ExpList, vec![
77        ast!(Bool, true),
78        ast!(Bool, false),
79        ast!(Bool, false)
80    ]));
81}