forked from beark/ftl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_combinator.cpp
88 lines (74 loc) · 1.58 KB
/
parser_combinator.cpp
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
#include "parser_combinator.h"
#include <sstream>
using namespace ftl;
parser<char> anyChar() {
return parser<char>([](std::istream& s) {
char ch;
if(s.get(ch)) {
return yield(ch);
}
return fail<char>("any character");
});
}
parser<char> parseChar(char c) {
return parser<char>{[c](std::istream& s) {
if(s) {
char ch = s.peek();
if(ch == c) {
// Don't forget to acutally eat a char from the stream too
s.get();
return yield(c);
}
}
std::ostringstream oss;
oss << "'" << c << "'";
return fail<char>(oss.str());
}};
}
parser<char> notChar(char c) {
return parser<char>([c](std::istream& s) {
if(s) {
char ch = s.peek();
if(ch != c) {
s.get();
return yield(ch);
}
}
std::ostringstream oss;
oss << "any character but '" << c << "'";
return fail<char>(oss.str());
});
}
parser<char> oneOf(std::string str) {
return parser<char>{[str](std::istream& s) {
if(s) {
char peek = s.peek();
auto pos = str.find(peek);
if(pos != std::string::npos) {
s.get();
return yield(peek);
}
}
std::ostringstream oss;
oss << "one of \"" << str << "\"";
return fail<char>(oss.str());
}};
}
parser<std::string> many(parser<char> p) {
return parser<std::string>([p](std::istream& s) {
auto r = (*p)(s);
std::ostringstream oss;
while(r.template is<Right<char>>()) {
oss << *get<Right<char>>(r);
r = (*p)(s);
}
return yield(oss.str());
});
}
std::string prepend(char c, std::string s) {
s.insert(s.begin(), c);
return s;
}
parser<std::string> many1(parser<char> p) {
return curry(prepend) % p * many(p);
}