-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAST.cpp
137 lines (113 loc) · 2.51 KB
/
AST.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// AST.cpp - Abstract Syntax Trees, implementation details
//
#pragma warning(disable:4786)
#include "AST.h"
#include "scope.h"
#include "log.h"
#include <assert.h>
#include <string.h>
#include <string>
using namespace std;
namespace js2cpp {
///////////////////////////////////////////////////////////////////
// AST - Abstract Syntax Tree
AST::AST(const Token &t)
: token(t), first(NULL), second(NULL), third(NULL), scope(NULL)
{
}
AST::~AST()
{
delete first;
delete second;
delete third;
}
///////////////////////////////////////////////////////////////////
// access functions, to insulate from oddities of trees
aScope* AST::Scope(int nUp) const
{
assert(scope);
aScope* s = scope;
while (nUp--) {
assert(s);
if (!s) break;
s = s->Parent();
}
return s;
}
void AST::Attach(aScope* s)
{
assert(!scope);
scope = s;
} // Attach
AST*& LoopBody(AST* loop_node)
{
// body of a loop (any loop)
assert(Type(loop_node)==tWHILE ||
Type(loop_node)==tDO ||
Type(loop_node)==tFOR);
return loop_node->second;
}
AST*& LoopExpr(AST* loop_node)
{
// controlling expr of a loop
assert(Type(loop_node)==tWHILE ||
Type(loop_node)==tDO ||
Type(loop_node)==tFOR);
return loop_node->first;
}
AST*& ThenPart(AST* if_node)
{
// then-part of an if statement
assert(Type(if_node)==tIF);
return if_node->second;
}
AST*& ElsePart(AST* if_node)
{
// else-part of an if statement
assert(Type(if_node)==tIF);
return if_node->third;
}
AST*& FuncIdent(AST* func_node)
{
assert(Type(func_node)==tFUNCTION || Type(func_node)==tFUNEX);
return func_node->first;
}
AST*& Formals(AST* func_node)
{
assert(Type(func_node)==tFUNCTION || Type(func_node)==tFUNEX);
return func_node->second;
}
AST*& FuncBody(AST* func_node)
{
assert(Type(func_node)==tFUNCTION || Type(func_node)==tFUNEX);
return func_node->third;
}
AST*& LHS(AST* expr)
{
assert(isAssOp(Type(expr)));
return expr->first;
}
AST*& RHS(AST* expr)
{
assert(isAssOp(Type(expr)));
return expr->second;
}
bool IsPrefix(AST* expr)
{
assert(isUnaryOp(Type(expr)));
return (expr->second != NULL);
}
bool IsPostfix(AST* expr)
{
assert(isUnaryOp(Type(expr)));
return (expr->first != NULL);
}
AST*& LeftOperand(AST* expr)
{
return expr->first;
}
AST*& RightOperand(AST* expr)
{
return expr->second;
}
} // namespace js2cpp