-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_combinator.cpp
More file actions
97 lines (84 loc) · 1.74 KB
/
Copy pathparser_combinator.cpp
File metadata and controls
97 lines (84 loc) · 1.74 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
95
96
#include "parser_combinator.h"
#include <sstream>
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) {
oss << *r;
r = (*p)(s);
}
return yield(oss.str());
});
}
parser<std::string> many1(parser<char> p) {
using ftl::operator>>=;
// Run p once normally, bind with what's essentially "many"
return p >>= [p](char t) {
return parser<std::string>([p,t](std::istream& strm) {
auto r = (*many(p))(strm);
if(r) {
r->insert(r->begin(), t);
return r;
}
else {
std::string s;
s.insert(s.begin(), t);
return yield(s);
}
});
};
}