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
97
98
|
#include <cassert>
#include "ast.hpp"
namespace parserlib {
//current AST container.
static ast_container *_current = 0;
int ast_type_id = 0;
bool ast_node::visit(const std::function<bool (ast_node*)>& begin,
const std::function<bool (ast_node*)>& end)
{
return begin(this) || end(this);
}
/** sets the container under construction to be this.
*/
ast_container::ast_container() {
_current = this;
}
/** sets the container under construction to be this.
@param src source object.
*/
ast_container::ast_container(const ast_container &src) {
_current = this;
}
/** Asks all members to construct themselves from the stack.
The members are asked to construct themselves in reverse order.
from a node stack.
@param st stack.
*/
void ast_container::construct(ast_stack &st) {
for(ast_member_vector::reverse_iterator it = m_members.rbegin();
it != m_members.rend();
++it)
{
ast_member *member = *it;
member->construct(st);
}
}
bool ast_container::visit(const std::function<bool (ast_node*)>& begin,
const std::function<bool (ast_node*)>& end)
{
bool result = begin(this);
if (result) return true;
const auto& members = this->members();
for (auto member : members) {
if (_ast_ptr* ptr = ast_cast<_ast_ptr>(member)) {
if (ptr->get() && ptr->get()->visit(begin, end)) {
return true;
}
} else if (_ast_list* list = ast_cast<_ast_list>(member)) {
for (auto obj : list->objects()) {
if (obj->visit(begin, end)) {
return true;
}
}
}
}
return end(this);
}
//register the AST member to the current container.
void ast_member::_init() {
assert(_current);
m_container = _current;
_current->m_members.push_back(this);
}
/** parses the given input.
@param i input.
@param g root rule of grammar.
@param el list of errors.
@param ud user data, passed to the parse procedures.
@return pointer to ast node created, or null if there was an error.
The return object must be deleted by the caller.
*/
ast_node *parse(input &i, rule &g, error_list &el, void* ud) {
ast_stack st;
if (!parse(i, g, el, &st, ud)) return 0;
assert(st.size() == 1);
return st[0];
}
} //namespace parserlib
|