-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVisitor.java
117 lines (94 loc) · 2.12 KB
/
Visitor.java
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
/*
* Visitor
*
* version 1
*
* August 3, 2019
*
* Copyright © 2019 Sabrina Kim, Martial Pastor, Keven Presseau-St-Laurent, Marco Tropiano, Diana Zitting-Rioux. All rights reserved.
*/
import java.util.Stack;
/**
* Visitor class for parser
*
* @version 1
* @author Martial Pastor
*
*/
public class Visitor {
Node astRoot;
Stack<Float> fValues = new Stack<Float>();
String CURFNAME;
public Visitor(Node ast) {
astRoot = ast;
}
/**
* Calculate
* @return float
*/
public float calculate() {
computeExpr(astRoot);
return fValues.peek();
}
/**
* Computer expression
* @param a
*/
public void computeExpr(Node a) {
for (Node node: a.getChildren()) { // preorder traversal
computeExpr(node);
}
if (a.getType().equals("integer") || a.getType().equals("double")) {
float f = Float.parseFloat(a.getLexeme());
fValues.push(f);
}
if(a.getType().equals("function")) {
CURFNAME = a.getLexeme();
float result = applyFunction(fValues.peek());
fValues.pop();
fValues.push(result);
}
if(a.getType().equals("operator")) {
float v1 = fValues.peek();
fValues.pop();
float v2 = fValues.peek();
fValues.pop();
if (a.getLexeme().equals("*")) {
fValues.push(v1*v2);
}
if (a.getLexeme().equals("/")) {
fValues.push(v1/v2);
}
if (a.getLexeme().equals("+")) {
fValues.push(v1+v2);
}
if (a.getLexeme().equals("-")) {
fValues.push(v1-v2);
}
}
}
/**
* Apply function
* @param val
* @return function
*/
private float applyFunction(float val) {
switch (CURFNAME) {
case "exp":
return (float) Calculator.calculateExponent(10, val);
case "cosh":
return (float) Calculator.calculateCosh(val);
case "pow":
return Calculator.calculateTenPower(val);
case "sqrt":
return (float) Calculator.calculateSquareRoot(val);
case "sin":
return (float) Calculator.calculateSine(val);
case "neg":
return (float) -val;
}
System.out.println("\n\n INVALID INPUT: " + CURFNAME);
System.exit(0);
return 0;
}
}