Struct pom::parser::Parser

source ·
pub struct Parser<'a, I, O> {
    pub method: Box<dyn Fn(&'a [I], usize) -> Result<(O, usize)> + 'a>,
}
Expand description

Parser combinator.

Fields§

§method: Box<dyn Fn(&'a [I], usize) -> Result<(O, usize)> + 'a>

Implementations§

source§

impl<'a, I, O> Parser<'a, I, O>

source

pub fn new<P>(parse: P) -> Self
where P: Fn(&'a [I], usize) -> Result<(O, usize)> + 'a,

Create new parser.

source

pub fn parse(&self, input: &'a [I]) -> Result<O>

Apply the parser to parse input.

Examples found in repository?
examples/json_file.rs (line 94)
90
91
92
93
94
95
fn main() {
	let mut file = File::open("examples/test.json").unwrap();
	let mut input: Vec<u8> = Vec::new();
	file.read_to_end(&mut input).expect("read test.json");
	println!("{:?}", json().parse(input.as_slice()));
}
More examples
Hide additional examples
examples/simple.rs (line 15)
12
13
14
15
16
17
18
19
fn main() {
	let input = b"abcde";
	let parser = sym(b'a') * none_of(b"AB") - sym(b'c') + seq(b"de");
	let output = parser.parse(input);
	// assert_eq!(output, Ok( (b'b', &b"de"[..]) ) );
	println!("{:?}", output);
	println!("{:?}", example().parse("<app>bcb</app>".as_bytes()));
}
examples/duration.rs (line 77)
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
fn main() {
	let input = "P3Y6M4DT12H30M5S";
	let result = parser().parse(input.as_bytes());

	assert_eq!(
		Duration {
			years: Some(3f32),
			months: Some(6f32),
			weeks: None,
			days: Some(4f32),
			hours: Some(12f32),
			minutes: Some(30f32),
			seconds: Some(5f32)
		},
		result.unwrap()
	);
}
examples/whitespace.rs (line 67)
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
fn container<'a>() -> Parser<'a, u8, Container> {
	seq(b"Container\n")
		* (indented() | empty().map(|()| vec![]))
			.repeat(1..)
			.map(|lines| {
				lines
					.into_iter()
					.filter(|line| line.len() > 0)
					.fold(vec![], |accum, line| {
						accum
							.into_iter()
							.chain(line.into_iter().chain(vec![b'\n'].into_iter()))
							.collect()
					})
			})
			.map(|deden| subcontainer().parse(&deden).expect("subcont"))
			.map(|(containers, contents)| Container {
				containers,
				contents,
			})
}

fn mylang<'a>() -> Parser<'a, u8, Vec<Container>> {
	whitespace() * list(call(container), whitespace())
}

fn main() -> Result<(), ()> {
	let input = br#"
Container
	Container
		a
		b
		c

	1
	2
	3

	Container
		q

Container
	foo
	bar

	Container
		baz
		quux
		"#;

	assert_eq!(
		mylang().parse(input),
		Ok(vec![
			Container {
				containers: vec![
					Container {
						containers: vec![],
						contents: vec!["a".into(), "b".into(), "c".into(),]
					},
					Container {
						containers: vec![],
						contents: vec!["q".into(),]
					}
				],
				contents: vec!["1".into(), "2".into(), "3".into(),]
			},
			Container {
				containers: vec![Container {
					contents: vec!["baz".into(), "quux".into(),],
					containers: vec![],
				},],
				contents: vec!["foo".into(), "bar".into(),]
			},
		])
	);

	Ok(())
}
examples/json.rs (line 106)
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
fn main() {
	let input = br#"
	{
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        },
        "escaped characters": "\u2192\uD83D\uDE00\"\t\uD834\uDD1E"
    }"#;

	println!("{:?}", json().parse(input));
}
examples/json_char.rs (line 107)
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
fn main() {
	let test = r#"
	{
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        },
        "escaped characters": "\u2192\uD83D\uDE00\"\t\uD834\uDD1E"
    }"#;

	let input: Vec<char> = test.chars().collect();
	println!("{:?}", json().parse(&input));
}
source

pub fn parse_at(&self, input: &'a [I], start: usize) -> Result<(O, usize)>

Parse input at specified position.

source

pub fn map<U, F>(self, f: F) -> Parser<'a, I, U>
where F: Fn(O) -> U + 'a, I: 'a, O: 'a, U: 'a,

Convert parser result to desired value.

Examples found in repository?
examples/duration.rs (line 37)
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
fn date_part() -> Parser<u8, (Option<f32>, Option<f32>, Option<f32>, Option<f32>)> {
	((number() - sym(b'Y')).opt()
		+ (number() - sym(b'M')).opt()
		+ (number() - sym(b'W')).opt()
		+ (number() - sym(b'D')).opt())
	.map(|(((years, months), weeks), days)| (years, months, weeks, days))
}

fn time_part() -> Parser<u8, (Option<f32>, Option<f32>, Option<f32>)> {
	sym(b'T')
		* ((number() - sym(b'H')).opt()
			+ (number() - sym(b'M')).opt()
			+ (number() - sym(b'S')).opt())
		.map(|((hours, minutes), seconds)| (hours, minutes, seconds))
}

fn parser() -> Parser<u8, Duration> {
	sym(b'P')
		* (time_part().map(|(hours, minutes, seconds)| Duration {
			years: None,
			months: None,
			weeks: None,
			days: None,
			hours,
			minutes,
			seconds,
		}) | (date_part() + time_part()).map(|(date_elements, time_elements)| {
			let (years, months, weeks, days) = date_elements;
			let (hours, minutes, seconds) = time_elements;
			Duration {
				years,
				months,
				weeks,
				days,
				hours,
				minutes,
				seconds,
			}
		}))
}
More examples
Hide additional examples
examples/json_char.rs (line 29)
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
fn number<'a>() -> Parser<'a, char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | sym('0');
	let frac = sym('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = sym('-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.map(String::from_iter)
		.convert(|s| f64::from_str(&s))
}

fn string<'a>() -> Parser<'a, char, String> {
	let special_char = sym('\\')
		| sym('/')
		| sym('"')
		| sym('b').map(|_| '\x08')
		| sym('f').map(|_| '\x0C')
		| sym('n').map(|_| '\n')
		| sym('r').map(|_| '\r')
		| sym('t').map(|_| '\t');
	let escape_sequence = sym('\\') * special_char;
	let char_string = (none_of("\\\"") | escape_sequence)
		.repeat(1..)
		.map(String::from_iter);
	let utf16_char = tag("\\u")
		* is_a(|c: char| c.is_digit(16))
			.repeat(4)
			.map(String::from_iter)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym('"') * (char_string | utf16_string).repeat(0..) - sym('"');
	string.map(|strings| strings.concat())
}

fn array<'a>() -> Parser<'a, char, Vec<JsonValue>> {
	let elems = list(call(value), sym(',') * space());
	sym('[') * space() * elems - sym(']')
}

fn object<'a>() -> Parser<'a, char, HashMap<String, JsonValue>> {
	let member = string() - space() - sym(':') - space() + call(value);
	let members = list(member, sym(',') * space());
	let obj = sym('{') * space() * members - sym('}');
	obj.map(|members| members.into_iter().collect::<HashMap<_, _>>())
}

fn value<'a>() -> Parser<'a, char, JsonValue> {
	(tag("null").map(|_| JsonValue::Null)
		| tag("true").map(|_| JsonValue::Bool(true))
		| tag("false").map(|_| JsonValue::Bool(false))
		| number().map(|num| JsonValue::Num(num))
		| string().map(|text| JsonValue::Str(text))
		| array().map(|arr| JsonValue::Array(arr))
		| object().map(|obj| JsonValue::Object(obj)))
		- space()
}
examples/whitespace.rs (line 35)
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
fn subcontainer<'a>() -> Parser<'a, u8, (Vec<Container>, Vec<String>)> {
	(call(container).map(|ctr| TmpContainerOrContent::Container(ctr))
		| content().map(|ctn| TmpContainerOrContent::Content(ctn)))
	.repeat(1..)
	.map(|tmp| {
		tmp.into_iter().fold((vec![], vec![]), |acc, x| match x {
			TmpContainerOrContent::Container(ct) => (
				acc.0.into_iter().chain(vec![ct].into_iter()).collect(),
				acc.1,
			),
			TmpContainerOrContent::Content(cn) => (
				acc.0,
				acc.1.into_iter().chain(vec![cn].into_iter()).collect(),
			),
		})
	})
}

fn container<'a>() -> Parser<'a, u8, Container> {
	seq(b"Container\n")
		* (indented() | empty().map(|()| vec![]))
			.repeat(1..)
			.map(|lines| {
				lines
					.into_iter()
					.filter(|line| line.len() > 0)
					.fold(vec![], |accum, line| {
						accum
							.into_iter()
							.chain(line.into_iter().chain(vec![b'\n'].into_iter()))
							.collect()
					})
			})
			.map(|deden| subcontainer().parse(&deden).expect("subcont"))
			.map(|(containers, contents)| Container {
				containers,
				contents,
			})
}
examples/json.rs (line 37)
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
fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}

fn array<'a>() -> Parser<'a, u8, Vec<JsonValue>> {
	let elems = list(call(value), sym(b',') * space());
	sym(b'[') * space() * elems - sym(b']')
}

fn object<'a>() -> Parser<'a, u8, HashMap<String, JsonValue>> {
	let member = string() - space() - sym(b':') - space() + call(value);
	let members = list(member, sym(b',') * space());
	let obj = sym(b'{') * space() * members - sym(b'}');
	obj.map(|members| members.into_iter().collect::<HashMap<_, _>>())
}

fn value<'a>() -> Parser<'a, u8, JsonValue> {
	(seq(b"null").map(|_| JsonValue::Null)
		| seq(b"true").map(|_| JsonValue::Bool(true))
		| seq(b"false").map(|_| JsonValue::Bool(false))
		| number().map(|num| JsonValue::Num(num))
		| string().map(|text| JsonValue::Str(text))
		| array().map(|arr| JsonValue::Array(arr))
		| object().map(|obj| JsonValue::Object(obj)))
		- space()
}
examples/json_file.rs (line 39)
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
fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}

fn array<'a>() -> Parser<'a, u8, Vec<JsonValue>> {
	let elems = list(call(value), sym(b',') * space());
	sym(b'[') * space() * elems - sym(b']')
}

fn object<'a>() -> Parser<'a, u8, HashMap<String, JsonValue>> {
	let member = string() - space() - sym(b':') - space() + call(value);
	let members = list(member, sym(b',') * space());
	let obj = sym(b'{') * space() * members - sym(b'}');
	obj.map(|members| members.into_iter().collect::<HashMap<_, _>>())
}

fn value<'a>() -> Parser<'a, u8, JsonValue> {
	(seq(b"null").map(|_| JsonValue::Null)
		| seq(b"true").map(|_| JsonValue::Bool(true))
		| seq(b"false").map(|_| JsonValue::Bool(false))
		| number().map(|num| JsonValue::Num(num))
		| string().map(|text| JsonValue::Str(text))
		| array().map(|arr| JsonValue::Array(arr))
		| object().map(|obj| JsonValue::Object(obj)))
		- space()
}
source

pub fn convert<U, E, F>(self, f: F) -> Parser<'a, I, U>
where F: Fn(O) -> Result<U, E> + 'a, E: Debug, O: 'a, U: 'a,

Convert parser result to desired value, fail in case of conversion error.

Examples found in repository?
examples/whitespace.rs (line 31)
30
31
32
fn content<'a>() -> Parser<'a, u8, String> {
	none_of(b" \t\r\n").repeat(1..).convert(String::from_utf8) - linebreak()
}
More examples
Hide additional examples
examples/duration.rs (line 28)
22
23
24
25
26
27
28
29
30
fn number() -> Parser<u8, f32> {
	let integer = one_of(b"0123456789").repeat(0..);
	let frac = number_separator() + one_of(b"0123456789").repeat(1..);
	let number = integer + frac.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f32::from_str)
}
examples/simple.rs (line 7)
3
4
5
6
7
8
9
10
fn example<'a>() -> Parser<'a, u8, Vec<u8>> {
	(sym(b'<') * none_of(b">").repeat(0..) - sym(b'>'))
		>> |tag| {
			(call(example) | none_of(b"<>").repeat(0..))
				- seq(b"</") - take(tag.len()).convert(move |t| if t == tag { Ok(()) } else { Err(()) })
				- sym(b'>')
		}
}
examples/json.rs (line 29)
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
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}

fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}
examples/json_char.rs (line 30)
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
fn number<'a>() -> Parser<'a, char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | sym('0');
	let frac = sym('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = sym('-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.map(String::from_iter)
		.convert(|s| f64::from_str(&s))
}

fn string<'a>() -> Parser<'a, char, String> {
	let special_char = sym('\\')
		| sym('/')
		| sym('"')
		| sym('b').map(|_| '\x08')
		| sym('f').map(|_| '\x0C')
		| sym('n').map(|_| '\n')
		| sym('r').map(|_| '\r')
		| sym('t').map(|_| '\t');
	let escape_sequence = sym('\\') * special_char;
	let char_string = (none_of("\\\"") | escape_sequence)
		.repeat(1..)
		.map(String::from_iter);
	let utf16_char = tag("\\u")
		* is_a(|c: char| c.is_digit(16))
			.repeat(4)
			.map(String::from_iter)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym('"') * (char_string | utf16_string).repeat(0..) - sym('"');
	string.map(|strings| strings.concat())
}
examples/json_file.rs (line 31)
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
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}

fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}
source

pub fn cache(self) -> Self
where O: Clone + 'a,

Cache parser output result to speed up backtracking.

source

pub fn pos(self) -> Parser<'a, I, usize>
where O: 'a,

Get input position after matching parser.

source

pub fn collect(self) -> Parser<'a, I, &'a [I]>
where O: 'a,

Collect all matched input symbols.

Examples found in repository?
examples/duration.rs (line 27)
22
23
24
25
26
27
28
29
30
fn number() -> Parser<u8, f32> {
	let integer = one_of(b"0123456789").repeat(0..);
	let frac = number_separator() + one_of(b"0123456789").repeat(1..);
	let number = integer + frac.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f32::from_str)
}
More examples
Hide additional examples
examples/json.rs (line 28)
22
23
24
25
26
27
28
29
30
31
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}
examples/json_char.rs (line 28)
22
23
24
25
26
27
28
29
30
31
fn number<'a>() -> Parser<'a, char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | sym('0');
	let frac = sym('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = sym('-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.map(String::from_iter)
		.convert(|s| f64::from_str(&s))
}
examples/json_file.rs (line 30)
24
25
26
27
28
29
30
31
32
33
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}
source

pub fn discard(self) -> Parser<'a, I, ()>
where O: 'a,

Discard parser output.

Examples found in repository?
examples/json.rs (line 19)
18
19
20
fn space<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}
More examples
Hide additional examples
examples/json_file.rs (line 21)
20
21
22
fn space<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}
examples/json_char.rs (line 19)
18
19
20
fn space<'a>() -> Parser<'a, char, ()> {
	one_of(" \t\r\n").repeat(0..).discard()
}
examples/whitespace.rs (line 15)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn whitespace<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}

fn linebreak<'a>() -> Parser<'a, u8, ()> {
	sym(b'\r').opt() * sym(b'\n').discard()
}

fn indented<'a>() -> Parser<'a, u8, Vec<u8>> {
	sym(b'\t') * none_of(b"\n\r").repeat(1..) - linebreak()
}

fn empty<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t").repeat(0..).discard() - linebreak()
}
examples/duration.rs (line 19)
17
18
19
20
fn number_separator() -> Parser<u8, ()> {
	// either '.' or ',' can be used as a separator between the whole and decimal part of a number
	one_of(b".,").discard()
}
source

pub fn opt(self) -> Parser<'a, I, Option<O>>
where O: 'a,

Make parser optional.

Examples found in repository?
examples/whitespace.rs (line 19)
18
19
20
fn linebreak<'a>() -> Parser<'a, u8, ()> {
	sym(b'\r').opt() * sym(b'\n').discard()
}
More examples
Hide additional examples
examples/duration.rs (line 25)
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
fn number() -> Parser<u8, f32> {
	let integer = one_of(b"0123456789").repeat(0..);
	let frac = number_separator() + one_of(b"0123456789").repeat(1..);
	let number = integer + frac.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f32::from_str)
}

fn date_part() -> Parser<u8, (Option<f32>, Option<f32>, Option<f32>, Option<f32>)> {
	((number() - sym(b'Y')).opt()
		+ (number() - sym(b'M')).opt()
		+ (number() - sym(b'W')).opt()
		+ (number() - sym(b'D')).opt())
	.map(|(((years, months), weeks), days)| (years, months, weeks, days))
}

fn time_part() -> Parser<u8, (Option<f32>, Option<f32>, Option<f32>)> {
	sym(b'T')
		* ((number() - sym(b'H')).opt()
			+ (number() - sym(b'M')).opt()
			+ (number() - sym(b'S')).opt())
		.map(|((hours, minutes), seconds)| (hours, minutes, seconds))
}
examples/json.rs (line 25)
22
23
24
25
26
27
28
29
30
31
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}
examples/json_char.rs (line 25)
22
23
24
25
26
27
28
29
30
31
fn number<'a>() -> Parser<'a, char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | sym('0');
	let frac = sym('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = sym('-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.map(String::from_iter)
		.convert(|s| f64::from_str(&s))
}
examples/json_file.rs (line 27)
24
25
26
27
28
29
30
31
32
33
fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}
source

pub fn repeat<R>(self, range: R) -> Parser<'a, I, Vec<O>>
where R: RangeArgument<usize> + Debug + 'a, O: 'a,

p.repeat(5) repeat p exactly 5 times p.repeat(0..) repeat p zero or more times p.repeat(1..) repeat p one or more times p.repeat(1..4) match p at least 1 and at most 3 times

Examples found in repository?
examples/json.rs (line 19)
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
fn space<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}

fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}

fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}
More examples
Hide additional examples
examples/json_file.rs (line 21)
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
fn space<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}

fn number<'a>() -> Parser<'a, u8, f64> {
	let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0');
	let frac = sym(b'.') + one_of(b"0123456789").repeat(1..);
	let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..);
	let number = sym(b'-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f64::from_str)
}

fn string<'a>() -> Parser<'a, u8, String> {
	let special_char = sym(b'\\')
		| sym(b'/')
		| sym(b'"')
		| sym(b'b').map(|_| b'\x08')
		| sym(b'f').map(|_| b'\x0C')
		| sym(b'n').map(|_| b'\n')
		| sym(b'r').map(|_| b'\r')
		| sym(b't').map(|_| b'\t');
	let escape_sequence = sym(b'\\') * special_char;
	let char_string = (none_of(b"\\\"") | escape_sequence)
		.repeat(1..)
		.convert(String::from_utf8);
	let utf16_char = seq(b"\\u")
		* is_a(hex_digit)
			.repeat(4)
			.convert(String::from_utf8)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym(b'"') * (char_string | utf16_string).repeat(0..) - sym(b'"');
	string.map(|strings| strings.concat())
}
examples/json_char.rs (line 19)
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
fn space<'a>() -> Parser<'a, char, ()> {
	one_of(" \t\r\n").repeat(0..).discard()
}

fn number<'a>() -> Parser<'a, char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | sym('0');
	let frac = sym('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = sym('-').opt() + integer + frac.opt() + exp.opt();
	number
		.collect()
		.map(String::from_iter)
		.convert(|s| f64::from_str(&s))
}

fn string<'a>() -> Parser<'a, char, String> {
	let special_char = sym('\\')
		| sym('/')
		| sym('"')
		| sym('b').map(|_| '\x08')
		| sym('f').map(|_| '\x0C')
		| sym('n').map(|_| '\n')
		| sym('r').map(|_| '\r')
		| sym('t').map(|_| '\t');
	let escape_sequence = sym('\\') * special_char;
	let char_string = (none_of("\\\"") | escape_sequence)
		.repeat(1..)
		.map(String::from_iter);
	let utf16_char = tag("\\u")
		* is_a(|c: char| c.is_digit(16))
			.repeat(4)
			.map(String::from_iter)
			.convert(|digits| u16::from_str_radix(&digits, 16));
	let utf16_string = utf16_char.repeat(1..).map(|chars| {
		decode_utf16(chars)
			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
			.collect::<String>()
	});
	let string = sym('"') * (char_string | utf16_string).repeat(0..) - sym('"');
	string.map(|strings| strings.concat())
}
examples/whitespace.rs (line 15)
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
fn whitespace<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}

fn linebreak<'a>() -> Parser<'a, u8, ()> {
	sym(b'\r').opt() * sym(b'\n').discard()
}

fn indented<'a>() -> Parser<'a, u8, Vec<u8>> {
	sym(b'\t') * none_of(b"\n\r").repeat(1..) - linebreak()
}

fn empty<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t").repeat(0..).discard() - linebreak()
}

fn content<'a>() -> Parser<'a, u8, String> {
	none_of(b" \t\r\n").repeat(1..).convert(String::from_utf8) - linebreak()
}

fn subcontainer<'a>() -> Parser<'a, u8, (Vec<Container>, Vec<String>)> {
	(call(container).map(|ctr| TmpContainerOrContent::Container(ctr))
		| content().map(|ctn| TmpContainerOrContent::Content(ctn)))
	.repeat(1..)
	.map(|tmp| {
		tmp.into_iter().fold((vec![], vec![]), |acc, x| match x {
			TmpContainerOrContent::Container(ct) => (
				acc.0.into_iter().chain(vec![ct].into_iter()).collect(),
				acc.1,
			),
			TmpContainerOrContent::Content(cn) => (
				acc.0,
				acc.1.into_iter().chain(vec![cn].into_iter()).collect(),
			),
		})
	})
}

fn container<'a>() -> Parser<'a, u8, Container> {
	seq(b"Container\n")
		* (indented() | empty().map(|()| vec![]))
			.repeat(1..)
			.map(|lines| {
				lines
					.into_iter()
					.filter(|line| line.len() > 0)
					.fold(vec![], |accum, line| {
						accum
							.into_iter()
							.chain(line.into_iter().chain(vec![b'\n'].into_iter()))
							.collect()
					})
			})
			.map(|deden| subcontainer().parse(&deden).expect("subcont"))
			.map(|(containers, contents)| Container {
				containers,
				contents,
			})
}
examples/duration.rs (line 23)
22
23
24
25
26
27
28
29
30
fn number() -> Parser<u8, f32> {
	let integer = one_of(b"0123456789").repeat(0..);
	let frac = number_separator() + one_of(b"0123456789").repeat(1..);
	let number = integer + frac.opt();
	number
		.collect()
		.convert(str::from_utf8)
		.convert(f32::from_str)
}
examples/simple.rs (line 4)
3
4
5
6
7
8
9
10
fn example<'a>() -> Parser<'a, u8, Vec<u8>> {
	(sym(b'<') * none_of(b">").repeat(0..) - sym(b'>'))
		>> |tag| {
			(call(example) | none_of(b"<>").repeat(0..))
				- seq(b"</") - take(tag.len()).convert(move |t| if t == tag { Ok(()) } else { Err(()) })
				- sym(b'>')
		}
}
source

pub fn name(self, name: &'a str) -> Self
where O: 'a,

Give parser a name to identify parsing errors.

source

pub fn expect(self, name: &'a str) -> Self
where O: 'a,

Mark parser as expected, abort early when failed in ordered choice.

Trait Implementations§

source§

impl<'a, I, O: 'a, U: 'a> Add<Parser<'a, I, U>> for Parser<'a, I, O>

Sequence reserve value

§

type Output = Parser<'a, I, (O, U)>

The resulting type after applying the + operator.
source§

fn add(self, other: Parser<'a, I, U>) -> Self::Output

Performs the + operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Add<Parser<'a, Right>> for Parser<'a, u8, Left>

Sequence reserve value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, (Left, Right)>

The resulting type after applying the + operator.
source§

fn add(self, other: Parser<'a, Right>) -> Self::Output

Performs the + operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Add<Parser<'a, u8, Right>> for Parser<'a, Left>

Sequence reserve value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, (Left, Right)>

The resulting type after applying the + operator.
source§

fn add(self, other: Parser<'a, u8, Right>) -> Self::Output

Performs the + operation. Read more
source§

impl<'a, O: 'a> BitOr<Parser<'a, O>> for Parser<'a, u8, O>

Ordered choice (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, O>

The resulting type after applying the | operator.
source§

fn bitor(self, other: Parser<'a, O>) -> Self::Output

Performs the | operation. Read more
source§

impl<'a, O: 'a> BitOr<Parser<'a, u8, O>> for Parser<'a, O>

Ordered choice (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, O>

The resulting type after applying the | operator.
source§

fn bitor(self, other: Parser<'a, u8, O>) -> Self::Output

Performs the | operation. Read more
source§

impl<'a, I, O: 'a> BitOr for Parser<'a, I, O>

Ordered choice

§

type Output = Parser<'a, I, O>

The resulting type after applying the | operator.
source§

fn bitor(self, other: Parser<'a, I, O>) -> Self::Output

Performs the | operation. Read more
source§

impl<'a, O> From<Parser<'a, O>> for Parser<'a, u8, O>

source§

fn from(parser: Parser<'a, O>) -> Self

Converts to this type from the input type.
source§

impl<'a, I: 'a, O: 'a, U: 'a> Mul<Parser<'a, I, U>> for Parser<'a, I, O>

Sequence discard first value

§

type Output = Parser<'a, I, U>

The resulting type after applying the * operator.
source§

fn mul(self, other: Parser<'a, I, U>) -> Self::Output

Performs the * operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Mul<Parser<'a, Right>> for Parser<'a, u8, Left>

Sequence discard first value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, Right>

The resulting type after applying the * operator.
source§

fn mul(self, other: Parser<'a, Right>) -> Self::Output

Performs the * operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Mul<Parser<'a, u8, Right>> for Parser<'a, Left>

Sequence discard first value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, Right>

The resulting type after applying the * operator.
source§

fn mul(self, other: Parser<'a, u8, Right>) -> Self::Output

Performs the * operation. Read more
source§

impl<'a, I, O: 'a> Neg for Parser<'a, I, O>

And predicate

§

type Output = Parser<'a, I, bool>

The resulting type after applying the - operator.
source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
source§

impl<'a, I, O: 'a> Not for Parser<'a, I, O>

Not predicate

§

type Output = Parser<'a, I, bool>

The resulting type after applying the ! operator.
source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
source§

impl<'a, I, O: 'a, U: 'a, F: Fn(O) -> Parser<'a, I, U> + 'a> Shr<F> for Parser<'a, I, O>

Chain two parsers where the second parser depends on the first’s result.

§

type Output = Parser<'a, I, U>

The resulting type after applying the >> operator.
source§

fn shr(self, other: F) -> Self::Output

Performs the >> operation. Read more
source§

impl<'a, I, O: 'a, U: 'a> Sub<Parser<'a, I, U>> for Parser<'a, I, O>

Sequence discard second value

§

type Output = Parser<'a, I, O>

The resulting type after applying the - operator.
source§

fn sub(self, other: Parser<'a, I, U>) -> Self::Output

Performs the - operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Sub<Parser<'a, Right>> for Parser<'a, u8, Left>

Sequence discard second value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, Left>

The resulting type after applying the - operator.
source§

fn sub(self, other: Parser<'a, Right>) -> Self::Output

Performs the - operation. Read more
source§

impl<'a, Left: 'a, Right: 'a> Sub<Parser<'a, u8, Right>> for Parser<'a, Left>

Sequence discard second value (but degrade to non-utf8 parser)

§

type Output = Parser<'a, u8, Left>

The resulting type after applying the - operator.
source§

fn sub(self, other: Parser<'a, u8, Right>) -> Self::Output

Performs the - operation. Read more

Auto Trait Implementations§

§

impl<'a, I, O> !RefUnwindSafe for Parser<'a, I, O>

§

impl<'a, I, O> !Send for Parser<'a, I, O>

§

impl<'a, I, O> !Sync for Parser<'a, I, O>

§

impl<'a, I, O> Unpin for Parser<'a, I, O>

§

impl<'a, I, O> !UnwindSafe for Parser<'a, I, O>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.