org.eclipse.jdt.core.dom.Expression Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Expression. 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 File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(FieldDeclaration fieldDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		Expression expression = fragment.getInitializer();
		if(expression != null && expression instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
			AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
			if(anonymousClassDeclaration != null) {
				List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
				for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
					if(bodyDeclaration instanceof MethodDeclaration)
						methods.add((MethodDeclaration)bodyDeclaration);
				}
			}
		}
	}
	return methods;
}
 
Example #2
Source File: AssociativeInfixExpressionFragment.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode = getGroupRoot();

	List<Expression> allOperands = findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first = allOperands.indexOf(fOperands.get(0));
	int after = first + fOperands.size();
	for (int i = first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #3
Source File: PDGNodeMapping.java    From JDeodorant with MIT License 6 votes vote down vote up
public boolean isVoidMethodCallDifferenceCoveringEntireStatement() {
	boolean expression1IsVoidMethodCallDifference = false;
	boolean expression2IsVoidMethodCallDifference = false;
	for(ASTNodeDifference difference : nodeDifferences) {
		Expression expr1 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression1().getExpression());
		Expression expr2 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression2().getExpression());
		for(PreconditionViolation violation : getPreconditionViolations()) {
			if(violation instanceof ExpressionPreconditionViolation && violation.getType().equals(PreconditionViolationType.EXPRESSION_DIFFERENCE_IS_VOID_METHOD_CALL)) {
				ExpressionPreconditionViolation expressionViolation = (ExpressionPreconditionViolation)violation;
				Expression expression = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expressionViolation.getExpression().getExpression());
				if(expression.equals(expr1)) {
					if(expr1.getParent() instanceof ExpressionStatement) {
						expression1IsVoidMethodCallDifference = true;
					}
				}
				if(expression.equals(expr2)) {
					if(expr2.getParent() instanceof ExpressionStatement) {
						expression2IsVoidMethodCallDifference = true;
					}
				}
			}
		}
	}
	return expression1IsVoidMethodCallDifference && expression2IsVoidMethodCallDifference;
}
 
Example #4
Source File: AbstractControlStructureUtilities.java    From JDeodorant with MIT License 6 votes vote down vote up
private static boolean isSameAssignee(Assignment assignment1, Assignment assignment2)
{
	Expression assignee1 = assignment1.getLeftHandSide();
	Expression assignee2 = assignment2.getLeftHandSide();
	IBinding binding1 = null;
	IBinding binding2 = null;
	if (assignee1 instanceof Name && assignee2 instanceof Name)
	{
		binding1 = ((Name)assignee1).resolveBinding();
		binding2 = ((Name)assignee2).resolveBinding();
	}
	else if (assignee1 instanceof FieldAccess && assignee2 instanceof FieldAccess)
	{
		binding1 = ((FieldAccess)assignee1).resolveFieldBinding();
		binding2 = ((FieldAccess)assignee2).resolveFieldBinding();
	}
	return (binding1 != null && binding2 != null &&
			binding1.getKind() == IBinding.VARIABLE && binding2.getKind() == IBinding.VARIABLE &&
			binding1.isEqualTo(binding2));
}
 
Example #5
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Proposes a getter for this field.
 * 
 * @param context the proposal parameter
 * @param relevance relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method= findGetter(context);
	if (method != null) {
		Expression mi= createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label= Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
		return proposal;
	} else {
		IJavaElement element= context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field= (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
					return new SelfEncapsulateFieldProposal(relevance, field);
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #6
Source File: MoveStaticMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void rewrite(MethodInvocation node, ITypeBinding type) {
	Expression exp= node.getExpression();
	if (exp == null) {
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(node, fCuRewrite.getImportRewrite());
		Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context);
		fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
		exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
		fCuRewrite.getASTRewrite().set(node, MethodInvocation.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fNeedsImport= true;
	} else if (exp instanceof Name) {
		rewriteName((Name)exp, type);
	} else {
		rewriteExpression(node, exp, type);
	}
	fProcessed.add(node.getName());
}
 
Example #7
Source File: MethodDeclarationUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static AbstractVariable processMethodInvocationExpression(Expression expression) {
	if(expression != null) {
		if(expression instanceof QualifiedName) {
			QualifiedName qualifiedName = (QualifiedName)expression;
			return createVariable(qualifiedName.getName(), null);
		}
		else if(expression instanceof FieldAccess) {
			FieldAccess fieldAccess = (FieldAccess)expression;
			return createVariable(fieldAccess.getName(), null);
		}
		else if(expression instanceof SimpleName) {
			SimpleName simpleName = (SimpleName)expression;
			return createVariable(simpleName, null);
		}
	}
	return null;
}
 
Example #8
Source File: ObjectCreation.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public ObjectCreation(CompilationUnit cu, String filePath, ClassInstanceCreation creation) {
	this.locationInfo = new LocationInfo(cu, filePath, creation, CodeElementType.CLASS_INSTANCE_CREATION);
	this.type = UMLType.extractTypeObject(cu, filePath, creation.getType(), 0);
	this.typeArguments = creation.arguments().size();
	this.arguments = new ArrayList<String>();
	List<Expression> args = creation.arguments();
	for(Expression argument : args) {
		this.arguments.add(argument.toString());
	}
	if(creation.getExpression() != null) {
		this.expression = creation.getExpression().toString();
	}
	if(creation.getAnonymousClassDeclaration() != null) {
		this.anonymousClassDeclaration = creation.getAnonymousClassDeclaration().toString();
	}
}
 
Example #9
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void validateSourceAnnotationValues(Annotation annotation) throws JavaModelException {
  Expression exp = JavaASTUtils.getAnnotationValue(annotation);
  if (exp == null) {
    return;
  }

  // There will usually just be one string value
  if (exp instanceof StringLiteral) {
    validateSourceAnnotationValue((StringLiteral) exp);
  }

  // But there could be multiple values; if so, check each one.
  if (exp instanceof ArrayInitializer) {
    ArrayInitializer array = (ArrayInitializer) exp;

    for (Expression item : (List<Expression>) array.expressions()) {
      if (item instanceof StringLiteral) {
        validateSourceAnnotationValue((StringLiteral) item);
      }
    }
  }
}
 
Example #10
Source File: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Proposes a getter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method = findGetter(context);
	if (method != null) {
		Expression mi = createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
		return proposal;
	} else {
		IJavaElement element = context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field = (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
					return new SelfEncapsulateFieldProposal(relevance, field);
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #11
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Is the specified name a target access?
 *
 * @param name
 *            the name to check
 * @return <code>true</code> if this name is a target access,
 *         <code>false</code> otherwise
 */
protected boolean isTargetAccess(final Name name) {
	Assert.isNotNull(name);
	final IBinding binding= name.resolveBinding();
	if (Bindings.equals(fTarget, binding))
		return true;
	if (name.getParent() instanceof FieldAccess) {
		final FieldAccess access= (FieldAccess) name.getParent();
		final Expression expression= access.getExpression();
		if (expression instanceof Name)
			return isTargetAccess((Name) expression);
	} else if (name instanceof QualifiedName) {
		final QualifiedName qualified= (QualifiedName) name;
		if (qualified.getQualifier() != null)
			return isTargetAccess(qualified.getQualifier());
	}
	return false;
}
 
Example #12
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IExpressionFragment getSelectedExpression() throws JavaModelException {
	if (fSelectedExpression != null) {
		return fSelectedExpression;
	}
	IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);

	if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
		fSelectedExpression = (IExpressionFragment) selectedFragment;
	} else if (selectedFragment != null) {
		if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
			ExpressionStatement exprStatement = (ExpressionStatement) selectedFragment.getAssociatedNode();
			Expression expression = exprStatement.getExpression();
			fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
		} else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
			Assignment assignment = (Assignment) selectedFragment.getAssociatedNode();
			fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
		}
	}

	if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
		fSelectedExpression = null;
	}

	return fSelectedExpression;
}
 
Example #13
Source File: MoveMethodRefactoring.java    From JDeodorant with 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 #14
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(PrefixExpression node) {
	Expression operand= node.getOperand();
	if (!considerBinding(resolveBinding(operand), operand))
		return true;

	PrefixExpression.Operator operator= node.getOperator();
	if (operator != PrefixExpression.Operator.INCREMENT && operator != PrefixExpression.Operator.DECREMENT)
		return true;

	checkParent(node);

	fRewriter.replace(node,
		createInvocation(node.getAST(), node.getOperand(), node.getOperator().toString()),
		createGroupDescription(PREFIX_ACCESS));
	return false;
}
 
Example #15
Source File: MoveMethodRefactoring.java    From JDeodorant with 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 #16
Source File: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #17
Source File: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Expression methodB(String methodName, Type castType, Object... args) {
		MethodInvocation p = ast.newMethodInvocation();
		p.setExpression(name(MEM0_B));
//		p.setName(name(Translator.StringCache.getString(
//				type,
//				t,
//				opsymbol)));
		p.setName(name(methodName));

		for(Object arg : args)
			p.arguments().add(arg);
		
		if(castType != null) {
			CastExpression cast = ast.newCastExpression();			
			cast.setType(castType);
			cast.setExpression(p);
			cast.setProperty(TYPEBIND_PROP, FieldType.OBJECT);
			return cast;
		}
		return p;
	}
 
Example #18
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getExtractMethodProposal(CodeActionParams params, IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Map formattingOptions, boolean returnAsCommand) throws CoreException {
	if (!(coveringNode instanceof Expression) && !(coveringNode instanceof Statement) && !(coveringNode instanceof Block)) {
		return null;
	}
	if (coveringNode instanceof Block) {
		List<Statement> statements = ((Block) coveringNode).statements();
		int startIndex = getIndex(context.getSelectionOffset(), statements);
		if (startIndex == -1) {
			return null;
		}
		int endIndex = getIndex(context.getSelectionOffset() + context.getSelectionLength(), statements);
		if (endIndex == -1 || endIndex <= startIndex) {
			return null;
		}
	}

	final ICompilationUnit cu = context.getCompilationUnit();
	final ExtractMethodRefactoring extractMethodRefactoring = new ExtractMethodRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength(), formattingOptions);
	String uniqueMethodName = getUniqueMethodName(coveringNode, "extracted");
	extractMethodRefactoring.setMethodName(uniqueMethodName);
	if (extractMethodRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label = CorrectionMessages.QuickAssistProcessor_extractmethod_description;
		int relevance = problemsAtLocation ? IProposalRelevance.EXTRACT_METHOD_ERROR : IProposalRelevance.EXTRACT_METHOD;
		if (returnAsCommand) {
			return new CUCorrectionCommandProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD, cu, relevance, APPLY_REFACTORING_COMMAND_ID, Arrays.asList(EXTRACT_METHOD_COMMAND, params));
		}

		LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
		extractMethodRefactoring.setLinkedProposalModel(linkedProposalModel);
		RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD, cu, extractMethodRefactoring, relevance);
		proposal.setLinkedProposalModel(linkedProposalModel);
		return proposal;
	}

	return null;
}
 
Example #19
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isForStatementInit(Statement statement, SimpleName name) {
	if (statement instanceof ForStatement) {
		ForStatement forStatement= (ForStatement) statement;
		List<Expression> list = forStatement.initializers();
		if (list.size() == 1 && list.get(0) instanceof Assignment) {
			Assignment assignment= (Assignment) list.get(0);
			return assignment.getLeftHandSide() == name;
		}
	}
	return false;
}
 
Example #20
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example #21
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkTempInitializerForLocalTypeUsage() {
  	Expression initializer= fTempDeclarationNode.getInitializer();
  	if (initializer == null)
       return;

IMethodBinding declaringMethodBinding= getMethodDeclaration().resolveBinding();
ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
   LocalTypeAndVariableUsageAnalyzer localTypeAnalyer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
   initializer.accept(localTypeAnalyer);
   fInitializerUsesLocalTypes= ! localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
  }
 
Example #22
Source File: StringFormatGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addElement(Object element) {
	if (element instanceof String) {
		buffer.append((String)element);
	}
	if (element instanceof Expression) {
		arguments.add((Expression) element);
		if (getContext().is50orHigher()) {
			buffer.append("%s"); //$NON-NLS-1$
		} else {
			buffer.append("{" + (arguments.size() - 1) + "}"); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}
}
 
Example #23
Source File: ASTFragmentFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(InfixExpression node) {
	/* Try creating an associative infix expression fragment
	/* for the full subtree.  If this is not applicable,
	 * try something more generic.
	 */
	IASTFragment fragment= AssociativeInfixExpressionFragment.createFragmentForFullSubtree(node);
	if(fragment == null)
		return visit((Expression) node);

	setFragment(fragment);
	return false;
}
 
Example #24
Source File: CodeScopeBuilder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void accept(List<Expression> list) {
	int size;
	if (list == null || (size = list.size()) == 0) {
		return;
	}
	for (int i = 0; i < size; i++) {
		list.get(i).accept(this);
	}
}
 
Example #25
Source File: ProblemMarkerBuilder.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * createMarkerVisitor Creates the Visitor that goes through the unit and sets the Marker based on a case, which is currently hard coded as cypher.getinstance('AES').
 *
 * @param unit Unit from getUnitForParser
 * @param cu same as unit but different type
 * @return visitor for the unit
 */
private ASTVisitor createMarkerVisitor(final ICompilationUnit unit, final CompilationUnit cu) {
	final ASTVisitor visitor = new ASTVisitor() {

		@Override
		public boolean visit(final MethodInvocation node) {
			final int lineNumber = cu.getLineNumber(node.getStartPosition()) - 1;
			if ("getInstance".equals(node.getName().toString()) && "Cipher".equals(node.getExpression().toString())) {
				final List<Expression> l = node.arguments();
				if (!l.isEmpty()) {
					if ("AES".equals(l.get(0).resolveConstantExpressionValue()) && l.size() == 1) {
						addMarker(unit.getResource(), "Error found", lineNumber, node.getStartPosition(), node.getStartPosition() + node.getLength());
					}
				}
			}
			return true;
		}
	};
	return visitor;
}
 
Example #26
Source File: AbstractMethodFragment.java    From JDeodorant with MIT License 5 votes vote down vote up
protected void processConstructorInvocation(ConstructorInvocation constructorInvocation) {
	IMethodBinding methodBinding = constructorInvocation.resolveConstructorBinding();
	String originClassName = methodBinding.getDeclaringClass().getQualifiedName();
	TypeObject originClassTypeObject = TypeObject.extractTypeObject(originClassName);
	String methodInvocationName = methodBinding.getName();
	String qualifiedName = methodBinding.getReturnType().getQualifiedName();
	TypeObject returnType = TypeObject.extractTypeObject(qualifiedName);
	ConstructorInvocationObject constructorInvocationObject = new ConstructorInvocationObject(originClassTypeObject, methodInvocationName, returnType);
	constructorInvocationObject.setConstructorInvocation(constructorInvocation);
	ITypeBinding[] parameterTypes = methodBinding.getParameterTypes();
	for(ITypeBinding parameterType : parameterTypes) {
		String qualifiedParameterName = parameterType.getQualifiedName();
		TypeObject typeObject = TypeObject.extractTypeObject(qualifiedParameterName);
		constructorInvocationObject.addParameter(typeObject);
	}
	ITypeBinding[] thrownExceptionTypes = methodBinding.getExceptionTypes();
	for(ITypeBinding thrownExceptionType : thrownExceptionTypes) {
		constructorInvocationObject.addThrownException(thrownExceptionType.getQualifiedName());
	}
	if((methodBinding.getModifiers() & Modifier.STATIC) != 0)
		constructorInvocationObject.setStatic(true);
	addConstructorInvocation(constructorInvocationObject);
	List<Expression> arguments = constructorInvocation.arguments();
	for(Expression argument : arguments) {
		if(argument instanceof SimpleName) {
			SimpleName argumentName = (SimpleName)argument;
			IBinding binding = argumentName.resolveBinding();
			if(binding != null && binding.getKind() == IBinding.VARIABLE) {
				IVariableBinding variableBinding = (IVariableBinding)binding;
				if(variableBinding.isParameter()) {
					PlainVariable variable = new PlainVariable(variableBinding);
					addParameterPassedAsArgumentInConstructorInvocation(variable, constructorInvocationObject);
				}
			}
		}
	}
}
 
Example #27
Source File: PreconditionExaminer.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean isMethodCallDifferenceCoveringEntireStatement(ASTNodeDifference difference) {
	boolean expression1IsMethodCallDifference = false;
	boolean expression2IsMethodCallDifference = false;
	Expression expr1 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression1().getExpression());
	Expression expr2 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression2().getExpression());
	if(expr1.getParent() instanceof ExpressionStatement) {
		expression1IsMethodCallDifference = true;
	}
	if(expr2.getParent() instanceof ExpressionStatement) {
		expression2IsMethodCallDifference = true;
	}
	return expression1IsMethodCallDifference && expression2IsMethodCallDifference;
}
 
Example #28
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkMatchingFragments() throws JavaModelException {
	RefactoringStatus result = new RefactoringStatus();
	IASTFragment[] matchingFragments = getMatchingFragments();
	for (int i = 0; i < matchingFragments.length; i++) {
		ASTNode node = matchingFragments[i].getAssociatedNode();
		if (isLeftValue(node) && !isReferringToLocalVariableFromFor((Expression) node)) {
			String msg = RefactoringCoreMessages.ExtractTempRefactoring_assigned_to;
			result.addWarning(msg, JavaStatusContext.create(fCu, node));
		}
	}
	return result;
}
 
Example #29
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void collectInfixPlusOperands(Expression expression, List<Expression> collector) {
	if (expression instanceof InfixExpression && ((InfixExpression)expression).getOperator() == InfixExpression.Operator.PLUS) {
		InfixExpression infixExpression= (InfixExpression)expression;
		
		collectInfixPlusOperands(infixExpression.getLeftOperand(), collector);
		collectInfixPlusOperands(infixExpression.getRightOperand(), collector);
		List<Expression> extendedOperands= infixExpression.extendedOperands();
		for (Iterator<Expression> iter= extendedOperands.iterator(); iter.hasNext();) {
			collectInfixPlusOperands(iter.next(), collector);
		}
		
	} else {
		collector.add(expression);
	}
}
 
Example #30
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Expression newInfixExpression(AST ast, Operator operator, ArrayList<Expression> operands) {
	if (operands.size() == 1)
		return operands.get(0);

	InfixExpression result= ast.newInfixExpression();
	result.setOperator(operator);
	result.setLeftOperand(operands.get(0));
	result.setRightOperand(operands.get(1));
	result.extendedOperands().addAll(operands.subList(2, operands.size()));
	return result;
}