nom_lua/
field.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::*;
11use exp::parse_exp;
12use name::parse_name;
13
14named!(pub parse_fieldlist<ASTNode>, map!(
15            map!(do_parse!(
16                   a: parse_field
17                >> b: many0!(preceded!(parse_fieldsep, parse_field))
18                >> (a,b)
19            ), |(a, mut b): (_, Vec <ASTNode>) | { b.insert(0, a); b }),
20ASTNode::FieldList));
21
22named!(parse_field<ASTNode>, ws!(alt!(
23        do_parse!(
24               n: delimited!(tag!("["), ws!(parse_exp), tag!("]"))
25            >> ws!(tag!("="))
26            >> e: parse_exp
27            >> (astb!(FieldAssign, n, e)))|
28        do_parse!(
29               n: parse_name
30            >> ws!(tag!("="))
31            >> e: parse_exp
32            >> (astb!(FieldAssign, n, e)))|
33        map!(map!(parse_exp, Box::new), ASTNode::FieldSingle)
34)));
35
36named!(parse_fieldsep, alt!(tag!(",") | tag!(";")));
37
38#[cfg(test)]
39mod tests {
40    use ast::ASTNode::*;
41
42    ast_valid!(parse_fieldsep_1, parse_fieldsep, ";");
43    ast_valid!(parse_fieldsep_2, parse_fieldsep, ",");
44
45    ast_test!(parse_field_assign_1, parse_field, " [ true ] = true ",
46              astb!(FieldAssign, ast!(Bool, true), ast!(Bool, true)));
47    ast_test!(parse_field_assign_2, parse_field, "[true]=nil",
48              astb!(FieldAssign, ast!(Bool, true), ast!(Nil)));
49    ast_test!(parse_field_assign_3, parse_field, "is=true",
50              astb!(FieldAssign, ast!(Name, "is".into()), ast!(Bool, true)));
51    ast_test!(parse_field_single_1, parse_field, "true",
52              astb!(FieldSingle, ast!(Bool, true)));
53}