@@ -8,37 +8,75 @@ bool output::isBinOp(const string &c)
88}
99
1010
11- void output::outputAST (BasicNode* now, int fatherpriority )
11+ void output::outputAST (BasicNode* now, const string& FatherOP )
1212{
1313 if (now == nullptr )
1414 return ;
15- if (now->getType () == Num){
16- cout << ((NumNode*)now)->getNum ();
15+ if (now->getType () == Num)
16+ {
17+ double nownum = ((NumNode*)now)->getNum ();
18+ if (nownum < 0 )
19+ cout << ' (' << nownum << ' )' ;
20+ else
21+ cout << nownum;
1722 return ;
1823 }
19- if (now->getType () == Fun){
24+ if (now->getType () == Fun)
25+ {
2026 FunNode* t = (FunNode*)now;
21- Function* l = t->getEntity ();
22- if (output::isBinOp (l->NAME )){
23- if (ast::BinOpPriority[l->NAME ] < fatherpriority)
27+ string op = t->getEntity ()->NAME ;
28+ if (output::isBinOp (op))
29+ {
30+ if (ast::BinOpPriority[op] < ast::BinOpPriority[FatherOP])
2431 cout << ' (' ;
25- outputAST (t->sonNode [0 ], ast::BinOpPriority[l->NAME ]);
26- cout << l->NAME ;
27- outputAST (t->sonNode [1 ], ast::BinOpPriority[l->NAME ]);
28- if (ast::BinOpPriority[l->NAME ] < fatherpriority)
32+ outputAST (t->sonNode [0 ], op);
33+ cout << op;
34+ if (op == " -" && t->sonNode [1 ]->getType () == Fun && ast::BinOpPriority[op] == ast::BinOpPriority[((FunNode*)(t->sonNode [1 ]))->getEntity ()->NAME ])
35+ cout << ' (' ;
36+ outputAST (t->sonNode [1 ], op);
37+ if (ast::BinOpPriority[op] < ast::BinOpPriority[FatherOP])
38+ cout << ' )' ;
39+ if (op == " -" && t->sonNode [1 ]->getType () == Fun && ast::BinOpPriority[op] == ast::BinOpPriority[((FunNode*)(t->sonNode [1 ]))->getEntity ()->NAME ])
2940 cout << ' )' ;
3041 return ;
3142 }
32- cout << l->NAME << ' (' ;
33- for (int i = 0 ; i < l->getParnum (); i++){
43+ cout << op << ' (' ;
44+ int n = t->getEntity ()->getParnum ();
45+ for (int i = 0 ; i < n; i++)
46+ {
3447 outputAST (t->sonNode [i], 0 );
35- if (i != l-> getParnum () - 1 )
48+ if (i != n - 1 )
3649 cout << " ," ;
3750 }
3851 cout << ' )' ;
3952 return ;
4053 }
41- if (now->getType () == Var){
54+ if (now->getType () == Var)
55+ {
4256 cout << ((VarNode*)now)->NAME ;
4357 }
4458}
59+
60+ void output::outputASTstruct (BasicNode* now, int depth)// 方便输出AST结构(并没有找到别的好方法)
61+ {
62+ for (int i = 0 ; i < depth; i++)
63+ cout << ' ' ;
64+ if (now->getType () == Num)
65+ {
66+ cout << ((NumNode*)now)->getNum () << endl;
67+ return ;
68+ }
69+ if (now->getType () == Var)
70+ {
71+ cout << ((VarNode*)now)->NAME << endl;
72+ return ;
73+ }
74+ if (now->getType () == Fun)
75+ {
76+ FunNode* temp = (FunNode*)now;
77+ int n = temp->getEntity ()->getParnum ();
78+ cout << temp->getEntity ()->NAME << endl ;
79+ for (int i = 0 ; i < n; i++)
80+ outputASTstruct (temp->sonNode [i], depth+1 );;
81+ }
82+ }
0 commit comments