use of com.github.javaparser.ast.expr.ThisExpr in project javaparser by javaparser.
the class MethodsResolutionTest method thisInAnonymousClass.
@Test
public void thisInAnonymousClass() {
CompilationUnit cu = parseSample("ThisInAnonymousClass");
ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Bar");
ThisExpr thisExpression = Navigator.findNodeOfGivenClass(clazz, ThisExpr.class);
ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(thisExpression);
assertEquals(true, type.isReferenceType());
assertEquals(true, type.asReferenceType().getTypeDeclaration() instanceof JavaParserAnonymousClassDeclaration);
}
use of com.github.javaparser.ast.expr.ThisExpr 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.expr.ThisExpr in project drools by kiegroup.
the class DrlxParseUtil method findRootNodeViaScopeRec.
private static RemoveRootNodeResult findRootNodeViaScopeRec(Expression expr, LinkedList<Expression> acc) {
if (expr.isArrayAccessExpr()) {
throw new RuntimeException("This doesn't work on arrayAccessExpr convert them to a method call");
}
if (expr instanceof EnclosedExpr) {
return findRootNodeViaScopeRec(expr.asEnclosedExpr().getInner(), acc);
} else if (expr instanceof CastExpr) {
return findRootNodeViaScopeRec(expr.asCastExpr().getExpression(), acc);
} else if (expr instanceof ThisExpr) {
return new RemoveRootNodeResult(Optional.of(expr), expr, expr);
} else if (expr instanceof NodeWithTraversableScope) {
final NodeWithTraversableScope exprWithScope = (NodeWithTraversableScope) expr;
return exprWithScope.traverseScope().flatMap((Expression scope) -> {
if (isDslTopLevelNamespace(scope)) {
return empty();
}
Expression sanitizedExpr = DrlxParseUtil.transformDrlNameExprToNameExpr(expr);
acc.addLast(sanitizedExpr.clone());
return of(findRootNodeViaScopeRec(scope, acc));
}).orElse(new RemoveRootNodeResult(Optional.of(expr), expr, acc.isEmpty() ? expr : acc.getLast()));
} else if (expr instanceof NameExpr) {
if (!acc.isEmpty() && acc.getLast() instanceof NodeWithOptionalScope<?>) {
((NodeWithOptionalScope<?>) acc.getLast()).setScope(null);
for (ListIterator<Expression> iterator = acc.listIterator(); iterator.hasNext(); ) {
Expression e = iterator.next();
if (e instanceof NodeWithOptionalScope) {
NodeWithOptionalScope<?> node = (NodeWithOptionalScope<?>) e;
if (iterator.hasNext()) {
node.setScope(acc.get(iterator.nextIndex()));
}
}
}
return new RemoveRootNodeResult(Optional.of(expr), acc.getFirst(), acc.getLast());
} else {
return new RemoveRootNodeResult(Optional.of(expr), expr, expr);
}
}
return new RemoveRootNodeResult(empty(), expr, expr);
}
use of com.github.javaparser.ast.expr.ThisExpr in project drools by kiegroup.
the class PackageModel method generateRulesInUnit.
private void generateRulesInUnit(String ruleUnitName, BlockStmt rulesListInitializerBody, RuleSourceResult results, ClassOrInterfaceDeclaration rulesClass) {
results.withModel(name + "." + ruleUnitName, name + "." + rulesClass.getNameAsString());
Collection<MethodDeclaration> ruleMethodsInUnit = ofNullable(ruleMethods.get(ruleUnitName)).map(Map::values).orElse(null);
if (ruleMethodsInUnit == null || ruleMethodsInUnit.isEmpty()) {
BodyDeclaration<?> getQueriesMethod = parseBodyDeclaration(" @Override\n" + " public java.util.List<org.drools.model.Rule> getRules() {\n" + " return java.util.Collections.emptyList();\n" + " }\n");
rulesClass.addMember(getQueriesMethod);
return;
}
if (!ruleUnitName.equals(DEFAULT_RULE_UNIT)) {
BodyDeclaration<?> modelNameMethod = parseBodyDeclaration(" @Override\n" + " public String getName() {\n" + " return super.getName() + \"." + ruleUnitName + "\";\n" + " }\n");
rulesClass.addMember(modelNameMethod);
BodyDeclaration<?> modelPackageNameMethod = parseBodyDeclaration(" @Override\n" + " public String getPackageName() {\n" + " return super.getName();\n" + " }\n");
rulesClass.addMember(modelPackageNameMethod);
}
createAndAddGetRulesMethod(rulesClass);
int ruleCount = ruleMethodsInUnit.size();
boolean requiresMultipleRulesLists = ruleCount >= RULES_DECLARATION_PER_CLASS - 1;
boolean parallelRulesLoad = ruleCount >= (RULES_DECLARATION_PER_CLASS * 3 - 1);
MethodCallExpr parallelRulesGetter = null;
MethodCallExpr rules = buildRulesField(rulesClass);
if (requiresMultipleRulesLists) {
rulesClass.addImplementedType(RulesSupplier.class);
if (parallelRulesLoad) {
parallelRulesGetter = new MethodCallExpr(new NameExpr(RulesSupplier.class.getCanonicalName()), "getRules");
parallelRulesGetter.addArgument(new ThisExpr());
rulesListInitializerBody.addStatement(new AssignExpr(new NameExpr("this.rules"), parallelRulesGetter, AssignExpr.Operator.ASSIGN));
} else {
MethodCallExpr add = new MethodCallExpr(new NameExpr("rules"), "addAll");
add.addArgument("getRulesList()");
rulesListInitializerBody.addStatement(add);
}
}
ruleMethodsInUnit.parallelStream().forEach(DrlxParseUtil::transformDrlNameExprToNameExpr);
int maxLength = ruleMethodsInUnit.parallelStream().map(MethodDeclaration::toString).mapToInt(String::length).max().orElse(1);
int rulesPerClass = oneClassPerRule ? 1 : Math.max(50000 / maxLength, 1);
// each method per Drlx parser result
int count = -1;
Map<Integer, ClassOrInterfaceDeclaration> splitted = new LinkedHashMap<>();
for (MethodDeclaration ruleMethod : ruleMethodsInUnit) {
String methodName = ruleMethod.getNameAsString();
ClassOrInterfaceDeclaration rulesMethodClass = splitted.computeIfAbsent(++count / rulesPerClass, i -> {
String className = rulesClass.getNameAsString() + (oneClassPerRule ? "_" + methodName : "RuleMethods" + i);
return createClass(className, results);
});
rulesMethodClass.addMember(ruleMethod);
if (count % RULES_DECLARATION_PER_CLASS == RULES_DECLARATION_PER_CLASS - 1) {
int index = count / RULES_DECLARATION_PER_CLASS;
rules = buildRulesField(results, index);
ObjectCreationExpr newObject = new ObjectCreationExpr(null, toClassOrInterfaceType(rulesFileName + "Rules" + index), NodeList.nodeList());
if (parallelRulesLoad) {
parallelRulesGetter.addArgument(newObject);
} else {
MethodCallExpr add = new MethodCallExpr(new NameExpr("rules"), "addAll");
add.addArgument(new MethodCallExpr(newObject, "getRulesList"));
rulesListInitializerBody.addStatement(add);
}
}
// manage in main class init block:
rules.addArgument(new MethodCallExpr(new NameExpr(rulesMethodClass.getNameAsString()), methodName));
}
BodyDeclaration<?> rulesList = requiresMultipleRulesLists ? parseBodyDeclaration("java.util.List<org.drools.model.Rule> rules = new java.util.ArrayList<>(" + ruleCount + ");") : parseBodyDeclaration("java.util.List<org.drools.model.Rule> rules = getRulesList();");
rulesClass.addMember(rulesList);
}
use of com.github.javaparser.ast.expr.ThisExpr in project drools by kiegroup.
the class CommonCodegenUtils method addMapPopulation.
/**
* For every entry in the given map, add
* <pre>
* (<i>mapName</i>).put(<i>entry_key<i/>, this::<i>entry_value_ref</i>>);
* </pre>
* e.g.
* <pre>
* MAP_NAME.put("KEY_0", this::METHOD_015);
* MAP_NAME.put("KEY_3", this::METHOD_33);
* MAP_NAME.put("KEY_2", this::METHOD_219);
* MAP_NAME.put("KEY_4", this::METHOD_46);
* </pre>
* inside the given <code>BlockStmt</code>
* @param toAdd
* @param body
* @param mapName
*/
public static void addMapPopulation(final Map<String, MethodDeclaration> toAdd, final BlockStmt body, final String mapName) {
Map<String, Expression> toAddExpr = toAdd.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> {
MethodReferenceExpr methodReferenceExpr = new MethodReferenceExpr();
methodReferenceExpr.setScope(new ThisExpr());
methodReferenceExpr.setIdentifier(entry.getValue().getNameAsString());
return methodReferenceExpr;
}));
addMapPopulationExpressions(toAddExpr, body, mapName);
}
Aggregations