-
Notifications
You must be signed in to change notification settings - Fork 0
/
copynode.cpp
90 lines (82 loc) · 3.1 KB
/
copynode.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
#include "nodetype.h"
#include "matrix.hpp"
BasicNode* copyHelp::copyVal(BasicNode* node) //(值类型)拷贝
{
//调用前应该对参数类型进行检查
if(node->getType()==Num)
return new NumNode(*dynamic_cast<NumNode*>(node));
if(node->getType()==String)
return new StringNode(*dynamic_cast<StringNode*>(node));
if(node->getType()==Matrix)
return new matrixNode(*dynamic_cast<matrixNode*>(node));
if(node->getType()==Vector)
return new vectorNode(*dynamic_cast<vectorNode*>(node));
if(node->getType()==Arr)
return new ArrNode(*dynamic_cast<ArrNode*>(node));
if(node->getType()==Null)
return new nullNode();
//warn:支持更多具拷贝构造函数类型(目前都是字面量)后还需要在此处进行添加
return nullptr; //如果进行参数检查了不会走到这一步
}
BasicNode* copyHelp::copyNode(BasicNode* node) //拷贝单个子节点,warn:支持新的常规子节点类型后要进行修改
{
if(copyHelp::isLiteral(node))
return copyHelp::copyVal(node);
if(node->getType()==Var) //Var所有权在域,此处不进行复制,直接返回
return node;
if(node->getType()==Fun)
return new FunNode(*dynamic_cast<FunNode*>(node));
if(node->getType()==VarRef) //VarRef所有权在函数节点,此处不进行复制,直接返回
return node;
if(node->getType()==If)
return new IfNode(*dynamic_cast<IfNode*>(node));
if(node->getType()==While)
return new WhileNode(*dynamic_cast<WhileNode*>(node));
throw string("The type is not regular son nodes to copy"); //Pro不作为常规子节点,不在此考虑
}
void copyHelp::delTree(BasicNode *n)
{
for(BasicNode* node:n->sonNode)
{
if(node->getType()!=Var) //fix:这里没有VarRef,是否错误?
{
delete node;
node=nullptr;
}
}
}
BasicNode::BasicNode(const BasicNode &n)
{
this->retFlag=n.isRet();
for(BasicNode* i:n.sonNode)
this->sonNode.push_back(copyHelp::copyNode(i));
}
IfNode::IfNode(const IfNode &n):conditionalControlNode(n)
{
this->condition=copyHelp::copyNode(n.condition);
this->truePro=copyHelp::copyNode(n.truePro);
this->falsePro=copyHelp::copyNode(n.falsePro);
}
WhileNode::WhileNode(const WhileNode &n):conditionalControlNode(n)
{
this->condition=copyHelp::copyNode(n.condition);
this->body=copyHelp::copyNode(n.body);
}
VarNode::VarNode(VarNode &n):BasicNode(n)
{
this->typeRestrictFlag=n.istypeRestrict();
this->ownershipFlag=n.isOwnership();
this->valtype=n.getValType();
if(this->ownershipFlag) //有所有权拷贝,没有直接赋值
this->val=copyHelp::copyVal(n.eval()); //此处按照默认的策略——只有字面量作为有所有权的值,所以直接调用拷贝字面量的方法进行拷贝
else
this->val=n.eval();
}
ArrNode::ArrNode(const ArrNode &n):BasicNode(n)
{
this->typeRestrictFlag=n.istypeRestrict();
this->valtype=n.getValType();
this->len=n.getLen();
for(VarNode* pn:n.allelm)
this->allelm.push_back(new VarNode(*pn));
}