public static ChildListPropertyDescriptor getArgumentsProperty(ASTNode invocation) { switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: return MethodInvocation.ARGUMENTS_PROPERTY; case ASTNode.SUPER_METHOD_INVOCATION: return SuperMethodInvocation.ARGUMENTS_PROPERTY; case ASTNode.CONSTRUCTOR_INVOCATION: return ConstructorInvocation.ARGUMENTS_PROPERTY; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: return SuperConstructorInvocation.ARGUMENTS_PROPERTY; case ASTNode.CLASS_INSTANCE_CREATION: return ClassInstanceCreation.ARGUMENTS_PROPERTY; case ASTNode.ENUM_CONSTANT_DECLARATION: return EnumConstantDeclaration.ARGUMENTS_PROPERTY; default: throw new IllegalArgumentException(invocation.toString()); } }
@SuppressWarnings("unchecked") @Override public void createCollectionInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); String collTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> collType = getClassForName(collTypeName); final String varName; // -- determine if an alternative collection must be used for code generation final boolean isPrivate = java.lang.reflect.Modifier.isPrivate(collType.getModifiers()); if(isPrivate || ! hasDefaultConstructor(collType)) { if(Set.class.isAssignableFrom(collType)) { collTypeName = HashSet.class.getName(); } else if (List.class.isAssignableFrom(collType)) { collTypeName = ArrayList.class.getName(); } else if(Queue.class.isAssignableFrom(collType)) { collTypeName = ArrayDeque.class.getName(); } else { throw new RuntimeException("Collection " + collType + " is not supported"); } } // -- create code for instantiating collection varName = this.createNewVarName(oid, collTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName varNameExpr = ast.newSimpleName(varName); vd.setName(varNameExpr); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(collTypeName, ast)); vd.setInitializer(ci); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(collTypeName, ast)); methodBlock.statements().add(stmt); // --- create code for filling the collection Integer paramOID; MethodInvocation mi; for(int i = 0; i < params.length; i++) { mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("add")); paramOID = (Integer) params[i]; if(paramOID == null) { mi.arguments().add(ast.newNullLiteral()); } else { mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(paramOID))); } methodBlock.statements().add(mi); } }
@Override public void createMapInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); String collTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> collType = getClassForName(collTypeName); final String varName; // -- determine if an alternative collection must be used for code generation final boolean isPrivate = java.lang.reflect.Modifier.isPrivate(collType.getModifiers()); if(isPrivate || ! hasDefaultConstructor(collType)) { collTypeName = HashMap.class.getName(); } // -- create code for instantiating collection varName = this.createNewVarName(oid, collTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName varNameExpr = ast.newSimpleName(varName); vd.setName(varNameExpr); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(collTypeName, ast)); vd.setInitializer(ci); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(collTypeName, ast)); methodBlock.statements().add(stmt); // --- create code for filling the collection Integer valueOID; Integer keyOID; MethodInvocation mi; for(int i = 0; i + 1< params.length; i+=2) { mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("put")); keyOID = (Integer) params[i]; mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(keyOID))); valueOID = (Integer) params[i + 1]; if(valueOID == null) { mi.arguments().add(ast.newNullLiteral()); } else { mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(valueOID))); } methodBlock.statements().add(mi); } }
public static Optional<GroovyClosure> asClosure(ASTNodeFactory nodeFactory, GroovyClosureBuilder groovyClosureBuilder, Expression expression, String methodName) { if (expression instanceof ClassInstanceCreation) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression; if (classInstanceCreation.getAnonymousClassDeclaration() != null) { AnonymousClassDeclaration classDeclaration = classInstanceCreation.getAnonymousClassDeclaration(); if (classDeclaration.bodyDeclarations().size() == 1 && classDeclaration.bodyDeclarations().get(0) instanceof MethodDeclaration && ((MethodDeclaration) classDeclaration.bodyDeclarations().get(0)) .getName().getIdentifier().equals(methodName)) { MethodDeclaration methodDeclaration = (MethodDeclaration) classDeclaration.bodyDeclarations().get(0); List<Statement> statements = nodeFactory.clone(methodDeclaration.getBody()).statements(); GroovyClosure closure = groovyClosureBuilder.aClosure() .withBodyStatements(statements) .withTypeLiteral(nodeFactory.typeLiteral(type(nodeFactory, classInstanceCreation))) .withArgument(nodeFactory.clone((SingleVariableDeclaration) methodDeclaration.parameters().get(0))) .build(); return Optional.of(closure); } } } return empty(); }
public boolean visit(ClassInstanceCreation node) { IMethodBinding mmtb = node.resolveConstructorBinding(); if (mtbStack.isEmpty()) // not part of a method return true; // make field access fact try { facts.add(Fact.makeCallsFact(getQualifiedName(mtbStack.peek()), getQualifiedName(mmtb))); } catch (Exception e) { System.err.println("Cannot resolve class instance creation \"" + node.getType().toString() + "\""); } return true; }
public Block createReturnBlock(AST ast, TypeDeclaration builderType, String withName, String parameterName) { Block builderMethodBlock = ast.newBlock(); ReturnStatement returnStatement = ast.newReturnStatement(); ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation(); newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString()))); MethodInvocation withMethodInvocation = ast.newMethodInvocation(); withMethodInvocation.setExpression(newClassInstanceCreation); withMethodInvocation.setName(ast.newSimpleName(withName)); withMethodInvocation.arguments().add(ast.newSimpleName(parameterName)); returnStatement.setExpression(withMethodInvocation); builderMethodBlock.statements().add(returnStatement); return builderMethodBlock; }
/** * Returns whether an expression at the given location needs explicit boxing. * * @param expression the expression * @return <code>true</code> iff an expression at the given location needs explicit boxing * @since 3.6 */ private static boolean needsExplicitBoxing(Expression expression) { StructuralPropertyDescriptor locationInParent= expression.getLocationInParent(); if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return needsExplicitBoxing((ParenthesizedExpression) expression.getParent()); } if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY || locationInParent == FieldAccess.EXPRESSION_PROPERTY || locationInParent == MethodInvocation.EXPRESSION_PROPERTY) { return true; } return false; }
/** * Returns the declaration node for the originally selected node. * * @param name * the name of the node * * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) { parent = parent.getParent(); } if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
@Override public OOGContext transfer(SourceVariableDeclaration instr, OOGContext value) { // Get the source variable that is being declared SourceVariable declaredVariable = instr.getDeclaredVariable(); // Get the set of qualifiers of the variable that is being declared Set<OType> declVarSet = this.tm.getAnalysisResult(declaredVariable); // Check if the declared variable is the left-hand side of a new expression, call T-New for its ser // And remove the qualfiers that contain 'n.PD' VariableDeclaration node = instr.getNode(); ASTNode parent = node.getParent(); if(parent instanceof VariableDeclarationStatement){ if(node.getInitializer()!=null && node.getInitializer() instanceof ClassInstanceCreation){ TypeConstraints.tNewNoOthersPublicDomain(declVarSet); } } return value; }
public ExpressionVisitor(ASTNode enclosingDeclartion, BaseTraceability trace) { AstNode expression = trace.getExpression(); if(expression instanceof ast.ClassInstanceCreation){ expressionType = ExpressionType.CLASS_INSTANCE_CREATION; expressionToFind =((ast.ClassInstanceCreation) expression).complexExpression; }else if(expression instanceof ast.FieldWrite){ expressionType = ExpressionType.FIELD_WRITE; expressionToFind = ((ast.FieldWrite) expression).complexExpression; }else if(expression instanceof ast.FieldAccess){ expressionType = ExpressionType.FIELD_ACCESS; expressionToFind = ((ast.FieldAccess) expression).complexExpression; }else if(expression instanceof ast.MethodInvocation){ expressionToFind =((ast.MethodInvocation) expression).complexExpression; expressionType = ExpressionType.METHOD_INVOCATION; } enclosingDeclaration = enclosingDeclartion; enclosingDeclaration.accept(this); }
public static IJavaElement getIJavaElement(ASTNode node){ IJavaElement javaElement = null; // Find IJavaElement corresponding to the ASTNode if (node instanceof MethodDeclaration) { javaElement = ((MethodDeclaration) node).resolveBinding() .getJavaElement(); } else if (node instanceof VariableDeclaration) { javaElement = ((VariableDeclaration) node).resolveBinding() .getJavaElement(); }else if(node instanceof TypeDeclaration){ javaElement = ((TypeDeclaration)node).resolveBinding() .getJavaElement(); }else if(node instanceof ClassInstanceCreation){ javaElement = ((ClassInstanceCreation)node).resolveConstructorBinding().getJavaElement(); } return javaElement; }
public boolean visit(ClassInstanceCreation node) { IMethodBinding mmtb = node.resolveConstructorBinding(); if (this.mtbStack.isEmpty()) { return true; } try { this.facts.add(Fact.makeCallsFact(getQualifiedName((IMethodBinding)this.mtbStack.peek()), getQualifiedName(mmtb))); } catch (Exception e) { System.err.println("Cannot resolve class instance creation \"" + node.getType().toString() + "\""); } return true; }
public boolean visit(ClassInstanceCreation node) { IMethodBinding mmtb = node.resolveConstructorBinding(); if (this.mtbStack.isEmpty()) { return true; } try { this.facts.add(Fact.makeCallsFact(getQualifiedName((IMethodBinding)this.mtbStack.peek()), getQualifiedName(mmtb))); } catch (Exception localException) { System.err.println("Cannot resolve class instance creation \"" + node.getType().toString() + "\""); } return true; }
/** * Returns the declaration node for the originally selected node. * * @param name the name of the node * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) parent = parent.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group = createTextEditGroup( FixMessages.CodeStyleFix_ChangeAccessUsingDeclaring_description, cuRewrite); if (fQualifier instanceof MethodInvocation || fQualifier instanceof ClassInstanceCreation) extractQualifier(fQualifier, cuRewrite, group); Type type = importType( fDeclaringTypeBinding, fQualifier, cuRewrite.getImportRewrite(), cuRewrite.getRoot()); cuRewrite.getASTRewrite().replace(fQualifier, type, group); }
public static ASTNode getSelectedTypeNode(CompilationUnit root, IProblemLocation problem) { ASTNode selectedNode = problem.getCoveringNode(root); if (selectedNode == null) return null; if (selectedNode.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION) { // bug 200016 selectedNode = selectedNode.getParent(); } if (selectedNode.getLocationInParent() == EnumConstantDeclaration.NAME_PROPERTY) { selectedNode = selectedNode.getParent(); } if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent() instanceof AbstractTypeDeclaration) { return selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { return ((ClassInstanceCreation) selectedNode).getAnonymousClassDeclaration(); } else if (selectedNode.getNodeType() == ASTNode.ENUM_CONSTANT_DECLARATION) { EnumConstantDeclaration enumConst = (EnumConstantDeclaration) selectedNode; if (enumConst.getAnonymousClassDeclaration() != null) return enumConst.getAnonymousClassDeclaration(); return enumConst; } else { return null; } }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration .modifiers() .addAll( ASTNodeFactory.newModifiers( ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) continue; if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) rewrite .getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()) .insertAt(declaration, 0, editGroup); else if (node instanceof AnonymousClassDeclaration) rewrite .getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) rewrite .getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); } } else Assert.isTrue(false); addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment( fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit)); if (comment != null && comment.length() > 0) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) return; positionGroups.setEndPosition(rewrite.track(fragment)); }
protected String getFullTypeName() { ASTNode node = getNode(); while (true) { node = node.getParent(); if (node instanceof AbstractTypeDeclaration) { String typeName = ((AbstractTypeDeclaration) node).getName().getIdentifier(); if (getNode() instanceof LambdaExpression) { return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_lambda_expression, typeName); } return typeName; } else if (node instanceof ClassInstanceCreation) { ClassInstanceCreation cic = (ClassInstanceCreation) node; return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(cic.getType()))); } else if (node instanceof EnumConstantDeclaration) { EnumDeclaration ed = (EnumDeclaration) node.getParent(); return Messages.format( RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(ed.getName()))); } } }
@Override public void endVisit(ClassInstanceCreation node) { Expression receiver = node.getExpression(); Type createdType = node.getType(); ConstraintVariable2 typeCv; if (node.getAnonymousClassDeclaration() == null) { typeCv = getConstraintVariable(createdType); } else { typeCv = fTCModel.makeImmutableTypeVariable(createdType.resolveBinding(), null); setConstraintVariable(createdType, typeCv); } setConstraintVariable(node, typeCv); IMethodBinding methodBinding = node.resolveConstructorBinding(); Map<String, IndependentTypeVariable2> methodTypeVariables = createMethodTypeArguments(methodBinding); List<Expression> arguments = node.arguments(); doVisitMethodInvocationArguments( methodBinding, arguments, receiver, methodTypeVariables, createdType); }
public static boolean isIntroduceFactoryAvailable(final JavaTextSelection selection) throws JavaModelException { final IJavaElement[] elements = selection.resolveElementAtOffset(); if (elements.length == 1 && elements[0] instanceof IMethod) return isIntroduceFactoryAvailable((IMethod) elements[0]); // there's no IMethod for the default constructor if (!Checks.isAvailable(selection.resolveEnclosingElement())) return false; ASTNode node = selection.resolveCoveringNode(); if (node == null) { ASTNode[] selectedNodes = selection.resolveSelectedNodes(); if (selectedNodes != null && selectedNodes.length == 1) { node = selectedNodes[0]; if (node == null) return false; } else { return false; } } if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) return true; node = ASTNodes.getNormalizedNode(node); if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) return true; return false; }
private ASTNode createNewClassInstanceCreation( CompilationUnitRewrite rewrite, ITypeBinding[] parameters) { AST ast = fAnonymousInnerClassNode.getAST(); ClassInstanceCreation newClassCreation = ast.newClassInstanceCreation(); newClassCreation.setAnonymousClassDeclaration(null); Type type = null; SimpleName newNameNode = ast.newSimpleName(fClassName); if (parameters.length > 0) { final ParameterizedType parameterized = ast.newParameterizedType(ast.newSimpleType(newNameNode)); for (int index = 0; index < parameters.length; index++) parameterized .typeArguments() .add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName()))); type = parameterized; } else type = ast.newSimpleType(newNameNode); newClassCreation.setType(type); copyArguments(rewrite, newClassCreation); addArgumentsForLocalsUsedInInnerClass(newClassCreation); addLinkedPosition(KEY_TYPE_NAME, newNameNode, rewrite.getASTRewrite(), true); return newClassCreation; }
private IMethodBinding getSuperConstructorBinding() { // workaround for missing java core functionality - finding a // super constructor for an anonymous class creation IMethodBinding anonConstr = ((ClassInstanceCreation) fAnonymousInnerClassNode.getParent()).resolveConstructorBinding(); if (anonConstr == null) return null; ITypeBinding superClass = anonConstr.getDeclaringClass().getSuperclass(); IMethodBinding[] superMethods = superClass.getDeclaredMethods(); for (int i = 0; i < superMethods.length; i++) { IMethodBinding superMethod = superMethods[i]; if (superMethod.isConstructor() && parameterTypesMatch(superMethod, anonConstr)) return superMethod; } Assert.isTrue(false); // there's no way - it must be there return null; }
private void setSuperType(TypeDeclaration declaration) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) fAnonymousInnerClassNode.getParent(); ITypeBinding binding = classInstanceCreation.resolveTypeBinding(); if (binding == null) return; Type newType = (Type) ASTNode.copySubtree(fAnonymousInnerClassNode.getAST(), classInstanceCreation.getType()); if (binding.getSuperclass().getQualifiedName().equals("java.lang.Object")) { // $NON-NLS-1$ Assert.isTrue(binding.getInterfaces().length <= 1); if (binding.getInterfaces().length == 0) return; declaration.superInterfaceTypes().add(0, newType); } else { declaration.setSuperclassType(newType); } }
public static List<Expression> getArguments(ASTNode invocation) { switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: return ((MethodInvocation) invocation).arguments(); case ASTNode.SUPER_METHOD_INVOCATION: return ((SuperMethodInvocation) invocation).arguments(); case ASTNode.CONSTRUCTOR_INVOCATION: return ((ConstructorInvocation) invocation).arguments(); case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: return ((SuperConstructorInvocation) invocation).arguments(); case ASTNode.CLASS_INSTANCE_CREATION: return ((ClassInstanceCreation) invocation).arguments(); case ASTNode.ENUM_CONSTANT_DECLARATION: return ((EnumConstantDeclaration) invocation).arguments(); default: throw new IllegalArgumentException(invocation.toString()); } }
public static Expression getExpression(ASTNode invocation) { switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: return ((MethodInvocation) invocation).getExpression(); case ASTNode.SUPER_METHOD_INVOCATION: return null; case ASTNode.CONSTRUCTOR_INVOCATION: return null; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: return ((SuperConstructorInvocation) invocation).getExpression(); case ASTNode.CLASS_INSTANCE_CREATION: return ((ClassInstanceCreation) invocation).getExpression(); case ASTNode.ENUM_CONSTANT_DECLARATION: return null; default: throw new IllegalArgumentException(invocation.toString()); } }
public static IMethodBinding resolveBinding(ASTNode invocation) { switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: return ((MethodInvocation) invocation).resolveMethodBinding(); case ASTNode.SUPER_METHOD_INVOCATION: return ((SuperMethodInvocation) invocation).resolveMethodBinding(); case ASTNode.CONSTRUCTOR_INVOCATION: return ((ConstructorInvocation) invocation).resolveConstructorBinding(); case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: return ((SuperConstructorInvocation) invocation).resolveConstructorBinding(); case ASTNode.CLASS_INSTANCE_CREATION: return ((ClassInstanceCreation) invocation).resolveConstructorBinding(); case ASTNode.ENUM_CONSTANT_DECLARATION: return ((EnumConstantDeclaration) invocation).resolveConstructorBinding(); default: throw new IllegalArgumentException(invocation.toString()); } }
public static ITypeBinding[] getInferredTypeArguments(Expression invocation) { IMethodBinding methodBinding; switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: methodBinding = ((MethodInvocation) invocation).resolveMethodBinding(); return methodBinding == null ? null : methodBinding.getTypeArguments(); case ASTNode.SUPER_METHOD_INVOCATION: methodBinding = ((SuperMethodInvocation) invocation).resolveMethodBinding(); return methodBinding == null ? null : methodBinding.getTypeArguments(); case ASTNode.CLASS_INSTANCE_CREATION: Type type = ((ClassInstanceCreation) invocation).getType(); ITypeBinding typeBinding = type.resolveBinding(); return typeBinding == null ? null : typeBinding.getTypeArguments(); default: throw new IllegalArgumentException(invocation.toString()); } }
/** * Finds and returns the <code>ASTNode</code> for the given source text selection, if it is an * entire constructor call or the class name portion of a constructor call or constructor * declaration, or null otherwise. * * @param unit The compilation unit in which the selection was made * @param offset The textual offset of the start of the selection * @param length The length of the selection in characters * @return ClassInstanceCreation or MethodDeclaration */ private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) { ASTNode node = ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length)); if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) return node; if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration) node).isConstructor()) return node; // we have some sub node. Make sure its the right child of the parent StructuralPropertyDescriptor location = node.getLocationInParent(); ASTNode parent = node.getParent(); if (location == ClassInstanceCreation.TYPE_PROPERTY) { return parent; } else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration) parent).isConstructor()) { return parent; } return null; }
/** * Sets the type being instantiated in the given constructor call, including specifying any * necessary type arguments. * * @param newCtorCall the constructor call to modify * @param ctorTypeName the simple name of the type being instantiated * @param ctorOwnerTypeParameters the formal type parameters of the type being instantiated * @param ast utility object used to create AST nodes */ private void setCtorTypeArguments( ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName)); else { Type baseType = ast.newSimpleType(ast.newSimpleName(ctorTypeName)); ParameterizedType newInstantiatedType = ast.newParameterizedType(baseType); List<Type> newInstTypeArgs = newInstantiatedType.typeArguments(); for (int i = 0; i < ctorOwnerTypeParameters.length; i++) { Type typeArg = ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newInstTypeArgs.add(typeArg); } newCtorCall.setType(newInstantiatedType); } }
@Override public ITypeConstraint[] create(ClassInstanceCreation instanceCreation) { List<Expression> arguments = instanceCreation.arguments(); List<ITypeConstraint> result = new ArrayList<ITypeConstraint>(arguments.size()); IMethodBinding methodBinding = instanceCreation.resolveConstructorBinding(); result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding))); if (instanceCreation.getAnonymousClassDeclaration() == null) { ConstraintVariable constructorVar = fConstraintVariableFactory.makeExpressionOrTypeVariable(instanceCreation, getContext()); ConstraintVariable typeVar = fConstraintVariableFactory.makeRawBindingVariable(instanceCreation.resolveTypeBinding()); result.addAll( Arrays.asList(fTypeConstraintFactory.createDefinesConstraint(constructorVar, typeVar))); } return result.toArray(new ITypeConstraint[result.size()]); }
private static IBinding resolveBinding(ASTNode node) { if (node instanceof SimpleName) { SimpleName simpleName = (SimpleName) node; // workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not // method) ASTNode normalized = ASTNodes.getNormalizedNode(simpleName); if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { ClassInstanceCreation cic = (ClassInstanceCreation) normalized.getParent(); IMethodBinding constructorBinding = cic.resolveConstructorBinding(); if (constructorBinding == null) return null; ITypeBinding declaringClass = constructorBinding.getDeclaringClass(); if (!declaringClass.isAnonymous()) return constructorBinding; ITypeBinding superTypeDeclaration = declaringClass.getSuperclass().getTypeDeclaration(); return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding); } return simpleName.resolveBinding(); } else if (node instanceof SuperConstructorInvocation) { return ((SuperConstructorInvocation) node).resolveConstructorBinding(); } else if (node instanceof ConstructorInvocation) { return ((ConstructorInvocation) node).resolveConstructorBinding(); } else { return null; } }
public boolean visit(ClassInstanceCreation cic) { int lineNum = cu.getLineNumber(cic.getStartPosition()); AnonymousClassDeclaration anonymDecl = cic.getAnonymousClassDeclaration(); if(anonymDecl != null){ assert topLevelClassSig != null : cic.toString(); ITypeBinding anonymType = anonymDecl.resolveBinding(); String name = topLevelClassSig+"#"+chordClassName(anonymType.getSuperclass())+"#"+lineNum; ITypeBinding anonymTypeBinding = anonymType.getErasure(); PetabloxSigFactory.newAnonymousClass(anonymTypeBinding, name); } IMethodBinding callee = cic.resolveConstructorBinding().getMethodDeclaration(); List args = cic.arguments(); args = new ArrayList(args); args.add(0, cic); processInvkExpr(lineNum, cic.getType(), cic.toString(), callee, args, "newexpr", null); //System.out.println("** " + cic + " ##"); return true; }
/** {@inheritDoc} */ @Override public void endVisit(Assignment assignment) { if ((assignment.getRightHandSide() instanceof MethodInvocation) || (assignment.getRightHandSide() instanceof ClassInstanceCreation)) { // treated in respective endVisit methods return; } VariableReference varRef = retrieveVariableReference(assignment.getLeftHandSide(), null); varRef.setOriginalCode(assignment.getLeftHandSide().toString()); VariableReference newAssignment = retrieveVariableReference(assignment.getRightHandSide(), null); newAssignment.setOriginalCode(assignment.getRightHandSide().toString()); if (varRef instanceof ArrayIndex) { AssignmentStatement assignmentStatement = new AssignmentStatement( testCase.getReference(), varRef, newAssignment); testCase.addStatement(assignmentStatement); return; } testCase.variableAssignment(varRef, newAssignment); }
/** {@inheritDoc} */ @Override public void endVisit(ClassInstanceCreation instanceCreation) { if (instanceCreation.getParent() instanceof ThrowStatement) { logger.warn("Ignoring throw statements!"); return; } List<?> paramTypes = Arrays.asList(instanceCreation.resolveConstructorBinding().getParameterTypes()); List<?> paramValues = instanceCreation.arguments(); Constructor<?> constructor = retrieveConstructor(instanceCreation.getType(), paramTypes, paramValues); List<VariableReference> params = convertParams(instanceCreation.arguments(), paramTypes); VariableReference retVal = retrieveVariableReference(instanceCreation, null); retVal.setOriginalCode(instanceCreation.toString()); ConstructorStatement statement = new ValidConstructorStatement( testCase.getReference(), constructor, retVal, params); testCase.addStatement(statement); }
private VariableReference retrieveVariableReference( ClassInstanceCreation instanceCreation, Class<?> varType) { if ((instanceCreation.getParent() instanceof MethodInvocation) || (instanceCreation.getParent() instanceof ClassInstanceCreation)) { VariableReference result = new ValidVariableReference( testCase.getReference(), retrieveTypeClass(instanceCreation.getType())); nestedCallResults.push(result); return result; } if ((instanceCreation.getParent() instanceof ExpressionStatement) && (instanceCreation.getParent().getParent() instanceof Block)) { if (varType == null) { varType = retrieveTypeClass(instanceCreation); } VariableReference varRef = new ValidVariableReference( testCase.getReference(), varType); return varRef; } return retrieveVariableReference(instanceCreation.getParent(), varType); }
/** * handles * new Class() */ @SuppressWarnings("unchecked") @Override public boolean visit(ClassInstanceCreation node) { IMethodBinding binding = node.resolveConstructorBinding(); if (binding != null) importer.createInvocationFromMethodBinding(binding, node.toString().trim()); else { String name = node.getType().toString(); importer.ensureBasicMethod( name, name, importer.ensureTypeNamedInUnknownNamespace(name), m -> importer.createInvocationToMethod(m, node.toString().trim())); } node.arguments().stream().forEach(arg -> importer.createAccessFromExpression((Expression) arg)); return true; }
public static IMethodBinding resolveBinding(ASTNode invocation) { switch (invocation.getNodeType()) { case ASTNode.METHOD_INVOCATION: return ((MethodInvocation)invocation).resolveMethodBinding(); case ASTNode.SUPER_METHOD_INVOCATION: return ((SuperMethodInvocation)invocation).resolveMethodBinding(); case ASTNode.CONSTRUCTOR_INVOCATION: return ((ConstructorInvocation)invocation).resolveConstructorBinding(); case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: return ((SuperConstructorInvocation)invocation).resolveConstructorBinding(); case ASTNode.CLASS_INSTANCE_CREATION: return ((ClassInstanceCreation)invocation).resolveConstructorBinding(); case ASTNode.ENUM_CONSTANT_DECLARATION: return ((EnumConstantDeclaration)invocation).resolveConstructorBinding(); default: throw new IllegalArgumentException(invocation.toString()); } }
/** * Sets the type being instantiated in the given constructor call, including * specifying any necessary type arguments. * @param newCtorCall the constructor call to modify * @param ctorTypeName the simple name of the type being instantiated * @param ctorOwnerTypeParameters the formal type parameters of the type being * instantiated * @param ast utility object used to create AST nodes */ private void setCtorTypeArguments(ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName)); else { Type baseType= ast.newSimpleType(ast.newSimpleName(ctorTypeName)); ParameterizedType newInstantiatedType= ast.newParameterizedType(baseType); List<Type> newInstTypeArgs= newInstantiatedType.typeArguments(); for(int i= 0; i < ctorOwnerTypeParameters.length; i++) { Type typeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newInstTypeArgs.add(typeArg); } newCtorCall.setType(newInstantiatedType); } }