-
Notifications
You must be signed in to change notification settings - Fork 6
/
ast_parse.cpp
executable file
·50 lines (40 loc) · 1.07 KB
/
ast_parse.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
#include "ast.hpp"
static std::vector<std::string> Tokenise(std::istream &src)
{
std::vector<std::string> res;
std::string tmp;
while(src >> tmp){
res.push_back(tmp);
}
return res;
}
static std::pair<TreePtr,int> ParseImpl(const std::vector<std::string> &tokens, int pos)
{
std::string type;
std::string value;
std::vector<TreePtr> branches;
type=tokens.at(pos++);
if(pos < tokens.size()){
if(tokens.at(pos)==":"){
pos++;
value=tokens.at(pos++);
}
}
if(pos < tokens.size()){
if(tokens.at(pos)=="["){
pos++;
while(tokens.at(pos)!="]"){
auto sub=ParseImpl(tokens, pos);
branches.push_back( sub.first );
pos=sub.second;
}
pos++; // skip ']'
}
}
return std::make_pair(std::make_shared<Tree>(type, value, branches),pos);
}
TreePtr Parse(std::istream &src)
{
auto tokens=Tokenise(src);
return ParseImpl(tokens, 0).first;
}