use of com.github.javaparser.ast.Node in project drools by kiegroup.
the class CommonCodegenUtilsTest method replaceNodesInBlock.
@Test
public void replaceNodesInBlock() {
final BlockStmt toRead = getBlockStmt();
final List<NameExpr> retrieved = CommonCodegenUtils.getNameExprsFromBlock(toRead, "value");
assertEquals(2, retrieved.size());
final List<NullLiteralExpr> nullExprs = toRead.stream().filter(node -> node instanceof NullLiteralExpr).map(NullLiteralExpr.class::cast).collect(Collectors.toList());
assertNotNull(nullExprs);
assertTrue(nullExprs.isEmpty());
final List<CommonCodegenUtils.ReplacementTupla> replacementTuplas = retrieved.stream().map(nameExpr -> {
NullLiteralExpr toAdd = new NullLiteralExpr();
nullExprs.add(toAdd);
return new CommonCodegenUtils.ReplacementTupla(nameExpr, toAdd);
}).collect(Collectors.toList());
CommonCodegenUtils.replaceNodesInStatement(toRead, replacementTuplas);
final List<NameExpr> newRetrieved = CommonCodegenUtils.getNameExprsFromBlock(toRead, "value");
assertTrue(newRetrieved.isEmpty());
final List<NullLiteralExpr> retrievedNullExprs = toRead.stream().filter(node -> node instanceof NullLiteralExpr).map(NullLiteralExpr.class::cast).collect(Collectors.toList());
assertNotNull(nullExprs);
assertEquals(nullExprs.size(), retrievedNullExprs.size());
nullExprs.forEach(nullExpr -> assertTrue(retrievedNullExprs.contains(nullExpr)));
}
use of com.github.javaparser.ast.Node in project drools by kiegroup.
the class ExpressionTyper method drlNameExpr.
private Optional<TypedExpressionCursor> drlNameExpr(Expression drlxExpr, DrlNameExpr firstNode, boolean isInLineCast, java.lang.reflect.Type originalTypeCursor) {
String firstName = firstNode.getName().getIdentifier();
java.lang.reflect.Type typeCursor;
// In OOPath a declaration is based on a position rather than a name.
// Only an OOPath chunk can have a backreference expression
Optional<DeclarationSpec> backReference = empty();
if (firstNode.getBackReferencesCount() > 0) {
List<DeclarationSpec> ooPathDeclarations = ruleContext.getOOPathDeclarations();
DeclarationSpec backReferenceDeclaration = ooPathDeclarations.get(ooPathDeclarations.size() - 1 - firstNode.getBackReferencesCount());
typeCursor = backReferenceDeclaration.getDeclarationClass();
backReference = of(backReferenceDeclaration);
context.addUsedDeclarations(backReferenceDeclaration.getBindingId());
} else {
typeCursor = originalTypeCursor;
}
try {
Class<?> resolvedType = ruleContext.getTypeResolver().resolveType(firstName);
return of(new TypedExpressionCursor(new NameExpr(firstName), resolvedType));
} catch (ClassNotFoundException e) {
// ignore
}
Class<?> classCursor = toRawClass(typeCursor);
if (classCursor != null) {
Method firstAccessor = DrlxParseUtil.getAccessor(!isInLineCast ? classCursor : patternType, firstName, ruleContext);
if (firstAccessor != null) {
if (!"".equals(firstName)) {
context.addReactOnProperties(firstName);
}
NameExpr thisAccessor = new NameExpr(THIS_PLACEHOLDER);
NameExpr scope = backReference.map(d -> new NameExpr(d.getBindingId())).orElse(thisAccessor);
Expression fieldAccessor = new MethodCallExpr(scope, firstAccessor.getName());
if (isInLineCast) {
return of(new TypedExpressionCursor(fieldAccessor, typeCursor));
}
Optional<java.lang.reflect.Type> castType = ruleContext.explicitCastType(firstName).flatMap(t -> safeResolveType(ruleContext.getTypeResolver(), t.asString()));
if (castType.isPresent()) {
java.lang.reflect.Type typeOfFirstAccessor = castType.get();
ClassOrInterfaceType typeWithoutDollar = toClassOrInterfaceType(typeOfFirstAccessor.getTypeName());
return of(new TypedExpressionCursor(addCastToExpression(typeWithoutDollar, fieldAccessor, false), typeOfFirstAccessor));
}
return of(new TypedExpressionCursor(fieldAccessor, firstAccessor.getGenericReturnType()));
}
Field field = DrlxParseUtil.getField(classCursor, firstName);
if (field != null) {
NameExpr scope = new NameExpr(Modifier.isStatic(field.getModifiers()) ? classCursor.getCanonicalName() : THIS_PLACEHOLDER);
return of(new TypedExpressionCursor(new FieldAccessExpr(scope, field.getName()), field.getType()));
}
}
Optional<DeclarationSpec> declarationById = ruleContext.getDeclarationById(firstName);
if (declarationById.isPresent()) {
// do NOT append any reactOnProperties.
// because reactOnProperties is referring only to the properties of the type of the pattern, not other declarations properites.
context.addUsedDeclarations(firstName);
typeCursor = isInLineCast ? originalTypeCursor : declarationById.get().getDeclarationClass();
return of(new TypedExpressionCursor(new NameExpr(firstName), typeCursor));
}
if (packageModel.getGlobals().containsKey(firstName)) {
context.addUsedDeclarations(firstName);
return of(new TypedExpressionCursor(new NameExpr(firstName), packageModel.getGlobals().get(firstName)));
}
final Optional<Node> rootNode = findRootNodeViaParent(drlxExpr);
rootNode.ifPresent(n -> {
// In the error messages HalfBinary are transformed to Binary
Node withHalfBinaryReplaced = replaceAllHalfBinaryChildren(n);
ruleContext.addCompilationError(new ParseExpressionErrorResult((Expression) withHalfBinaryReplaced, ruleContext.getCurrentConstraintDescr()));
});
return empty();
}
use of com.github.javaparser.ast.Node in project drools by kiegroup.
the class ExpressionTyper method processFirstNode.
private Optional<TypedExpressionCursor> processFirstNode(Expression drlxExpr, List<Node> childNodes, Node firstNode, boolean isInLineCast, java.lang.reflect.Type originalTypeCursor) {
Optional<TypedExpressionCursor> result;
if (isThisExpression(firstNode) || (firstNode instanceof DrlNameExpr && printNode(firstNode).equals(bindingId))) {
result = of(thisExpr(drlxExpr, childNodes, isInLineCast, originalTypeCursor));
} else if (firstNode instanceof DrlNameExpr) {
result = drlNameExpr(drlxExpr, (DrlNameExpr) firstNode, isInLineCast, originalTypeCursor);
} else if (firstNode instanceof NameExpr) {
result = drlNameExpr(drlxExpr, new DrlNameExpr(((NameExpr) firstNode).getName()), isInLineCast, originalTypeCursor);
} else if (firstNode instanceof FieldAccessExpr) {
if (((FieldAccessExpr) firstNode).getScope() instanceof ThisExpr) {
result = of(fieldAccessExpr(originalTypeCursor, ((FieldAccessExpr) firstNode).getName()));
} else {
try {
Class<?> resolvedType = ruleContext.getTypeResolver().resolveType(PrintUtil.printNode(firstNode));
result = of(new TypedExpressionCursor(new NameExpr(PrintUtil.printNode(firstNode)), resolvedType));
} catch (ClassNotFoundException e) {
result = empty();
}
}
} else if (firstNode instanceof NullSafeFieldAccessExpr && ((NullSafeFieldAccessExpr) firstNode).getScope() instanceof ThisExpr) {
result = of(fieldAccessExpr(originalTypeCursor, ((NullSafeFieldAccessExpr) firstNode).getName()));
} else if (firstNode instanceof MethodCallExpr) {
Optional<Expression> scopeExpr = ((MethodCallExpr) firstNode).getScope();
Optional<DeclarationSpec> scopeDecl = scopeExpr.flatMap(scope -> ruleContext.getDeclarationById(PrintUtil.printNode(scope)));
Expression scope;
java.lang.reflect.Type type;
if (scopeDecl.isPresent() && !scopeDecl.get().getBindingId().equals(bindingId)) {
type = scopeDecl.get().getDeclarationClass();
scope = new NameExpr(scopeDecl.get().getBindingId());
context.addUsedDeclarations(scopeDecl.get().getBindingId());
} else if (scopeExpr.isPresent()) {
TypedExpressionCursor parsedScope = processFirstNode(drlxExpr, childNodes, scopeExpr.get(), isInLineCast, originalTypeCursor).get();
type = parsedScope.typeCursor;
scope = parsedScope.expressionCursor;
} else {
type = originalTypeCursor;
scope = new NameExpr(THIS_PLACEHOLDER);
}
result = of(methodCallExpr((MethodCallExpr) firstNode, type, scope));
} else if (firstNode instanceof ObjectCreationExpr) {
result = of(objectCreationExpr((ObjectCreationExpr) firstNode));
} else if (firstNode instanceof StringLiteralExpr) {
result = of(stringLiteralExpr((StringLiteralExpr) firstNode));
} else if (firstNode instanceof EnclosedExpr) {
result = processFirstNode(drlxExpr, childNodes, ((EnclosedExpr) firstNode).getInner(), isInLineCast, originalTypeCursor);
} else if (firstNode instanceof CastExpr) {
result = castExpr((CastExpr) firstNode, drlxExpr, childNodes, isInLineCast, originalTypeCursor);
} else if (firstNode instanceof ArrayCreationExpr) {
result = of(arrayCreationExpr(((ArrayCreationExpr) firstNode)));
} else if (firstNode instanceof BinaryExpr) {
result = of(binaryExpr((BinaryExpr) firstNode));
} else if (firstNode instanceof ArrayAccessExpr) {
Optional<DeclarationSpec> scopeDecl = ruleContext.getDeclarationById(((ArrayAccessExpr) firstNode).getName().toString());
Expression scope;
java.lang.reflect.Type type;
if (scopeDecl.isPresent() && !scopeDecl.get().getBindingId().equals(bindingId)) {
type = scopeDecl.get().getDeclarationClass();
scope = new NameExpr(scopeDecl.get().getBindingId());
context.addUsedDeclarations(scopeDecl.get().getBindingId());
} else {
type = originalTypeCursor;
scope = new NameExpr(THIS_PLACEHOLDER);
}
result = arrayAccessExpr((ArrayAccessExpr) firstNode, type, scope);
} else if (firstNode instanceof MapCreationLiteralExpression) {
result = mapCreationLiteral((MapCreationLiteralExpression) firstNode, originalTypeCursor);
} else if (firstNode instanceof ListCreationLiteralExpression) {
result = listCreationLiteral((ListCreationLiteralExpression) firstNode, originalTypeCursor);
} else {
result = of(new TypedExpressionCursor((Expression) firstNode, getExpressionType(ruleContext, ruleContext.getTypeResolver(), (Expression) firstNode, context.getUsedDeclarations())));
}
if (result.isPresent()) {
processNullSafeDereferencing(drlxExpr);
}
return result.map(te -> {
if (isInLineCast) {
Expression exprWithInlineCast = addCastToExpression(toRawClass(te.typeCursor), te.expressionCursor, isInLineCast);
return new TypedExpressionCursor(exprWithInlineCast, te.typeCursor);
} else {
return te;
}
});
}
use of com.github.javaparser.ast.Node in project drools by kiegroup.
the class ExpressionTyper method toTypedExpressionFromMethodCallOrField.
private TypedExpressionResult toTypedExpressionFromMethodCallOrField(Expression drlxExpr) {
if (drlxExpr instanceof FieldAccessExpr) {
// try to see if it's a constant
final Optional<TypedExpression> typedExpression = tryParseAsConstantField(ruleContext.getTypeResolver(), ((FieldAccessExpr) drlxExpr).getScope(), ((FieldAccessExpr) drlxExpr).getNameAsString());
if (typedExpression.isPresent()) {
return new TypedExpressionResult(typedExpression, context);
}
}
if (patternType == null && drlxExpr instanceof NullSafeFieldAccessExpr) {
// try to see if it's a constant
final Optional<TypedExpression> typedExpression = tryParseAsConstantField(ruleContext.getTypeResolver(), ((NullSafeFieldAccessExpr) drlxExpr).getScope(), ((NullSafeFieldAccessExpr) drlxExpr).getNameAsString());
if (typedExpression.isPresent()) {
return new TypedExpressionResult(typedExpression, context);
}
}
final List<Node> childrenNodes = flattenScope(ruleContext.getTypeResolver(), drlxExpr);
final Node firstChild = childrenNodes.get(0);
boolean isInLineCast = firstChild instanceof InlineCastExpr;
java.lang.reflect.Type originalTypeCursor;
final Node firstNode;
if (isInLineCast) {
InlineCastExpr inlineCast = (InlineCastExpr) firstChild;
originalTypeCursor = originalTypeCursorFromInlineCast(inlineCast);
firstNode = inlineCast.getExpression();
if (inlineCast.getExpression().isThisExpr()) {
context.setInlineCastExpression(Optional.of(new InstanceOfExpr(new NameExpr(THIS_PLACEHOLDER), (ReferenceType) inlineCast.getType())));
} else {
context.setInlineCastExpression(toTypedExpression(inlineCast.getExpression()).getTypedExpression().map(TypedExpression::getExpression).map(expr -> new InstanceOfExpr(expr, (ReferenceType) inlineCast.getType())));
}
} else {
originalTypeCursor = patternType;
firstNode = firstChild;
}
if (originalTypeCursor != null && originalTypeCursor.equals(Object.class)) {
// try infer type from the declarations
final Optional<DeclarationSpec> declarationById = ruleContext.getDeclarationById(printNode(firstChild));
originalTypeCursor = declarationById.map(d -> (java.lang.reflect.Type) d.getDeclarationClass()).orElse(originalTypeCursor);
}
final Optional<TypedExpressionCursor> teCursor = processFirstNode(drlxExpr, childrenNodes, firstNode, isInLineCast, originalTypeCursor);
if (firstNode instanceof MethodCallExpr) {
MethodCallExpr me = (MethodCallExpr) firstNode;
addReactOnProperty(me.getNameAsString(), me.getArguments());
}
if (firstNode instanceof NullSafeMethodCallExpr) {
NullSafeMethodCallExpr me = (NullSafeMethodCallExpr) firstNode;
addReactOnProperty(me.getNameAsString(), me.getArguments());
}
if (!teCursor.isPresent()) {
return new TypedExpressionResult(empty(), context);
}
Expression previous = teCursor.get().expressionCursor;
java.lang.reflect.Type typeCursor = teCursor.get().typeCursor;
List<Node> childrenWithoutFirst = childrenNodes.subList(1, childrenNodes.size());
for (Node part : childrenWithoutFirst) {
if (part instanceof SimpleName) {
String field = part.toString();
TypedExpression expression = nameExprToMethodCallExpr(field, typeCursor, previous, ruleContext);
if (expression == null) {
ruleContext.addCompilationError(new InvalidExpressionErrorResult("Unknown field " + field + " on " + typeCursor));
break;
}
typeCursor = expression.getType();
previous = expression.getExpression();
} else if (part instanceof MethodCallExpr) {
TypedExpressionCursor typedExpr = methodCallExpr((MethodCallExpr) part, typeCursor, previous);
typeCursor = typedExpr.typeCursor;
previous = typedExpr.expressionCursor;
} else if (part instanceof NullSafeMethodCallExpr) {
TypedExpressionCursor typedExpr = nullSafeMethodCallExpr((NullSafeMethodCallExpr) part, typeCursor, previous);
typeCursor = typedExpr.typeCursor;
previous = typedExpr.expressionCursor;
} else if (part instanceof InlineCastExpr && ((InlineCastExpr) part).getExpression() instanceof FieldAccessExpr) {
InlineCastExpr inlineCastExprPart = (InlineCastExpr) part;
final FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) inlineCastExprPart.getExpression();
final TypedExpression toMethodCallExpr = nameExprToMethodCallExpr(fieldAccessExpr.getNameAsString(), typeCursor, previous, ruleContext);
if (toMethodCallExpr == null) {
ruleContext.addCompilationError(new InvalidExpressionErrorResult("Unknown field " + fieldAccessExpr.getNameAsString() + " on " + typeCursor));
break;
}
final Class<?> castClass = getClassFromType(ruleContext.getTypeResolver(), inlineCastExprPart.getType());
previous = addCastToExpression(castClass, toMethodCallExpr.getExpression(), false);
typeCursor = castClass;
} else if (part instanceof ArrayAccessExpr) {
final ArrayAccessExpr inlineCastExprPart = (ArrayAccessExpr) part;
TypedExpressionCursor typedExpr = arrayAccessExpr(inlineCastExprPart, typeCursor, previous).orElseThrow(() -> new NoSuchElementException("ArrayAccessExpr doesn't contain TypedExpressionCursor!"));
typeCursor = typedExpr.typeCursor;
previous = typedExpr.expressionCursor;
} else {
throw new UnsupportedOperationException();
}
}
return new TypedExpressionResult(of(new TypedExpression(previous, typeCursor, accessorToFieldName(drlxExpr))), context);
}
use of com.github.javaparser.ast.Node in project drools by kiegroup.
the class AccumulateInline method parseInitBlock.
private void parseInitBlock() {
MethodDeclaration initMethod = getMethodFromTemplateClass("init");
String mvelBlock = addCurlyBracesToBlock(addSemicolon(accumulateDescr.getInitCode()));
CompiledBlockResult initCodeCompilationResult = mvelCompiler.compileStatement(mvelBlock);
BlockStmt initBlock = initCodeCompilationResult.statementResults();
for (Statement stmt : initBlock.getStatements()) {
final BlockStmt initMethodBody = initMethod.getBody().orElseThrow(InvalidInlineTemplateException::new);
if (stmt.isExpressionStmt() && stmt.asExpressionStmt().getExpression().isVariableDeclarationExpr()) {
VariableDeclarationExpr vdExpr = stmt.asExpressionStmt().getExpression().asVariableDeclarationExpr();
for (VariableDeclarator vd : vdExpr.getVariables()) {
final String variableName = vd.getNameAsString();
contextFieldNames.add(variableName);
contextData.addField(vd.getType(), variableName, Modifier.publicModifier().getKeyword());
Optional<Expression> optInitializer = vd.getInitializer();
optInitializer.ifPresent(initializer -> {
Expression target = new FieldAccessExpr(getDataNameExpr(), variableName);
Statement initStmt = new ExpressionStmt(new AssignExpr(target, initializer, AssignExpr.Operator.ASSIGN));
initMethodBody.addStatement(initStmt);
initStmt.findAll(NameExpr.class).stream().map(Node::toString).filter(context::hasDeclaration).forEach(usedExternalDeclarations::add);
});
accumulateDeclarations.add(new DeclarationSpec(variableName, DrlxParseUtil.getClassFromContext(context.getTypeResolver(), vd.getType().asString())));
}
}
}
}
Aggregations