forked from apache/incubator-kie-drools
-
Notifications
You must be signed in to change notification settings - Fork 25
/
MVELDumper.java
554 lines (492 loc) · 22.1 KB
/
MVELDumper.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.lang;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.drools.core.base.EvaluatorWrapper;
import org.drools.core.base.evaluators.Operator;
import org.drools.compiler.compiler.DrlExprParser;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.BindingDescr;
import org.drools.compiler.lang.descr.ConstraintConnectiveDescr;
import org.drools.compiler.lang.descr.OperatorDescr;
import org.drools.compiler.lang.descr.RelationalExprDescr;
import org.drools.core.util.ReflectiveVisitor;
import org.drools.compiler.lang.descr.AtomicExprDescr;
import org.drools.compiler.lang.descr.ExprConstraintDescr;
import org.drools.compiler.rule.builder.RuleBuildContext;
import static org.drools.core.util.ClassUtils.findClass;
import static org.drools.core.util.StringUtils.indexOfOutOfQuotes;
import static org.drools.compiler.rule.builder.dialect.DialectUtil.findClassByName;
public class MVELDumper extends ReflectiveVisitor implements ExpressionRewriter {
private static final java.util.regex.Pattern evalRegexp = java.util.regex.Pattern.compile( "^eval\\s*\\(", Pattern.MULTILINE );
private static final String[] standard;
static {
standard = new String[]{ "==", "<", ">", ">=", "<=", "!=", "~=", "instanceof" };
Arrays.sort( standard );
}
public String dump( BaseDescr base ) {
return dump( new StringBuilder(),
base,
0,
false,
createContext() ).toString();
}
public String dump( BaseDescr base,
MVELDumperContext context ) {
return dump( new StringBuilder(),
base,
0,
false,
context ).toString();
}
public String dump( BaseDescr base,
int parentPrecedence ) {
return dump( new StringBuilder(),
base,
parentPrecedence,
false,
createContext() ).toString();
}
public StringBuilder dump( StringBuilder sbuilder,
BaseDescr base,
int parentPriority,
boolean isInsideRelCons,
MVELDumperContext context ) {
if ( context == null ) {
context = createContext();
}
if ( base instanceof ConstraintConnectiveDescr) {
processConnectiveDescr( sbuilder, base, parentPriority, isInsideRelCons, context );
} else if ( base instanceof AtomicExprDescr ) {
sbuilder.append( processAtomicExpression(context, (AtomicExprDescr) base) );
} else if ( base instanceof BindingDescr) {
processBinding(sbuilder, (BindingDescr) base, isInsideRelCons, context);
} else if ( base instanceof RelationalExprDescr) {
processRelationalExpression(sbuilder, (RelationalExprDescr) base, context);
} else if ( base instanceof ExprConstraintDescr ) {
processConstraint(sbuilder, (ExprConstraintDescr) base, isInsideRelCons, context);
}
return sbuilder;
}
private void processConstraint(StringBuilder sbuilder, ExprConstraintDescr base, boolean isInsideRelCons, MVELDumperContext context) {
DrlExprParser expr = new DrlExprParser( context.getRuleContext().getConfiguration().getLanguageLevel() );
ConstraintConnectiveDescr result = expr.parse( base.getExpression() );
if ( result.getDescrs().size() == 1 ) {
dump( sbuilder,
result.getDescrs().get( 0 ),
0,
isInsideRelCons,
context );
} else {
dump( sbuilder,
result,
0,
isInsideRelCons,
context );
}
}
private String processAtomicExpression(MVELDumperContext context, AtomicExprDescr atomicExpr) {
String expr = atomicExpr.getExpression().trim();
expr = processEval(expr);
String[] constrAndExpr = processImplicitConstraints(expr, atomicExpr, context);
return constrAndExpr[0] + constrAndExpr[1];
}
private void processBinding(StringBuilder sbuilder, BindingDescr bind, boolean isInsideRelCons, MVELDumperContext context) {
String expr = bind.getExpression().trim();
AtomicExprDescr atomicExpr = new AtomicExprDescr(expr);
String[] constrAndExpr = processImplicitConstraints(expr, atomicExpr, context);
if ( isInsideRelCons ) {
sbuilder.append( constrAndExpr[0] ).append( constrAndExpr[1] );
} else if ( constrAndExpr[0].length() > 4 ) {
sbuilder.append( constrAndExpr[0].substring( 0, constrAndExpr[0].length() - 4 ) );
}
bind.setExpression( constrAndExpr[1] );
context.addBinding(bind);
}
private void processRelationalExpression(StringBuilder sbuilder, RelationalExprDescr red, MVELDumperContext context) {
// maximum precedence, so wrap any child connective in parenthesis
StringBuilder left = dump(new StringBuilder(), red.getLeft(), Integer.MAX_VALUE, true, context);
StringBuilder right = red.getRight() instanceof AtomicExprDescr ?
processRightAtomicExpr(left, (AtomicExprDescr)red.getRight(), context) :
dump( new StringBuilder(), red.getRight(), Integer.MAX_VALUE, true, context);
processRestriction( context,
sbuilder,
left.toString(),
red.getOperatorDescr(),
right.toString() );// maximum precedence, so wrap any child connective in parenthesis
}
private StringBuilder processRightAtomicExpr(StringBuilder left, AtomicExprDescr atomicExpr, MVELDumperContext context) {
String expr = atomicExpr.getExpression().trim();
expr = processEval( expr );
String[] constrAndExpr = processImplicitConstraints(expr, atomicExpr, context);
left.insert( 0, constrAndExpr[0] );
return new StringBuilder( constrAndExpr[1] );
}
String[] processImplicitConstraints(String expr, AtomicExprDescr atomicExpr, MVELDumperContext context) {
boolean hasQuotes = expr.indexOf('"') >= 0;
String[] constrAndExpr = new String[] { "", expr };
int sharpPos = hasQuotes ? indexOfOutOfQuotes(expr, '#') : expr.indexOf('#');
int nullSafePos = hasQuotes ? indexOfOutOfQuotes(expr, "!.") : expr.indexOf("!.");
while (sharpPos > 0 || nullSafePos > 0) {
if ( nullSafePos < 0 || ( sharpPos > 0 && sharpPos < nullSafePos ) ) {
String[] castAndExpr = processInlineCast(expr, atomicExpr, context, sharpPos);
expr = castAndExpr[1];
constrAndExpr = new String[] { constrAndExpr[0] + castAndExpr[0], expr };
} else {
String[] nullCheckAndExpr = processNullSafeDereferencing(expr, atomicExpr, nullSafePos);
expr = nullCheckAndExpr[1];
constrAndExpr = new String[] { constrAndExpr[0].contains(nullCheckAndExpr[0]) ? constrAndExpr[0] : constrAndExpr[0] + nullCheckAndExpr[0], expr };
}
sharpPos = hasQuotes ? indexOfOutOfQuotes(expr, '#') : expr.indexOf('#');
nullSafePos = hasQuotes ? indexOfOutOfQuotes(expr, "!.") : expr.indexOf("!.");
}
return new String[] { constrAndExpr[0], processInferredCast(constrAndExpr[1], atomicExpr, context) };
}
private String[] processInlineCast(String expr, AtomicExprDescr atomicExpr, MVELDumperContext context, int sharpPos) {
// convert "field1#Class.field2" in ["field1 instanceof Class && ", "((Class)field1).field2"]
String field1 = expr.substring(0, sharpPos).trim();
int sharpPos2 = expr.indexOf('#', sharpPos+1);
String part2 = sharpPos2 < 0 ? expr.substring(sharpPos+1).trim() : expr.substring(sharpPos+1, sharpPos2).trim();
String[] classAndField = splitInClassAndField(part2, context);
if (classAndField == null) {
return new String[] { "", expr };
}
String className = classAndField[0];
String field2 = classAndField[1];
String castedExpression = "((" + className + ")" + field1 + ")." + field2 + (sharpPos2 > 0 ? expr.substring(sharpPos2) : "");
atomicExpr.setRewrittenExpression(castedExpression);
return new String[] { field1 + " instanceof " + className + " && ", castedExpression };
}
private String processInferredCast(String expr, AtomicExprDescr atomicExpr, MVELDumperContext context) {
if (context == null) {
return expr;
}
Map.Entry<String, String> castEntry = context.getInferredCast(expr);
if (castEntry == null) {
return expr;
}
String castedExpr = "((" + castEntry.getValue() + ")" + castEntry.getKey() + ")" + expr.substring(castEntry.getKey().length());
atomicExpr.setRewrittenExpression(castedExpr);
return castedExpr;
}
private String[] processNullSafeDereferencing(String expr, AtomicExprDescr atomicExpr, int nullSafePos) {
// convert "field1!.field2" in ["field1 != null && ", "field1.field2"]
String field1 = expr.substring(0, nullSafePos).trim();
expr = field1 + "." + expr.substring(nullSafePos+2).trim();
String[] nullCheckAndExpr = new String[] { getPreconditionsToAppend(field1) + " != null && ", expr };
atomicExpr.setRewrittenExpression(nullCheckAndExpr[1]);
return nullCheckAndExpr;
}
private String getPreconditionsToAppend(String field1) {
int parenthesisDepth = 0;
int squareDepth = 0;
String precondition = field1;
for (int i = field1.length()-1; i >= 0; i--) {
switch (field1.charAt(i)) {
case '(':
parenthesisDepth--;
if (parenthesisDepth < 0) {
return field1.substring(i+1, field1.length()).trim();
}
break;
case ')':
parenthesisDepth++;
break;
case '[':
squareDepth--;
if (squareDepth < 0) {
return field1.substring(i+1, field1.length()).trim();
}
break;
case ']':
squareDepth++;
break;
case ',':
if (squareDepth == 0 && parenthesisDepth == 0) {
return field1.substring(i+1, field1.length()).trim();
}
break;
}
}
return field1;
}
private String processEval(String expr) {
// stripping "eval" as it is no longer necessary
return evalRegexp.matcher( expr ).find() ? expr.substring( expr.indexOf( '(' ) + 1, expr.lastIndexOf( ')' ) ) : expr;
}
private String[] splitInClassAndField(String expr, MVELDumperContext context) {
String[] split = expr.split("\\.");
if (split.length < 2) {
return null;
}
if (split[0].endsWith("!")) {
split[0] = split[0].substring(0, split[0].length()-1);
}
if (split.length < 3) {
return split;
}
// check non-FQN case first
if ( context == null || findClassByName(context.getRuleContext(), split[0]) != null ) {
return new String[] { split[0], concatDotSeparated(split, 1, split.length) };
}
ClassLoader cl = context.getRuleContext().getPackageBuilder().getRootClassLoader();
for (int i = split.length-1; i > 1; i++) {
String className = concatDotSeparated(split, 0, i);
if (className.endsWith("!")) {
className = className.substring(0, className.length()-1);
}
if (findClass(className, cl) != null) {
return new String[] { className, concatDotSeparated(split, i, split.length) };
}
}
return null;
}
private String concatDotSeparated(String[] parts, int start, int end) {
StringBuilder sb = new StringBuilder( parts[start] );
for (int i = start+1; i < end; i++) {
sb.append(".").append(parts[i]);
}
return sb.toString();
}
protected void processConnectiveDescr( StringBuilder sbuilder,
BaseDescr base,
int parentPriority,
boolean isInsideRelCons,
MVELDumperContext context ) {
ConstraintConnectiveDescr ccd = (ConstraintConnectiveDescr) base;
boolean wrapParenthesis = parentPriority > ccd.getConnective().getPrecedence();
if ( wrapParenthesis ) {
sbuilder.append( "( " );
}
boolean first = true;
for ( BaseDescr constr : ccd.getDescrs() ) {
if ( !( constr instanceof BindingDescr ) ) {
if ( first ) {
first = false;
} else {
sbuilder.append( " " );
sbuilder.append( ccd.getConnective().toString() );
sbuilder.append( " " );
}
}
dump( sbuilder,
constr,
ccd.getConnective().getPrecedence(),
isInsideRelCons,
context );
}
if( first ) {
// means all children were actually only bindings, replace by just true
sbuilder.append( "true" );
}
if ( wrapParenthesis ) {
sbuilder.append( " )" );
}
}
public void processRestriction( MVELDumperContext context,
StringBuilder sbuilder,
String left,
OperatorDescr operator,
String right ) {
Operator op = Operator.determineOperator( operator.getOperator(),
operator.isNegated() );
if ( op == Operator.determineOperator( "memberOf",
operator.isNegated() ) ) {
int lastAndPos = left.lastIndexOf("&&");
if ( lastAndPos > 0 ) {
sbuilder.append( left.substring(0, lastAndPos).trim() ).append( " && " );
left = left.substring(lastAndPos + 2).trim();
}
sbuilder.append( evaluatorPrefix( operator.isNegated() ) )
.append( right )
.append( " contains " )
.append( left )
.append( evaluatorSufix( operator.isNegated() ) );
} else if ( op == Operator.determineOperator( "contains",
operator.isNegated() ) ) {
sbuilder.append( evaluatorPrefix( operator.isNegated() ) )
.append( left )
.append( " contains " )
.append( right )
.append( evaluatorSufix( operator.isNegated() ) );
} else if ( op == Operator.determineOperator( "excludes",
operator.isNegated() ) ) {
sbuilder.append( evaluatorPrefix( !operator.isNegated() ) )
.append( left )
.append( " contains " )
.append( right )
.append( evaluatorSufix( !operator.isNegated() ) );
} else if ( op == Operator.determineOperator( "matches",
operator.isNegated() ) ) {
sbuilder.append( evaluatorPrefix( operator.isNegated() ) )
.append( left )
.append( " ~= " )
.append( right )
.append( evaluatorSufix( operator.isNegated() ) );
} else if ( lookupBasicOperator( operator.getOperator() ) ) {
if (operator.getOperator().equals("instanceof")) {
context.addInferredCast(left, right);
}
rewriteBasicOperator( sbuilder, left, operator, right );
} else {
// rewrite operator as a function call
rewriteOperator( context, sbuilder, left, operator, right );
}
}
protected void rewriteBasicOperator( StringBuilder sbuilder,
String left,
OperatorDescr operator,
String right) {
sbuilder.append( evaluatorPrefix( operator.isNegated() ) )
.append( left )
.append( " " )
.append( operator.getOperator() )
.append( " " )
.append( right )
.append( evaluatorSufix( operator.isNegated() ) );
}
protected boolean lookupBasicOperator( String op ) {
return Arrays.binarySearch( standard, op ) >= 0;
}
protected void rewriteOperator( MVELDumperContext context,
StringBuilder sbuilder,
String left,
OperatorDescr operator,
String right ) {
String alias = context.createAlias( operator );
operator.setLeftString( left );
operator.setRightString( right );
sbuilder.append( evaluatorPrefix( operator.isNegated() ) )
.append( alias )
.append( ".evaluate( " )
.append( left )
.append( ", " )
.append( right )
.append( " )" )
.append( evaluatorSufix( operator.isNegated() ) );
}
protected String evaluatorPrefix(final boolean isNegated) {
if ( isNegated ) {
return "!( ";
}
return "";
}
protected String evaluatorSufix(final boolean isNegated) {
if ( isNegated ) {
return " )";
}
return "";
}
protected MVELDumperContext createContext() {
return new MVELDumperContext();
}
public Class<?> getEvaluatorWrapperClass() {
return EvaluatorWrapper.class;
}
public static class MVELDumperContext {
protected Map<String, OperatorDescr> aliases;
protected int counter;
protected List<BindingDescr> bindings;
protected Map<String, Class<?>> localTypes;
private RuleBuildContext ruleContext;
private Map<String, String> inferredCasts;
public MVELDumperContext() {
this.aliases = new HashMap<String, OperatorDescr>();
this.counter = 0;
this.bindings = null;
this.localTypes = null;
}
public void clear() {
this.aliases.clear();
this.counter = 0;
this.bindings = null;
this.localTypes = null;
}
public void addInferredCast(String var, String cast) {
if (inferredCasts == null) {
inferredCasts = new HashMap<String, String>();
}
inferredCasts.put(var, cast);
}
public Map.Entry<String, String> getInferredCast(String expr) {
if (inferredCasts != null) {
for (Map.Entry<String, String> entry : inferredCasts.entrySet()) {
if (expr.matches(entry.getKey() + "\\s*\\..+")) {
return entry;
}
}
}
return null;
}
/**
* @return the aliases
*/
public Map<String, OperatorDescr> getAliases() {
return aliases;
}
/**
* @param aliases the aliases to set
*/
public void setAliases( Map<String, OperatorDescr> aliases ) {
this.aliases = aliases;
}
/**
* Creates a new alias for the operator, setting it in the descriptor
* class, adding it to the internal Map and returning it as a String
*
* @param operator
* @return
*/
public String createAlias( OperatorDescr operator ) {
String alias = operator.getOperator() + counter++;
operator.setAlias(alias);
this.aliases.put( alias,
operator );
return alias;
}
/**
* Adds a binding to the list of bindings on this context
* @param bind
*/
public void addBinding( BindingDescr bind ) {
if( this.bindings == null ) {
this.bindings = new ArrayList<BindingDescr>();
}
this.bindings.add( bind );
}
@SuppressWarnings("unchecked")
public List<BindingDescr> getBindings() {
return this.bindings == null ? Collections.EMPTY_LIST : this.bindings;
}
public Map<String,Class<?>> getLocalTypes() {
return localTypes;
}
public void setLocalTypes(Map<String, Class<?>> localTypes) {
this.localTypes = localTypes;
}
public RuleBuildContext getRuleContext() {
return ruleContext;
}
public MVELDumperContext setRuleContext(RuleBuildContext ruleContext) {
this.ruleContext = ruleContext;
return this;
}
}
}