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