private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
public Parameter ensureParameterFromSingleVariableDeclaration(SingleVariableDeclaration variableDeclaration, Method method) { String name = variableDeclaration.getName().toString(); String qualifiedName = Famix.qualifiedNameOf(method) + NAME_SEPARATOR + name; if (parameters.has(qualifiedName)) return parameters.named(qualifiedName); Parameter parameter = new Parameter(); parameters.add(qualifiedName, parameter); parameter.setName(name); parameter.setParentBehaviouralEntity(method); parameter.setDeclaredType(ensureTypeFromDomType(variableDeclaration.getType())); IVariableBinding binding = variableDeclaration.resolveBinding(); if (binding != null) { createAnnotationInstancesToEntityFromAnnotationBinding(parameter, binding.getAnnotations()); //We only recover the final modifier if (Modifier.isFinal(binding.getModifiers())) parameter.addModifiers("final"); } return parameter; }
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 static String getSignatureFromMethodDeclaration(MethodDeclaration methodDeclaration) { String methodName = methodDeclaration.isConstructor() ? "" : methodDeclaration.getName().getIdentifier(); // if (methodName.equals("allObjectsSorted")) { // System.out.println(); // } StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append('('); @SuppressWarnings("unchecked") Iterator<SingleVariableDeclaration> parameters = methodDeclaration.parameters().iterator(); while (parameters.hasNext()) { SingleVariableDeclaration parameter = parameters.next(); Type parameterType = parameter.getType(); String typeName = normalizeTypeName(parameterType, parameter.getExtraDimensions(), parameter.isVarargs()); sb.append(typeName); if (parameters.hasNext()) { sb.append(", "); } } sb.append(')'); String methodSignature = sb.toString(); return methodSignature; }
private MethodDeclaration createNewWithMethod(AST ast, String fieldName, Block newBlock, SingleVariableDeclaration methodParameterDeclaration, TypeDeclaration builderType, BuilderField builderField) { MethodDeclaration builderMethod = ast.newMethodDeclaration(); builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName))); builderMethod.setReturnType2(ast.newSimpleType( ast.newName(builderType.getName().getIdentifier()))); builderMethod.setBody(newBlock); builderMethod.parameters().add(methodParameterDeclaration); javadocAdder.addJavadocForWithMethod(ast, fieldName, builderMethod); if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) { markerAnnotationAttacher.attachNonNull(ast, builderMethod); } builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); return builderMethod; }
@SuppressWarnings("unchecked") public MethodDeclaration createPrivateConstructorDefinition(AST ast, TypeDeclaration originalType, TypeDeclaration builderType, List<BuilderField> builderFields) { MethodDeclaration method = ast.newMethodDeclaration(); method.setConstructor(true); method.setName(ast.newSimpleName(originalType.getName().toString())); if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) { generatedAnnotationPopulator.addGeneratedAnnotation(ast, method); } method.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD)); SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration(); methodParameterDeclaration.setType(ast.newSimpleType(ast.newName(builderType.getName().toString()))); methodParameterDeclaration.setName(ast.newSimpleName(camelCaseConverter.toLowerCamelCase(builderType.getName().toString()))); method.parameters().add(methodParameterDeclaration); return method; }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
boolean isExceptionCaught(ITypeBinding excpetionType) { for (Iterator<List<CatchClause>> exceptions= fExceptionStack.iterator(); exceptions.hasNext(); ) { for (Iterator<CatchClause> catchClauses= exceptions.next().iterator(); catchClauses.hasNext(); ) { SingleVariableDeclaration caughtException= catchClauses.next().getException(); IVariableBinding binding= caughtException.resolveBinding(); if (binding == null) { continue; } ITypeBinding caughtype= binding.getType(); while (caughtype != null) { if (caughtype == excpetionType) { return true; } caughtype= caughtype.getSuperclass(); } } } return false; }
private void initializeParameterInfos() { IVariableBinding[] arguments = fAnalyzer.getArguments(); fParameterInfos = new ArrayList<>(arguments.length); ASTNode root = fAnalyzer.getEnclosingBodyDeclaration(); ParameterInfo vararg = null; for (int i = 0; i < arguments.length; i++) { IVariableBinding argument = arguments[i]; if (argument == null) { continue; } VariableDeclaration declaration = ASTNodes.findVariableDeclaration(argument, root); boolean isVarargs = declaration instanceof SingleVariableDeclaration ? ((SingleVariableDeclaration) declaration).isVarargs() : false; ParameterInfo info = new ParameterInfo(argument, getType(declaration, isVarargs), argument.getName(), i); if (isVarargs) { vararg = info; } else { fParameterInfos.add(info); } } if (vararg != null) { fParameterInfos.add(vararg); } }
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<CUCorrectionProposal> proposals) { if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) { ASTNode type= selectedNode.getParent(); if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) { SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent(); if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) { if (svd.getName().getLength() == 0) { SimpleName simpleName= (SimpleName) selectedNode; String name= simpleName.getIdentifier(); int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name)); proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance)); } } } } }
@Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); List<Expression> arguments= fArguments; for (int i= 0; i < arguments.size(); i++) { Expression elem= arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); } }
private void extractParametersFromSource(List<Variable> parametersVarList, IMethod javaElement) { Option<MethodDeclaration> mDecl = WorkspaceUtilities.getMethodDeclFromModel(javaElement); MethodDeclaration mmDecl = mDecl.unwrap(); List<SingleVariableDeclaration> parameters = mmDecl.parameters(); for (SingleVariableDeclaration param : parameters) { IVariableBinding paramBinding = param.resolveBinding(); if(!paramBinding.getType().isPrimitive()){ Variable paramVariable = this.tm.getVariableFromBindingKey(paramBinding.getKey()); if(paramVariable!=null){ parametersVarList.add(paramVariable); } } } }
private String getFieldName(org.eclipse.jdt.core.dom.FieldDeclaration fieldDeclaration) { String name = null; List fragments = fieldDeclaration.fragments(); Iterator iterator = fragments.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (next instanceof SingleVariableDeclaration) { SingleVariableDeclaration svdecl = (SingleVariableDeclaration) next; name = svdecl.getName().getIdentifier(); break; } else if (next instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) next; name = vdf.getName().getIdentifier(); break; } } return name; }
/** * returns the method Parameters as a list of ast.VariableDeclarataion * */ public static List<ast.VariableDeclaration> getMethodParameters(MethodDeclaration md) { List<ast.VariableDeclaration> params = new ArrayList<ast.VariableDeclaration>(); IMethodBinding methodBinding = md.resolveBinding(); if(methodBinding != null ) { ITypeBinding[] typeParameters = methodBinding.getTypeParameters(); List<SingleVariableDeclaration> svdList = md.parameters(); for (SingleVariableDeclaration svd : svdList) { ast.Type type = getType(svd.getType().resolveBinding()); ast.VariableDeclaration vd = VariableDeclaration.createFrom(svd); vd.varType = type; vd.varName = svd.getName().getFullyQualifiedName(); params.add(vd); } } return params; }
private List<IType> getParameters(List list) { List<IType> params = new ArrayList<IType>(); for (Object elem : list) { if (elem instanceof SingleVariableDeclaration) { SingleVariableDeclaration param = (SingleVariableDeclaration) elem; Type type = param.getType(); if (type != null && type.resolveBinding() != null && type.resolveBinding().getJavaElement() instanceof IType) { params.add((IType) type.resolveBinding().getJavaElement()); } else { if (type.resolveBinding() != null && type.isPrimitiveType()) { params.add(new PrimitiveTypeHack(type.resolveBinding().getName())); } } } } return params; }
private void changeTargetMethodParametersToMatchSource(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration, ASTRewrite destinationRewrite) { Assert.isLegal(sourceMethodDeclaration.parameters().size() == targetMethodDeclaration.parameters().size()); // iterate over the source method parameters. for (int i = 0; i < sourceMethodDeclaration.parameters().size(); i++) { // get the parameter for the source method. SingleVariableDeclaration sourceParameter = (SingleVariableDeclaration) sourceMethodDeclaration.parameters() .get(i); // get the corresponding target method parameter. SingleVariableDeclaration targetParameter = (SingleVariableDeclaration) targetMethodDeclaration.parameters() .get(i); // if the names don't match. if (!sourceParameter.getName().equals(targetParameter.getName())) { // change the target method parameter to match it since that is // what the body will use. ASTNode sourceParameterNameCopy = ASTNode.copySubtree(destinationRewrite.getAST(), sourceParameter.getName()); destinationRewrite.replace(targetParameter.getName(), sourceParameterNameCopy, null); } } }
@SuppressWarnings("unchecked") @Override public boolean visit(MethodDeclaration node) { IMethodBinding binding = node.resolveBinding(); Method method; if (binding != null) { method = importer.ensureMethodFromMethodBindingToCurrentContainer(binding); Arrays.stream(binding.getExceptionTypes()).forEach(e -> importer.createDeclaredExceptionFromTypeBinding(e, method)); } else { logNullBinding("method declaration", node.getName(), ((CompilationUnit) node.getRoot()).getLineNumber(node.getStartPosition())); method = importer.ensureMethodFromMethodDeclaration(node); } method.setIsStub(false); importer.pushOnContainerStack(method); node.parameters(). stream(). forEach(p -> importer.ensureParameterFromSingleVariableDeclaration((SingleVariableDeclaration) p, method)); importer.createSourceAnchor(method, node, (CompilationUnit) node.getRoot()); importer.ensureCommentFromBodyDeclaration(method, node); return true; }
/** * This is a data dependency if this is a declaration and the * variable being declared is in the right hand side of the * seed assignment expression. */ public boolean visit(SingleVariableDeclaration node){ IBinding binding = node.resolveBinding(); if(binding == null){ if(this.aliases.contains((node.getName().getFullyQualifiedName()))) this.result = true; } else if(binding instanceof IVariableBinding){ /* If this variable is in the alias list, then this statement * is a data dependency. */ if(this.aliases.contains(binding.getKey())){ this.result = true; } } return false; }
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation // ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
/** {@inheritDoc} */ @Override public boolean visit(SimpleName node) { if (node.getParent() instanceof VariableDeclarationFragment) return super.visit(node); if (node.getParent() instanceof SingleVariableDeclaration) return super.visit(node); IBinding binding = node.resolveBinding(); if (!(binding instanceof IVariableBinding)) return super.visit(node); binding = ((IVariableBinding) binding).getVariableDeclaration(); if (ASTResolving.isWriteAccess(node)) { List<SimpleName> list; if (fResult.containsKey(binding)) { list = fResult.get(binding); } else { list = new ArrayList<SimpleName>(); } list.add(node); fResult.put(binding, list); } return super.visit(node); }
ParameterAnnotationRewriteOperation( CompilationUnit unit, MethodDeclaration method, String annotationToAdd, String annotationToRemove, int paramIdx, boolean allowRemove, String message) { fUnit = unit; fKey = method.resolveBinding().getKey(); fAnnotationToAdd = annotationToAdd; fAnnotationToRemove = annotationToRemove; fAllowRemove = allowRemove; fArgument = (SingleVariableDeclaration) method.parameters().get(paramIdx); fKey += fArgument.getName().getIdentifier(); fMessage = message; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fArgument, SingleVariableDeclaration.MODIFIERS2_PROPERTY); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fArgument.modifiers(), listRewrite, group)) return; Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the type }
@Override protected void changeParamgumentType(ParameterInfo info) { VariableDeclaration oldParam = getParameter(info.getOldIndex()); if (oldParam instanceof SingleVariableDeclaration) { getASTRewrite() .set( oldParam, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.valueOf(info.isNewVarargs()), fDescription); SingleVariableDeclaration oldSVDParam = (SingleVariableDeclaration) oldParam; replaceTypeNode( oldSVDParam.getType(), ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding()); removeExtraDimensions(oldSVDParam); } }
@Override protected VariableDeclaration createNewParamgument( ParameterInfo info, List<ParameterInfo> parameterInfos, List<VariableDeclaration> nodes) { List<VariableDeclaration> parameters = fLambdaDecl.parameters(); if (!parameters.isEmpty() && parameters.get(0) instanceof SingleVariableDeclaration) { return createNewSingleVariableDeclaration(info); } VariableDeclarationFragment newP = getASTRewrite().getAST().newVariableDeclarationFragment(); newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName())); return newP; }
@Override public boolean visit(SimpleName node) { addReferencesToName(node); IBinding binding = node.resolveBinding(); if (binding instanceof ITypeBinding) { ITypeBinding type = (ITypeBinding) binding; if (type.isTypeVariable()) { addTypeVariableReference(type, node); } } else if (binding instanceof IVariableBinding) { IVariableBinding vb = (IVariableBinding) binding; if (vb.isField() && !isStaticallyImported(node)) { Name topName = ASTNodes.getTopMostName(node); if (node == topName || node == ASTNodes.getLeftMostSimpleName(topName)) { StructuralPropertyDescriptor location = node.getLocationInParent(); if (location != SingleVariableDeclaration.NAME_PROPERTY && location != VariableDeclarationFragment.NAME_PROPERTY) { fImplicitReceivers.add(node); } } } else if (!vb.isField()) { // we have a local. Check if it is a parameter. ParameterData data = fParameters.get(binding); if (data != null) { ASTNode parent = node.getParent(); if (parent instanceof Expression) { int precedence = OperatorPrecedence.getExpressionPrecedence((Expression) parent); if (precedence != Integer.MAX_VALUE) { data.setOperatorPrecedence(precedence); } } } } } return true; }
boolean isExceptionCaught(ITypeBinding excpetionType) { for (Iterator<List<CatchClause>> exceptions = fExceptionStack.iterator(); exceptions.hasNext(); ) { for (Iterator<CatchClause> catchClauses = exceptions.next().iterator(); catchClauses.hasNext(); ) { SingleVariableDeclaration caughtException = catchClauses.next().getException(); IVariableBinding binding = caughtException.resolveBinding(); if (binding == null) continue; ITypeBinding caughtype = binding.getType(); while (caughtype != null) { if (caughtype == excpetionType) return true; caughtype = caughtype.getSuperclass(); } } } return false; }
private void copyArguments(MethodDeclaration intermediary, CompilationUnitRewrite rew) throws JavaModelException { String[] names = fTargetMethod.getParameterNames(); ITypeBinding[] types = fTargetMethodBinding.getParameterTypes(); for (int i = 0; i < names.length; i++) { ITypeBinding typeBinding = types[i]; SingleVariableDeclaration newElement = rew.getAST().newSingleVariableDeclaration(); newElement.setName(rew.getAST().newSimpleName(names[i])); if (i == (names.length - 1) && fTargetMethodBinding.isVarargs()) { newElement.setVarargs(true); if (typeBinding.isArray()) typeBinding = typeBinding.getComponentType(); } newElement.setType(rew.getImportRewrite().addImport(typeBinding, rew.getAST())); intermediary.parameters().add(newElement); } }
private void initializeParameterInfos() { IVariableBinding[] arguments = fAnalyzer.getArguments(); fParameterInfos = new ArrayList<ParameterInfo>(arguments.length); ASTNode root = fAnalyzer.getEnclosingBodyDeclaration(); ParameterInfo vararg = null; for (int i = 0; i < arguments.length; i++) { IVariableBinding argument = arguments[i]; if (argument == null) continue; VariableDeclaration declaration = ASTNodes.findVariableDeclaration(argument, root); boolean isVarargs = declaration instanceof SingleVariableDeclaration ? ((SingleVariableDeclaration) declaration).isVarargs() : false; ParameterInfo info = new ParameterInfo(argument, getType(declaration, isVarargs), argument.getName(), i); if (isVarargs) { vararg = info; } else { fParameterInfos.add(info); } } if (vararg != null) { fParameterInfos.add(vararg); } }
@Override public ITypeConstraint[] create(CatchClause node) { SingleVariableDeclaration exception = node.getException(); ConstraintVariable nameVariable = fConstraintVariableFactory.makeExpressionOrTypeVariable(exception.getName(), getContext()); ITypeConstraint[] defines = fTypeConstraintFactory.createDefinesConstraint( nameVariable, fConstraintVariableFactory.makeTypeVariable(exception.getType())); ITypeBinding throwable = node.getAST().resolveWellKnownType("java.lang.Throwable"); // $NON-NLS-1$ ITypeConstraint[] catchBound = fTypeConstraintFactory.createSubtypeConstraint( nameVariable, fConstraintVariableFactory.makeRawBindingVariable(throwable)); ArrayList<ITypeConstraint> result = new ArrayList<ITypeConstraint>(); result.addAll(Arrays.asList(defines)); result.addAll(Arrays.asList(catchBound)); return result.toArray(new ITypeConstraint[result.size()]); }
@Override public ITypeConstraint[] create(SingleVariableDeclaration svd) { ITypeConstraint[] defines = fTypeConstraintFactory.createDefinesConstraint( fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()), fConstraintVariableFactory.makeTypeVariable(svd.getType())); if (svd.getInitializer() == null) return defines; ITypeConstraint[] constraints = fTypeConstraintFactory.createSubtypeConstraint( fConstraintVariableFactory.makeExpressionOrTypeVariable( svd.getInitializer(), getContext()), fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext())); if (defines.length == 0 && constraints.length == 0) { return new ITypeConstraint[0]; } else if (defines.length == 0) { return constraints; } else if (constraints.length == 0) { return defines; } else { List<ITypeConstraint> all = new ArrayList<ITypeConstraint>(); all.addAll(Arrays.asList(defines)); all.addAll(Arrays.asList(constraints)); return (ITypeConstraint[]) all.toArray(); } }
/** * Adds a "param" javadoc tag for a new last parameter if necessary. * * @param parameterName * @param methodDeclaration * @param astRewrite * @param javaProject * @param groupDescription */ public static void addParamJavadoc( String parameterName, MethodDeclaration methodDeclaration, ASTRewrite astRewrite, IJavaProject javaProject, TextEditGroup groupDescription) { if (!shouldAddParamJavadoc(methodDeclaration)) return; ListRewrite tagsRewrite = astRewrite.getListRewrite(methodDeclaration.getJavadoc(), Javadoc.TAGS_PROPERTY); HashSet<String> leadingNames = new HashSet<String>(); for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator(); iter.hasNext(); ) { SingleVariableDeclaration curr = iter.next(); leadingNames.add(curr.getName().getIdentifier()); } TagElement parameterTag = createParamTag(parameterName, astRewrite.getAST(), javaProject); JavadocTagsSubProcessor.insertTag(tagsRewrite, parameterTag, leadingNames, groupDescription); }
public AssignToVariableAssistProposal( ICompilationUnit cu, SingleVariableDeclaration parameter, VariableDeclarationFragment existingFragment, ITypeBinding typeBinding, int relevance) { super("", cu, null, relevance, null); // $NON-NLS-1$ fVariableKind = FIELD; fNodeToAssign = parameter; fTypeBinding = typeBinding; fExistingFragment = existingFragment; if (existingFragment == null) { setDisplayName( CorrectionMessages.AssignToVariableAssistProposal_assignparamtofield_description); } else { setDisplayName( Messages.format( CorrectionMessages.AssignToVariableAssistProposal_assigntoexistingfield_description, BasicElementLabels.getJavaElementName(existingFragment.getName().getIdentifier()))); } setImage(JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE)); }
@Override public boolean consumes(SemanticToken token) { SimpleName node = token.getNode(); StructuralPropertyDescriptor location = node.getLocationInParent(); if (location == VariableDeclarationFragment.NAME_PROPERTY || location == SingleVariableDeclaration.NAME_PROPERTY) { ASTNode parent = node.getParent(); if (parent instanceof VariableDeclaration) { parent = parent.getParent(); return parent == null || !(parent instanceof FieldDeclaration); } } return false; }
public static String sigFor(MethodDeclaration node) { StringBuilder builder = new StringBuilder(); // buidling the method declaration if(node.getReturnType2()!=null) { builder.append(node.getReturnType2().resolveBinding().getName() + " "); } String mname = node.getName().getIdentifier(); builder.append(mname); builder.append("("); List params = node.parameters(); int psize = params.size(); for(int i = 0; i < psize; i++){ SingleVariableDeclaration p = (SingleVariableDeclaration) params.get(i); builder.append(p.getType().resolveBinding().getName()); if(i < psize-1) builder.append(","); } builder.append(")"); return builder.toString(); }
@SuppressWarnings("unchecked") private void addAsyncParameters(AST ast, MethodDeclaration asyncMethodDecl) { List<SingleVariableDeclaration> asyncMethodParams = asyncMethodDecl.parameters(); // Clone all the existing sync method parameters asyncMethodParams.addAll(JavaASTUtils.cloneParameters(ast, getSyncMethodDeclaration().parameters(), getImportRewrite())); List<String> existingParamNames = new ArrayList<String>(); for (SingleVariableDeclaration param : asyncMethodParams) { existingParamNames.add(param.getName().getIdentifier()); } String callbackParameterName = StringUtilities.computeUniqueName( existingParamNames.toArray(new String[0]), "callback"); // Add the AsyncCallback parameter to the end asyncMethodParams.add(Util.createAsyncCallbackParameter(ast, getSyncMethodDeclaration().getReturnType2(), callbackParameterName, getImportRewrite())); }
@Override protected List<SingleVariableDeclaration> computeParams(AST ast, MethodDeclaration srcMethod, MethodDeclaration dstMethod, ImportRewrite imports) { // Clone the sync method parameters List<SingleVariableDeclaration> params = new ArrayList<SingleVariableDeclaration>(); params.addAll(JavaASTUtils.cloneParameters(ast, adjustSrcParams(srcMethod), imports)); // Append an AsyncCallback params.add(Util.createAsyncCallbackParameter(ast, srcMethod.getReturnType2(), computeCallBackName(dstMethod), imports)); return params; }
/** * Generates a sync/async method declaration based on the associated * async/sync method signature. */ private MethodDeclaration computeMethodSignature(AST ast, RpcPair rpcPair, MethodDeclaration dstMethod) { MethodDeclaration method = ast.newMethodDeclaration(); // New method has same name as original String methodName = rpcPair.srcMethod.getName().getIdentifier(); method.setName(ast.newSimpleName(methodName)); // Update the parameters @SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = method.parameters(); params.addAll(computeParams(ast, rpcPair.srcMethod, dstMethod, getImportRewrite())); // Update the return type method.setReturnType2(computeReturnType(ast, rpcPair.srcMethod, dstMethod, getImportRewrite())); return method; }
/** * Finds the best signature update candidate method in the peer type (smallest * edit distance between the argument lists). */ private MethodDeclaration findBestUpdateMatch(RpcPair rpcPair) { int minDistance = 0; String name = rpcPair.srcMethod.getName().getIdentifier(); List<SingleVariableDeclaration> params = adjustSrcParams(rpcPair.srcMethod); // Scan the target's methods and pick the smallest edit distance candidate for (MethodDeclaration dstMethod : rpcPair.dstType.getMethods()) { if (name.equals(dstMethod.getName().getIdentifier())) { List<SingleVariableDeclaration> targetParams = adjustDstParams(dstMethod); int distance = JavaASTUtils.editDistance(params, targetParams); if ((rpcPair.dstMethod == null) || (distance < minDistance)) { rpcPair.dstMethod = dstMethod; minDistance = distance; } } } return rpcPair.dstMethod; }
/** * Returns true iff 'methodDeclaration' represents a void static method named 'main' that takes a * single String[] parameter. */ private static boolean isMainMethod(MethodDeclaration methodDeclaration) { // Is it static? if ((methodDeclaration.getModifiers() & Modifier.STATIC) == 0) { return false; } // Does it return void? Type returnType = methodDeclaration.getReturnType2(); if (!returnType.isPrimitiveType()) { return false; } if (((PrimitiveType) returnType).getPrimitiveTypeCode() != PrimitiveType.VOID) { return false; } // Is it called 'main'? if (!"main".equals(methodDeclaration.getName().getIdentifier())) { return false; } // Does it have a single parameter? if (methodDeclaration.parameters().size() != 1) { return false; } // Is the parameter's type String[]? SingleVariableDeclaration pt = getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters()); IVariableBinding vb = pt.resolveBinding(); if (vb == null) { return false; } ITypeBinding tb = vb.getType(); return tb != null && "java.lang.String[]".equals(tb.getQualifiedName()); }