-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimaryExp.java
More file actions
80 lines (70 loc) · 3.03 KB
/
PrimaryExp.java
File metadata and controls
80 lines (70 loc) · 3.03 KB
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
/**
* Primary expression (long integer) of mathematical expression for storing in AST for later calculations.
* Can store only integer (guaranteed by internal check).
*/
class PrimaryExp extends AstExpression {
private PrimaryExp(String num) {
super(num);
}
static String[] OPCODES = {"(", ")"};
@Override
String performAction(String[] args) {
return content;
}
static boolean isThisOpCode(String opCode) {
if (opCode == null || opCode.isEmpty()) {
return false;
}
for (String curOp : OPCODES) {
if (opCode.equals(curOp)) {
return true;
}
}
return false;
}
static AstNode parsePrimary(ExpParser parser, boolean isInsideParenthesis) throws ExpressionFormatException {
AstNode res;
String curParserExp = parser.getLast(); // Last fixed expression from the parser
if (TermExp.isThisOpCode(curParserExp)) { // If primary is precede by TermExp ("-" or "+")
return new AstNode(new PrimaryExp("0"));
}
// Is primary - integer?
if (isLongInteger(curParserExp)) {
res = new AstNode(new PrimaryExp(curParserExp));
} else if (isThisOpCode(curParserExp)) { // Is next - parenthesis?
if (curParserExp.equals(OPCODES[0])) { // If "("...
parser.moveNext();
if (parser.isEnd()) { // Opening parenthesis can't stay at the end of the string
throw new ExpressionFormatException("Wrong opening parenthesis detected");
}
// Parse subexpression from the top operations
res = LogicalExp.parseLogical(parser, true);
if (!parser.getLast().equals(OPCODES[1])) { // If next is not ")" - exception
throw new ExpressionFormatException("Wrong opening parenthesis detected");
}
} else { // If ")" instead of "(" - exception
throw new ExpressionFormatException("Wrong closing parenthesis detected");
}
} else { // If any unsupported sequence (not long int and not "(" or ")") - exception
throw new ExpressionFormatException("Wrong expression format");
}
// Move if not the end
if (!parser.isEnd()) {
parser.moveNext();
if (parser.getLast().equals(OPCODES[0])) { // "(" can't stay after an integer or after ")"
throw new ExpressionFormatException("Wrong parenthesis position detected (possibly multiplication missed)");
} else if (parser.getLast().equals(OPCODES[1]) && !isInsideParenthesis) { // No pair for ")"
throw new ExpressionFormatException("Wrong closing parenthesis detected");
}
}
return res;
}
private static boolean isLongInteger(String num) {
try {
Long.parseLong(num);
return num.matches("^([+-])?\\d+$");
} catch (NumberFormatException e) {
return false;
}
}
}