use of org.eclipse.jdt.core.dom.Assignment in project evosuite by EvoSuite.
the class JUnitCodeGenerator method createMethodCallStmt.
/* (non-Javadoc)
* @see org.evosuite.testcarver.codegen.ICodeGenerator#createMethodCallStmt(org.evosuite.testcarver.capture.CaptureLog, int)
*/
@SuppressWarnings("unchecked")
@Override
public void createMethodCallStmt(CaptureLog log, int logRecNo) {
PostProcessor.notifyRecentlyProcessedLogRecNo(logRecNo);
// assumption: all necessary statements are created and there is one variable for reach referenced object
final int oid = log.objectIds.get(logRecNo);
Object[] methodArgs = log.params.get(logRecNo);
final String methodName = log.methodNames.get(logRecNo);
final String methodDesc = log.descList.get(logRecNo);
org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc);
Class<?>[] methodParamTypeClasses = new Class[methodParamTypes.length];
for (int i = 0; i < methodParamTypes.length; i++) {
methodParamTypeClasses[i] = getClassForName(methodParamTypes[i].getClassName());
}
final String typeName = log.oidClassNames.get(log.oidRecMapping.get(oid));
Class<?> type = getClassForName(typeName);
// TODO might be nicer...
final boolean haveSamePackage = type.getPackage().getName().equals(packageName);
final Statement finalStmt;
@SuppressWarnings("rawtypes") final List arguments;
if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
/*
* Person var0 = null;
* {
* var0 = new Person();
* }
* catch(Throwable t)
* {
* org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>);
* }
*/
// e.g. Person var0 = null;
final String varName = this.createNewVarName(oid, typeName);
VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
vd.setName(ast.newSimpleName(varName));
VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
stmt.setType(this.createAstType(typeName, ast));
vd.setInitializer(ast.newNullLiteral());
methodBlock.statements().add(stmt);
// FIXME this does not make any sense
try {
this.getConstructorModifiers(type, methodParamTypeClasses);
} catch (Exception e) {
logger.error("" + e, e);
}
final int constructorTypeModifiers = this.getConstructorModifiers(type, methodParamTypeClasses);
final boolean isPublic = java.lang.reflect.Modifier.isPublic(constructorTypeModifiers);
final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;
if (isReflectionAccessNeeded) {
this.isNewInstanceMethodNeeded = true;
final MethodInvocation mi = this.createCallMethodOrNewInstanceCallStmt(true, ast, varName, typeName, methodName, methodArgs, methodParamTypes);
arguments = null;
final Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide(ast.newSimpleName(varName));
assignment.setOperator(Operator.ASSIGN);
final CastExpression cast = ast.newCastExpression();
cast.setType(this.createAstType(typeName, ast));
cast.setExpression(mi);
assignment.setRightHandSide(cast);
finalStmt = ast.newExpressionStatement(assignment);
} else {
// e.g. var0 = new Person();
final ClassInstanceCreation ci = ast.newClassInstanceCreation();
final int recNo = log.oidRecMapping.get(oid);
final int dependencyOID = log.dependencies.getQuick(recNo);
if (dependencyOID == CaptureLog.NO_DEPENDENCY) {
ci.setType(this.createAstType(typeName, ast));
} else {
// final String varTypeName = oidToVarMapping.get(dependencyOID) + "." + typeName.substring(typeName.indexOf('$') + 1);
// ci.setType(this.createAstType(varTypeName, ast));
/*
* e.g.
* OuterClass.InnerClass innerObject = outerObject.new InnerClass();
*/
ci.setType(this.createAstType(typeName.substring(typeName.indexOf('$') + 1), ast));
ci.setExpression(ast.newSimpleName(oidToVarMapping.get(dependencyOID)));
final int index = Arrays.binarySearch(methodArgs, dependencyOID);
if (index > -1) {
logger.debug(varName + " xxxx3 " + index);
final Object[] newArgs = new Object[methodArgs.length - 1];
System.arraycopy(methodArgs, 0, newArgs, 0, index);
System.arraycopy(methodArgs, index + 1, newArgs, index, methodArgs.length - index - 1);
methodArgs = newArgs;
final Class<?>[] newParamTypeClasses = new Class<?>[methodParamTypeClasses.length - 1];
System.arraycopy(methodParamTypeClasses, 0, newParamTypeClasses, 0, index);
System.arraycopy(methodParamTypeClasses, index + 1, newParamTypeClasses, index, methodParamTypeClasses.length - index - 1);
methodParamTypeClasses = newParamTypeClasses;
final org.objectweb.asm.Type[] newParamTypes = new org.objectweb.asm.Type[methodParamTypes.length - 1];
System.arraycopy(methodParamTypes, 0, newParamTypes, 0, index);
System.arraycopy(methodParamTypes, index + 1, newParamTypes, index, methodParamTypes.length - index - 1);
methodParamTypes = newParamTypes;
}
}
final Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide(ast.newSimpleName(varName));
assignment.setOperator(Operator.ASSIGN);
assignment.setRightHandSide(ci);
finalStmt = ast.newExpressionStatement(assignment);
arguments = ci.arguments();
}
} else // ------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
{
String returnVarName = null;
final String desc = log.descList.get(logRecNo);
final String returnType = org.objectweb.asm.Type.getReturnType(desc).getClassName();
final Object returnValue = log.returnValues.get(logRecNo);
if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
Integer returnValueOID = (Integer) returnValue;
// e.g. Person var0 = null;
returnVarName = this.createNewVarName(returnValueOID, returnType);
VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
vd.setName(ast.newSimpleName(returnVarName));
VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
stmt.setType(this.createAstType(returnType, ast));
vd.setInitializer(ast.newNullLiteral());
methodBlock.statements().add(stmt);
}
final String varName = this.oidToVarMapping.get(oid);
final int methodTypeModifiers = this.getMethodModifiers(type, methodName, methodParamTypeClasses);
final boolean isPublic = java.lang.reflect.Modifier.isPublic(methodTypeModifiers);
final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;
// e.g. Person var0 = var1.getPerson("Ben");
final MethodInvocation mi;
if (isReflectionAccessNeeded) {
this.isCallMethodMethodNeeded = true;
mi = this.createCallMethodOrNewInstanceCallStmt(false, ast, varName, typeName, methodName, methodArgs, methodParamTypes);
arguments = null;
if (returnVarName != null) {
final Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
assignment.setOperator(Operator.ASSIGN);
final CastExpression cast = ast.newCastExpression();
cast.setType(this.createAstType(returnType, ast));
cast.setExpression(mi);
assignment.setRightHandSide(cast);
finalStmt = ast.newExpressionStatement(assignment);
} else {
finalStmt = ast.newExpressionStatement(mi);
}
} else {
mi = ast.newMethodInvocation();
if (log.isStaticCallList.get(logRecNo)) {
// can only happen, if this is a static method call (because constructor statement has been reported)
final String tmpType = log.oidClassNames.get(log.oidRecMapping.get(oid));
mi.setExpression(ast.newName(tmpType.split("\\.")));
} else {
try {
mi.setExpression(ast.newSimpleName(varName));
} catch (final IllegalArgumentException ex) {
String msg = "";
msg += "--recno-- " + logRecNo + "\n";
msg += "--oid-- " + oid + "\n";
msg += "--method-- " + methodName + "\n";
msg += "--varName-- " + varName + "\n";
msg += "--oidToVarMap-- " + this.oidToVarMapping + "\n";
msg += (log) + "\n";
logger.error(msg);
throw new RuntimeException(msg);
}
}
mi.setName(ast.newSimpleName(methodName));
arguments = mi.arguments();
if (returnVarName != null) {
final Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
assignment.setOperator(Operator.ASSIGN);
assignment.setRightHandSide(mi);
finalStmt = ast.newExpressionStatement(assignment);
} else {
finalStmt = ast.newExpressionStatement(mi);
}
}
}
if (postprocessing) {
final TryStatement tryStmt = this.createTryStatementForPostProcessing(ast, finalStmt, logRecNo);
methodBlock.statements().add(tryStmt);
} else {
if (this.failedRecords.contains(logRecNo)) {
// we just need an empty catch block to preserve program flow
final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, finalStmt);
methodBlock.statements().add(tryStmt);
} else {
methodBlock.statements().add(finalStmt);
}
}
if (arguments != null) {
Class<?> methodParamType;
Class<?> argType;
// is either an oid or null
Integer arg;
for (int i = 0; i < methodArgs.length; i++) {
arg = (Integer) methodArgs[i];
if (arg == null) {
arguments.add(ast.newNullLiteral());
} else {
methodParamType = CaptureUtil.getClassFromDesc(methodParamTypes[i].getDescriptor());
argType = this.oidToTypeMapping.get(arg);
// TODO: Warten was Florian und Gordon dazu sagen. Siehe Mail 04.08.2012
if (argType == null) {
logger.error("Call within constructor needs instance of enclosing object as parameter -> ignored: " + arg);
methodBlock.statements().remove(methodBlock.statements().size() - 1);
return;
}
final CastExpression cast = ast.newCastExpression();
if (methodParamType.isPrimitive()) {
if (methodParamType.equals(boolean.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.BOOLEAN));
} else if (methodParamType.equals(byte.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.BYTE));
} else if (methodParamType.equals(char.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.CHAR));
} else if (methodParamType.equals(double.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.DOUBLE));
} else if (methodParamType.equals(float.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.FLOAT));
} else if (methodParamType.equals(int.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.INT));
} else if (methodParamType.equals(long.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.LONG));
} else if (methodParamType.equals(short.class)) {
cast.setType(ast.newPrimitiveType(PrimitiveType.SHORT));
} else {
throw new RuntimeException("unknown primitive type: " + methodParamType);
}
} else {
// we need an up-cast
if (methodParamType.getName().contains(".")) {
cast.setType(this.createAstType(methodParamType.getName(), ast));
} else {
cast.setType(createAstType(methodParamType.getName(), ast));
}
}
cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg)));
arguments.add(cast);
}
}
}
}
use of org.eclipse.jdt.core.dom.Assignment in project Main by SpartanRefactoring.
the class ConstructorRenameParameters method tip.
@Override
public Tip tip(final MethodDeclaration d) {
if (!d.isConstructor())
return null;
final List<String> parameterNames = step.parametersNames(d);
final List<Statement> statements = extract.statements(d.getBody());
for (final Statement s : statements) {
final Assignment a = az.assignment(step.expression(az.expressionStatement(s)));
if (a == null || a.getOperator() != Operator.ASSIGN)
continue;
final SimpleName parameter = az.simpleName(step.from(a));
if (parameter == null || !parameterNames.contains(parameter + ""))
continue;
final FieldAccess fieldAccess = az.fieldAccess(step.to(a));
if (fieldAccess == null)
continue;
final SimpleName field = fieldAccess.getName();
if (!parameterNames.contains(field + ""))
return new Tip(description(d), getClass(), d) {
@Override
public void go(final ASTRewrite r, final TextEditGroup g) {
final SimpleName to1 = d.getAST().newSimpleName(field + ""), $ = d.getAST().newSimpleName(parameter + "");
for (final SingleVariableDeclaration q : step.parameters(d)) misc.rename($, to1, q, r, g);
misc.rename($, to1, d.getBody(), r, g);
}
};
}
return null;
}
use of org.eclipse.jdt.core.dom.Assignment in project Main by SpartanRefactoring.
the class AssignmentTernaryBloater method replaceAssignment.
private static ASTNode replaceAssignment(final Statement ¢) {
final ExpressionStatement expressionStatement = az.expressionStatement(¢);
if (expressionStatement == null)
return null;
final Assignment $ = az.assignment(expressionStatement.getExpression());
return $ == null ? null : innerAssignReplacement(right($), left($), $.getOperator());
}
use of org.eclipse.jdt.core.dom.Assignment in project flux by eclipse.
the class QuickAssistProcessor method getConvertStringConcatenationProposals.
private static boolean getConvertStringConcatenationProposals(IInvocationContext context, Collection<ICommandAccess> resultingCollections) {
ASTNode node = context.getCoveringNode();
BodyDeclaration parentDecl = ASTResolving.findParentBodyDeclaration(node);
if (!(parentDecl instanceof MethodDeclaration || parentDecl instanceof Initializer))
return false;
AST ast = node.getAST();
// $NON-NLS-1$
ITypeBinding stringBinding = ast.resolveWellKnownType("java.lang.String");
if (node instanceof Expression && !(node instanceof InfixExpression)) {
node = node.getParent();
}
if (node instanceof VariableDeclarationFragment) {
node = ((VariableDeclarationFragment) node).getInitializer();
} else if (node instanceof Assignment) {
node = ((Assignment) node).getRightHandSide();
}
InfixExpression oldInfixExpression = null;
while (node instanceof InfixExpression) {
InfixExpression curr = (InfixExpression) node;
if (curr.resolveTypeBinding() == stringBinding && curr.getOperator() == InfixExpression.Operator.PLUS) {
// is a infix expression we can use
oldInfixExpression = curr;
} else {
break;
}
node = node.getParent();
}
if (oldInfixExpression == null)
return false;
if (resultingCollections == null) {
return true;
}
LinkedCorrectionProposal stringBufferProposal = getConvertToStringBufferProposal(context, ast, oldInfixExpression);
resultingCollections.add(stringBufferProposal);
ASTRewriteCorrectionProposal messageFormatProposal = getConvertToMessageFormatProposal(context, ast, oldInfixExpression);
if (messageFormatProposal != null)
resultingCollections.add(messageFormatProposal);
return true;
}
use of org.eclipse.jdt.core.dom.Assignment in project flux by eclipse.
the class QuickAssistProcessor method getInvertEqualsProposal.
private static boolean getInvertEqualsProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof MethodInvocation)) {
node = node.getParent();
if (!(node instanceof MethodInvocation)) {
return false;
}
}
MethodInvocation method = (MethodInvocation) node;
String identifier = method.getName().getIdentifier();
if (!"equals".equals(identifier) && !"equalsIgnoreCase".equals(identifier)) {
// $NON-NLS-1$ //$NON-NLS-2$
return false;
}
List<Expression> arguments = method.arguments();
if (arguments.size() != 1) {
// overloaded equals w/ more than 1 argument
return false;
}
Expression right = arguments.get(0);
ITypeBinding binding = right.resolveTypeBinding();
if (binding != null && !(binding.isClass() || binding.isInterface() || binding.isEnum())) {
// overloaded equals w/ non-class/interface argument or null
return false;
}
if (resultingCollections == null) {
return true;
}
Expression left = method.getExpression();
AST ast = method.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
if (left == null) {
// equals(x) -> x.equals(this)
MethodInvocation replacement = ast.newMethodInvocation();
replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName()));
replacement.arguments().add(ast.newThisExpression());
replacement.setExpression((Expression) rewrite.createCopyTarget(right));
rewrite.replace(method, replacement, null);
} else if (right instanceof ThisExpression) {
// x.equals(this) -> equals(x)
MethodInvocation replacement = ast.newMethodInvocation();
replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName()));
replacement.arguments().add(rewrite.createCopyTarget(left));
rewrite.replace(method, replacement, null);
} else {
ASTNode leftExpression = left;
while (leftExpression instanceof ParenthesizedExpression) {
leftExpression = ((ParenthesizedExpression) left).getExpression();
}
rewrite.replace(right, rewrite.createCopyTarget(leftExpression), null);
if (right instanceof CastExpression || right instanceof Assignment || right instanceof ConditionalExpression || right instanceof InfixExpression) {
ParenthesizedExpression paren = ast.newParenthesizedExpression();
paren.setExpression((Expression) rewrite.createCopyTarget(right));
rewrite.replace(left, paren, null);
} else {
rewrite.replace(left, rewrite.createCopyTarget(right), null);
}
}
String label = CorrectionMessages.QuickAssistProcessor_invertequals_description;
// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERT_EQUALS);
resultingCollections.add(proposal);
return true;
}
Aggregations