1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.jxpath.ri.compiler;
19
20 import org.apache.commons.jxpath.ri.EvalContext;
21
22
23
24
25 public abstract class CoreOperation extends Operation {
26
27
28 protected static final int OR_PRECEDENCE = 0;
29
30 protected static final int AND_PRECEDENCE = 1;
31
32 protected static final int COMPARE_PRECEDENCE = 2;
33
34 protected static final int RELATIONAL_EXPR_PRECEDENCE = 3;
35
36 protected static final int ADD_PRECEDENCE = 4;
37
38 protected static final int MULTIPLY_PRECEDENCE = 5;
39
40 protected static final int NEGATE_PRECEDENCE = 6;
41
42 protected static final int UNION_PRECEDENCE = 7;
43
44
45
46
47
48
49 public CoreOperation(final Expression[] args) {
50 super(args);
51 }
52
53 @Override
54 public Object compute(final EvalContext context) {
55 return computeValue(context);
56 }
57
58 @Override
59 public abstract Object computeValue(EvalContext context);
60
61
62
63
64
65
66 protected abstract int getPrecedence();
67
68
69
70
71
72
73 public abstract String getSymbol();
74
75
76
77
78
79
80 protected abstract boolean isSymmetric();
81
82
83
84
85
86
87
88
89 private String parenthesize(final Expression expression, final boolean left) {
90 final String s = expression.toString();
91 if (!(expression instanceof CoreOperation)) {
92 return s;
93 }
94 final int compared = getPrecedence() - ((CoreOperation) expression).getPrecedence();
95 if (compared < 0) {
96 return s;
97 }
98 if (compared == 0 && (isSymmetric() || left)) {
99 return s;
100 }
101 return '(' + s + ')';
102 }
103
104 @Override
105 public String toString() {
106 if (args.length == 1) {
107 return getSymbol() + parenthesize(args[0], false);
108 }
109 final StringBuilder buffer = new StringBuilder();
110 for (int i = 0; i < args.length; i++) {
111 if (i > 0) {
112 buffer.append(' ');
113 buffer.append(getSymbol());
114 buffer.append(' ');
115 }
116 buffer.append(parenthesize(args[i], i == 0));
117 }
118 return buffer.toString();
119 }
120 }