-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.rs
More file actions
94 lines (76 loc) · 1.79 KB
/
parser.rs
File metadata and controls
94 lines (76 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// TODO: WIP
use std::io::prelude::*;
use std::{error, io};
#[derive(Clone, Debug)]
enum Token<'a> {
Id(&'a str),
}
type Input<'a> = &'a [Token<'a>];
type Error = ();
type ParseResult<'a, T> = Result<(T, Input<'a>), Error>;
trait Parse {
type Output;
fn parse<'a>(&self, input: Input<'a>) -> ParseResult<'a, Self::Output>;
fn map<T, F>(&self, map: F) -> Map<&Self, F>
where
F: Fn(Self::Output) -> T,
{
Map { parser: self, map }
}
}
struct Parser<F> {
parse: F,
}
impl<F> Parser<F> {
fn new<T>(parse: F) -> Self
where
F: Fn(Input) -> ParseResult<T>,
{
Parser { parse }
}
}
impl<F, T> Parse for Parser<F>
where
F: Fn(Input) -> ParseResult<T>,
{
type Output = T;
fn parse<'a>(&self, input: Input<'a>) -> ParseResult<'a, Self::Output> {
(self.parse)(input)
}
}
struct Map<P, F> {
parser: P,
map: F,
}
impl<P, F, T> Parse for Map<P, F>
where
P: Parse,
F: Fn(P::Output) -> T,
{
type Output = T;
fn parse<'a>(&self, input: Input<'a>) -> ParseResult<'a, Self::Output> {
self.parser
.parse(input)
.map(|(res, inp)| ((self.map)(res), inp))
}
}
fn tokenize(line: &str) -> Vec<Token> {
line.split_whitespace().map(|s| Token::Id(s)).collect()
}
fn parse_any<'a>(inp: Input<'a>) -> ParseResult<'a, &'a Token<'a>> {
inp.split_first().ok_or(())
}
fn main() -> Result<(), Box<error::Error>> {
let any = Parser::new(parse_any);
let parser = any;
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line?;
let tokens = tokenize(line.as_ref());
match parser.parse(&tokens) {
Ok((res, inp)) => println!("{:?}", res),
Err(err) => println!("{:?}", err),
}
}
Ok(())
}