static_graph/parser/
field.rs

1use nom::{
2    bytes::complete::tag,
3    combinator::{map, opt},
4    sequence::tuple,
5    IResult,
6};
7
8use super::{annotations::Annotations, blank, ident::Ident, list_separator, ty::Type, Parser};
9
10#[derive(Debug, Clone)]
11pub struct Field {
12    pub name: Ident,
13    pub ty: Type,
14    pub annotations: Annotations,
15}
16
17impl<'a> Parser<'a> for Field {
18    fn parse(input: &'a str) -> IResult<&'a str, Self> {
19        map(
20            tuple((
21                opt(Annotations::parse),
22                opt(blank),
23                Ident::parse,
24                tag(":"),
25                opt(blank),
26                Type::parse,
27                opt(blank),
28                opt(list_separator),
29            )),
30            |(annotations, _, name, _, _, ty, _, _)| Field {
31                name,
32                ty,
33                annotations: annotations.unwrap_or_default(),
34            },
35        )(input)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    use crate::parser::ty::Type;
43
44    #[test]
45    fn test_field() {
46        let input = r#"#[default = "Bar::new"]
47        foo: Bar"#;
48        match super::Field::parse(input) {
49            Ok((remain, field)) => {
50                assert_eq!(remain, "");
51                assert_eq!(field.name.0, "foo");
52                match field.ty {
53                    Type::Path(path) => {
54                        assert_eq!(path.segments.len(), 1);
55                        assert_eq!(path.segments[0].0, "Bar");
56                    }
57                    _ => panic!("Expected Path"),
58                }
59                assert_eq!(field.annotations.len(), 1);
60                assert_eq!(field.annotations[0].key, "default");
61                assert_eq!(field.annotations[0].value.0, "Bar::new");
62            }
63            Err(e) => panic!("{e:?}"),
64        }
65    }
66}