Java Code Examples for org.eclipse.jdt.core.dom.MethodDeclaration

The following examples show how to use org.eclipse.jdt.core.dom.MethodDeclaration. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: lapse-plus   Author: OWASP   File: DeclarationInfoManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public VariableDeclaration getVariableDeclaration(SimpleName name) {
	ASTNode node = name;
	do {
		node = node.getParent();
	} while ( node != null && !(node instanceof MethodDeclaration) );
	
	String key = null;
	
	if(node != null) {
		key = node.toString() + "/" + name.getFullyQualifiedName();
	}else {
		key = "GLOBAL" + name.getFullyQualifiedName();	
	}
	
	logError("Trying " + key);
	VariableDeclaration var = getVariableDeclaration(key);
	if(var == null && node != null) {
		key = "GLOBAL" + name.getFullyQualifiedName();
		log("Trying " + key);
		var = getVariableDeclaration(key);
	}
	
	return var;
}
 
Example #2
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void removeAdditionalMethodsFromSourceClass() {
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
		ListRewrite sourceClassBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		sourceClassBodyRewrite.remove(methodDeclaration, null);
		try {
			TextEdit sourceEdit = sourceRewriter.rewriteAST();
			sourceMultiTextEdit.addChild(sourceEdit);
			sourceCompilationUnitChange.addTextEditGroup(new TextEditGroup("Remove additional moved method", new TextEdit[] {sourceEdit}));
		}
		catch(JavaModelException javaModelException) {
			javaModelException.printStackTrace();
		}
	}
}
 
Example #3
Source Project: JDeodorant   Author: tsantalis   File: TypeCheckingEvolution.java    License: MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinTypeDeclaration(TypeDeclaration typeDeclaration, TypeCheckElimination originalTypeCheckElimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	for(MethodDeclaration method : typeDeclaration.getMethods()) {
		Block methodBody = method.getBody();
		if(methodBody != null) {
			List<TypeCheckElimination> list = generateTypeCheckEliminationsWithinMethodBody(methodBody);
			for(TypeCheckElimination typeCheckElimination : list) {
				if(!typeCheckElimination.allTypeCheckBranchesAreEmpty()) {
					TypeCheckCodeFragmentAnalyzer analyzer = new TypeCheckCodeFragmentAnalyzer(typeCheckElimination, typeDeclaration, method, null);
					if((typeCheckElimination.getTypeField() != null || typeCheckElimination.getTypeLocalVariable() != null || typeCheckElimination.getTypeMethodInvocation() != null) &&
							typeCheckElimination.allTypeCheckingsContainStaticFieldOrSubclassType() && typeCheckElimination.isApplicable()) {
						if(originalTypeCheckElimination.matchingStatesOrSubTypes(typeCheckElimination))
							typeCheckEliminations.add(typeCheckElimination);
					}
				}
			}
		}
	}
	return typeCheckEliminations;
}
 
Example #4
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: UpdateAsyncSignatureProposal.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #5
Source Project: apidiff   Author: aserg-ufmg   File: MethodDiff.java    License: MIT License 6 votes vote down vote up
/**
 * Finding deprecated methods
 * 
 * @param version1
 * @param version2
 */
private void findAddedDeprecatedMethods(APIVersion version1, APIVersion version2) {
	
	for(TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()){
		for(MethodDeclaration methodVersion2 : typeVersion2.getMethods()){
			
			if(this.isMethodAcessible(methodVersion2) && this.isDeprecated(methodVersion2, typeVersion2)){
				MethodDeclaration methodInVersion1 = version1.findMethodByNameAndParametersAndReturn(methodVersion2, typeVersion2);
				if(methodInVersion1 == null || !this.isDeprecated(methodInVersion1, version1.getVersionAccessibleType(typeVersion2))){
					String description = this.description.deprecate(this.getSimpleNameMethod(methodVersion2), UtilTools.getPath(typeVersion2));
					this.addChange(typeVersion2, methodVersion2, Category.METHOD_DEPRECATED, false, description);
				}
			}
		}
	}
}
 
Example #6
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: InlineMethodRefactoring.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new inline method refactoring
 * @param unit the compilation unit or class file
 * @param node the compilation unit node
 * @param selectionStart start
 * @param selectionLength length
 * @return returns the refactoring
 */
public static InlineMethodRefactoring create(ITypeRoot unit, CompilationUnit node, int selectionStart, int selectionLength) {
	ASTNode target= RefactoringAvailabilityTester.getInlineableMethodNode(unit, node, selectionStart, selectionLength);
	if (target == null)
		return null;
	if (target.getNodeType() == ASTNode.METHOD_DECLARATION) {

		return new InlineMethodRefactoring(unit, (MethodDeclaration)target, selectionStart, selectionLength);
	} else {
		ICompilationUnit cu= (ICompilationUnit) unit;
		if (target.getNodeType() == ASTNode.METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (MethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (SuperMethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
			return new InlineMethodRefactoring(cu, (ConstructorInvocation)target, selectionStart, selectionLength);
		}
	}
	return null;
}
 
Example #7
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void addParamTagElementToJavadoc(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter, String parameterToBeAdded) {
	if(newMethodDeclaration.getJavadoc() != null) {
		AST ast = newMethodDeclaration.getAST();
		Javadoc javadoc = newMethodDeclaration.getJavadoc();
		List<TagElement> tags = javadoc.tags();
		TagElement returnTagElement = null;
		for(TagElement tag : tags) {
			if(tag.getTagName() != null && tag.getTagName().equals(TagElement.TAG_RETURN)) {
				returnTagElement = tag;
				break;
			}
		}
		
		TagElement tagElement = ast.newTagElement();
		targetRewriter.set(tagElement, TagElement.TAG_NAME_PROPERTY, TagElement.TAG_PARAM, null);
		ListRewrite fragmentsRewrite = targetRewriter.getListRewrite(tagElement, TagElement.FRAGMENTS_PROPERTY);
		SimpleName paramName = ast.newSimpleName(parameterToBeAdded);
		fragmentsRewrite.insertLast(paramName, null);
		
		ListRewrite tagsRewrite = targetRewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
		if(returnTagElement != null)
			tagsRewrite.insertBefore(tagElement, returnTagElement, null);
		else
			tagsRewrite.insertLast(tagElement, null);
	}
}
 
Example #8
/**
 * Returns the reserved identifiers in the method to move.
 *
 * @return the reserved identifiers
 * @throws JavaModelException
 *             if the method declaration could not be found
 */
protected String[] computeReservedIdentifiers() throws JavaModelException {
	final List<String> names= new ArrayList<String>();
	final MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
	if (declaration != null) {
		final List<SingleVariableDeclaration> parameters= declaration.parameters();
		VariableDeclaration variable= null;
		for (int index= 0; index < parameters.size(); index++) {
			variable= parameters.get(index);
			names.add(variable.getName().getIdentifier());
		}
		final Block body= declaration.getBody();
		if (body != null) {
			final IBinding[] bindings= new ScopeAnalyzer(fSourceRewrite.getRoot()).getDeclarationsAfter(body.getStartPosition(), ScopeAnalyzer.VARIABLES);
			for (int index= 0; index < bindings.length; index++)
				names.add(bindings[index].getName());
		}
	}
	final String[] result= new String[names.size()];
	names.toArray(result);
	return result;
}
 
Example #9
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void removeParamTagElementFromJavadoc(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter, String parameterToBeRemoved) {
	if(newMethodDeclaration.getJavadoc() != null) {
		Javadoc javadoc = newMethodDeclaration.getJavadoc();
		List<TagElement> tags = javadoc.tags();
		for(TagElement tag : tags) {
			if(tag.getTagName() != null && tag.getTagName().equals(TagElement.TAG_PARAM)) {
				List<ASTNode> tagFragments = tag.fragments();
				boolean paramFound = false;
				for(ASTNode node : tagFragments) {
					if(node instanceof SimpleName) {
						SimpleName simpleName = (SimpleName)node;
						if(simpleName.getIdentifier().equals(parameterToBeRemoved)) {
							paramFound = true;
							break;
						}
					}
				}
				if(paramFound) {
					ListRewrite tagsRewrite = targetRewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
					tagsRewrite.remove(tag, null);
					break;
				}
			}
		}
	}
}
 
Example #10
/**
 * 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;
}
 
Example #11
Source Project: JDeodorant   Author: tsantalis   File: ExpressionExtractor.java    License: MIT License 6 votes vote down vote up
private List<Expression> getExpressions(AnonymousClassDeclaration anonymousClassDeclaration) {
	List<Expression> expressionList = new ArrayList<Expression>();
	List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
	for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
		if(bodyDeclaration instanceof MethodDeclaration) {
			MethodDeclaration methodDeclaration = (MethodDeclaration)bodyDeclaration;
			Block body = methodDeclaration.getBody();
			if(body != null) {
				List<Statement> statements = body.statements();
				for(Statement statement : statements) {
					expressionList.addAll(getExpressions(statement));
				}
			}
		}
	}
	return expressionList;
}
 
Example #12
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void modifySourceStaticMethodInvocationsInTargetClass(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();	
	List<Expression> sourceMethodInvocations = extractor.getMethodInvocations(sourceMethod.getBody());
	List<Expression> newMethodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	int i = 0;
	for(Expression expression : sourceMethodInvocations) {
		if(expression instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
			if((methodBinding.getModifiers() & Modifier.STATIC) != 0 &&
					methodBinding.getDeclaringClass().isEqualTo(sourceTypeDeclaration.resolveBinding()) &&
					!additionalMethodsToBeMoved.containsKey(methodInvocation)) {
				AST ast = newMethodDeclaration.getAST();
				SimpleName qualifier = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
				targetRewriter.set(newMethodInvocations.get(i), MethodInvocation.EXPRESSION_PROPERTY, qualifier, null);
				this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
			}
		}
		i++;
	}
}
 
Example #13
/**
 * Returns the bindings of the method argument types of the specified
 * declaration.
 *
 * @param declaration
 *            the method declaration
 * @return the array of method argument variable bindings
 */
protected static ITypeBinding[] getArgumentTypes(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	final IVariableBinding[] parameters= getArgumentBindings(declaration);
	final List<ITypeBinding> types= new ArrayList<ITypeBinding>(parameters.length);
	IVariableBinding binding= null;
	ITypeBinding type= null;
	for (int index= 0; index < parameters.length; index++) {
		binding= parameters[index];
		type= binding.getType();
		if (type != null)
			types.add(type);
	}
	final ITypeBinding[] result= new ITypeBinding[types.size()];
	types.toArray(result);
	return result;
}
 
Example #14
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: MIT License 6 votes vote down vote up
private void replaceThisExpressionWithSourceClassParameterInMethodInvocationArguments(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	ExpressionExtractor extractor = new ExpressionExtractor();
	List<Expression> methodInvocations = extractor.getMethodInvocations(newMethodDeclaration.getBody());
	for(Expression invocation : methodInvocations) {
		if(invocation instanceof MethodInvocation) {
			MethodInvocation methodInvocation = (MethodInvocation)invocation;
			List<Expression> arguments = methodInvocation.arguments();
			for(Expression argument : arguments) {
				if(argument instanceof ThisExpression) {
					SimpleName parameterName = null;
					if(!additionalArgumentsAddedToMovedMethod.contains("this")) {
						parameterName = addSourceClassParameterToMovedMethod(newMethodDeclaration, targetRewriter);
					}
					else {
						AST ast = newMethodDeclaration.getAST();
						String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
						parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
					}
					ListRewrite argumentRewrite = targetRewriter.getListRewrite(methodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
					argumentRewrite.replace(argument, parameterName, null);
				}
			}
		}
	}
}
 
Example #15
Source Project: api-mining   Author: mast-group   File: JavaMethodDeclarationBindingExtractor.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add argument-related features.
 *
 * @param md
 * @param features
 */
private void addArgumentFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.ARGUMENTS));
	features.add("nParams:" + md.parameters().size());
	for (int i = 0; i < md.parameters().size(); i++) {
		final SingleVariableDeclaration varDecl = (SingleVariableDeclaration) md
				.parameters().get(i);
		features.add("param" + i + "Type:" + varDecl.getType().toString());
		for (final String namepart : JavaFeatureExtractor
				.getNameParts(varDecl.getName().toString())) {
			features.add("paramName:" + namepart);
		}
	}

	if (md.isVarargs()) {
		features.add("isVarArg");
	}
}
 
Example #16
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
	if (node == null)
		return null;
	switch (node.getNodeType()) {
		case ASTNode.SIMPLE_NAME:
			StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
			if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
				return node.getParent();
			} else if (locationInParent == MethodInvocation.NAME_PROPERTY
					|| locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
				return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
			}
			return null;
		case ASTNode.EXPRESSION_STATEMENT:
			node= ((ExpressionStatement)node).getExpression();
	}
	switch (node.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			return node;
		case ASTNode.METHOD_INVOCATION:
		case ASTNode.SUPER_METHOD_INVOCATION:
		case ASTNode.CONSTRUCTOR_INVOCATION:
			return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
	}
	return null;
}
 
Example #17
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: CreateAsyncMethodProposal.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static List<IJavaCompletionProposal> createProposalsForProblemOnAsyncType(
    ICompilationUnit asyncCompilationUnit, ASTNode problemNode,
    String syncMethodBindingKey) {
  TypeDeclaration asyncTypeDecl = (TypeDeclaration) ASTResolving.findAncestor(
      problemNode, ASTNode.TYPE_DECLARATION);
  assert (asyncTypeDecl != null);
  String asyncQualifiedTypeName = asyncTypeDecl.resolveBinding().getQualifiedName();

  // Lookup the sync version of the interface
  IType syncType = RemoteServiceUtilities.findSyncType(asyncTypeDecl);
  if (syncType == null) {
    return Collections.emptyList();
  }

  MethodDeclaration syncMethodDecl = JavaASTUtils.findMethodDeclaration(
      syncType.getCompilationUnit(), syncMethodBindingKey);
  if (syncMethodDecl == null) {
    return Collections.emptyList();
  }

  return Collections.<IJavaCompletionProposal> singletonList(new CreateAsyncMethodProposal(
      asyncCompilationUnit, asyncQualifiedTypeName, syncMethodDecl));
}
 
Example #18
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: VariableDeclarationFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private boolean isWrittenInTypeConstructors(List<SimpleName> writes, ITypeBinding declaringClass) {

			for (int i= 0; i < writes.size(); i++) {
	            SimpleName name= writes.get(i);

	            MethodDeclaration methodDeclaration= getWritingConstructor(name);
	            if (methodDeclaration == null)
	            	return false;

	            if (!methodDeclaration.isConstructor())
	            	return false;

	            IMethodBinding constructor= methodDeclaration.resolveBinding();
	            if (constructor == null)
	            	return false;

	            ITypeBinding declaringClass2= constructor.getDeclaringClass();
	            if (!declaringClass.equals(declaringClass2))
	            	return false;
            }

	        return true;
        }
 
Example #19
Source Project: api-mining   Author: mast-group   File: JavaMethodDeclarationBindingExtractor.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param node
 * @return
 */
public boolean methodOverrides(final MethodDeclaration node) {
	final boolean hasAnnotation = MethodUtils
			.hasOverrideAnnotation(node);
	final boolean isOverride = pti.isMethodOverride(className.peek(),
			node);
	return hasAnnotation || isOverride;
}
 
Example #20
Source Project: api-mining   Author: mast-group   File: MethodRetriever.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Map<String, MethodDeclaration> getMethodNodes(final File file)
		throws IOException {
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);
	final MethodRetriever m = new MethodRetriever();
	final CompilationUnit cu = astExtractor.getAST(file);
	cu.accept(m);
	return m.methods;
}
 
Example #21
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: UpdateAsyncSignatureProposal.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected List<SingleVariableDeclaration> adjustSrcParams(
    MethodDeclaration method) {

  // The source method is in the sync interface
  return method.parameters();
}
 
Example #22
/**
 * Add exception related features.
 *
 * @param md
 * @param features
 */
private void addExceptionFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.EXCEPTIONS));
	for (final Object exception : md.thrownExceptionTypes()) {
		final SimpleType ex = (SimpleType) exception;
		features.add("thrownException:" + ex.toString());
	}
}
 
Example #23
Source Project: spotbugs   Author: spotbugs   File: CreateDoPrivilegedBlockResolution.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void updateVariableReferences(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(classLoaderCreation);

    MethodDeclaration method = findMethodDeclaration(classLoaderCreation);
    if (method != null) {
        final Set<String> variableReferences = findVariableReferences(classLoaderCreation.arguments());
        if (!variableReferences.isEmpty()) {
            updateMethodParams(rewrite, variableReferences, method.parameters());
            updateLocalVariableDeclarations(rewrite, variableReferences, method.getBody());
        }
    }
}
 
Example #24
Source Project: codemining-core   Author: mast-group   File: MethodExtractor.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<MethodDeclaration> getMethods(final File file, final ProjectTypeInformation pti)
		throws IOException {
	try {
		final JavaASTExtractor ex = new JavaASTExtractor(false);
		final MethodVisitor mv = new MethodVisitor(pti);
		final CompilationUnit cu = ex.getAST(file);
		cu.accept(mv);
		return mv.allMethods;
	} catch (Exception e) {
		System.err.println(ExceptionUtils.getFullStackTrace(e));
	}
	return new ArrayList<>();
}
 
Example #25
Source Project: eclipse.jdt.ls   Author: eclipse   File: ChangeMethodSignatureProposal.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= (CompilationUnit) fInvocationNode.getRoot();
	ASTNode methodDecl= astRoot.findDeclaringNode(fSenderBinding);
	ASTNode newMethodDecl= null;
	if (methodDecl != null) {
		newMethodDecl= methodDecl;
	} else {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newMethodDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}
	createImportRewrite(astRoot);

	if (newMethodDecl instanceof MethodDeclaration) {
		MethodDeclaration decl= (MethodDeclaration) newMethodDecl;

		ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
		if (fParameterChanges != null) {
			modifyParameters(rewrite, decl);
		}
		if (fExceptionChanges != null) {
			modifyExceptions(rewrite, decl);
		}
		return rewrite;
	}
	return null;
}
 
Example #26
Source Project: compiler   Author: boalang   File: TestQ21.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(AnonymousClassDeclaration node) {
//	classes++;
	for (Object d : node.bodyDeclarations()) {
		if (d instanceof FieldDeclaration)
			((FieldDeclaration)d).accept(this);
		if (d instanceof MethodDeclaration)
			((MethodDeclaration)d).accept(this);
	}
	return false;
}
 
Example #27
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: HierarchyProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void copyParameters(final ASTRewrite rewrite, final ICompilationUnit unit, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaModelException {
	SingleVariableDeclaration newDeclaration= null;
	for (int index= 0, size= oldMethod.parameters().size(); index < size; index++) {
		final SingleVariableDeclaration oldDeclaration= (SingleVariableDeclaration) oldMethod.parameters().get(index);
		if (mapping.length > 0)
			newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, mapping, rewrite);
		else
			newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, rewrite);
		newMethod.parameters().add(newDeclaration);
	}
}
 
Example #28
Source Project: naturalize   Author: mast-group   File: DynamicRangeEval.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void pushStatsFor(final BaseIdentifierRenamings renamer,
		final MethodDeclaration method, final AbstractNGramLM lm,
		final List<String> allToks) throws IOException {
	final JavaASTExtractor ex = new JavaASTExtractor(false);
	final Multimap<Scope, String> scopes = scopeExtractor
			.getFromNode(method);
	final ScopedIdentifierRenaming identifierRenamer = new ScopedIdentifierRenaming(
			scopeExtractor, ParseType.METHOD);
	final List<String> renamedVars = Lists.newArrayList(scopes.values());
	Collections.shuffle(renamedVars);

	checkArgument(!renamedVars.isEmpty());

	final SnippetSuggestions ssBefore = SnippetScorer.scoreSnippet(method,
			renamer, scopeExtractor, false, false);

	final Map<String, String> renamingPlan = Maps.newTreeMap();
	final String targetName = getRandomName(allToks, renamer.getLM()
			.getTokenizer());
	renamingPlan.put(renamedVars.get(0), targetName);

	final String renamedMethod = identifierRenamer.getRenamedCode(
			method.toString(), method.toString(), renamingPlan);
	final ASTNode renamedMethodNode = ex.getASTNode(renamedMethod,
			ParseType.METHOD);

	final SnippetSuggestions ssAfter = SnippetScorer.scoreSnippet(
			renamedMethodNode, renamer, scopeExtractor, false, false);

	scoreBest.add(new BeforeAfterScore<Double>(-ssBefore.suggestions
			.first().getConfidence(), -ssAfter.suggestions.first()
			.getConfidence()));

	if (DEBUG_OUTPUT) {
		printDebugOutput(method, lm, renamedVars, ssBefore, targetName,
				renamedMethodNode, ssAfter);
	}
}
 
Example #29
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: HierarchyProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void copyReturnType(final ASTRewrite rewrite, final ICompilationUnit unit, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaModelException {
	Type newReturnType= null;
	if (mapping.length > 0)
		newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, mapping, rewrite);
	else
		newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, rewrite);
	newMethod.setReturnType2(newReturnType);
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: SelfEncapsulateFieldRefactoring.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block = ast.newBlock();
	result.setBody(block);

	String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(getterNode);
	} else {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}