jp_rs/
parse.rs

1
2use pa_rs::parser::*;
3use crate::json::JSONValue::{self, *};
4
5
6struct JSONNullParser;
7
8impl Parse for JSONNullParser {
9  type Result = JSONValue;
10
11  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
12    str_p("null").map(|_| JSONNull).parse(input)
13  }
14}
15
16struct JSONBoolParser;
17
18impl Parse for JSONBoolParser {
19  type Result = JSONValue;
20
21  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
22    bool_p().map(|x| JSONBool(x)).parse(input)
23  }
24}
25
26struct JSONNumberParser;
27
28impl Parse for JSONNumberParser {
29  type Result = JSONValue;
30
31  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
32    float_p().map(|x| JSONNumber(x)).parse(input)
33  }
34}
35
36struct JSONStringParser;
37
38impl Parse for JSONStringParser {
39  type Result = JSONValue;
40
41  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {    
42    dq_str_p().map(|x| JSONString(x)).parse(input)
43  }
44}
45
46struct JSONArrayParser;
47
48impl Parse for JSONArrayParser {
49  type Result = JSONValue;
50
51  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
52    list_square_p(JSONValueParser)
53      .map(|x| JSONArray(x))
54      .parse(input)
55  }
56}
57
58struct JSONObjectParser;
59
60impl Parse for JSONObjectParser {
61  type Result = JSONValue;
62
63  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
64    let parse_kv = 
65    dq_str_p()
66      .sbws()
67      .keep(char_p(':'))
68      .and(JSONValueParser.sbws());
69
70    char_p('{')
71      .drop(parse_kv.sep_by(',').map(|x| JSONObject(x)))
72      .keep(char_p('}'))
73      .parse(input)
74  }
75}
76
77pub struct JSONValueParser;
78
79impl Parse for JSONValueParser {
80  type Result = JSONValue;
81
82  fn parse<'b>(&self, input: &'b str) -> ParseResult<'b, Self::Result> {
83    JSONObjectParser
84      .or(JSONArrayParser)
85      .map(|x| match x {
86        Either::Left(lhs) => lhs,
87        Either::Right(rhs) => rhs
88      })
89      .or(JSONStringParser)
90      .map(|x| match x {
91        Either::Left(lhs) => lhs,
92        Either::Right(rhs) => rhs
93      })
94      .or(JSONNumberParser)
95      .map(|x| match x {
96        Either::Left(lhs) => lhs,
97        Either::Right(rhs) => rhs
98      })
99      .or(JSONBoolParser)
100      .map(|x| match x {
101        Either::Left(lhs) => lhs,
102        Either::Right(rhs) => rhs
103      })
104      .or(JSONNullParser) .map(|x| match x {
105        Either::Left(lhs) => lhs,
106        Either::Right(rhs) => rhs
107      })
108      .parse(input)
109  }
110}