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

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationFragment. 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: StyledStringVisitor.java    From JDeodorant with MIT License 6 votes vote down vote up
public boolean visit(VariableDeclarationFragment expr) {
	/*
	 * Identifier { [] } [ = Expression ]
	 */
	activateDiffStyle(expr);
	handleExpression(expr.getName());
	for (int i = 0; i < expr.getExtraDimensions(); i++) {
		appendOpenBracket();
		appendClosedBracket();
	}
	if (expr.getInitializer() != null) {
		appendEquals();
		handleExpression(expr.getInitializer());
	}
	deactivateDiffStyle(expr);
	return false;
}
 
Example #2
Source File: InOutFlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void clearAccessMode(FlowInfo info, List<? extends ASTNode> nodes) {
	if (nodes== null || nodes.isEmpty() || info == null)
		return;
	for (Iterator<? extends ASTNode> iter= nodes.iterator(); iter.hasNext(); ) {
		Object node= iter.next();
		Iterator<VariableDeclarationFragment> fragments= null;
		if (node instanceof VariableDeclarationStatement) {
			fragments= ((VariableDeclarationStatement)node).fragments().iterator();
		} else if (node instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression)node).fragments().iterator();
		}
		if (fragments != null) {
			while (fragments.hasNext()) {
				clearAccessMode(info, fragments.next());
			}
		}
	}
}
 
Example #3
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean canReplace(IASTFragment fragment) {
	ASTNode node = fragment.getAssociatedNode();
	ASTNode parent = node.getParent();
	if (parent instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
		if (node.equals(vdf.getName())) {
			return false;
		}
	}
	if (parent instanceof ExpressionStatement) {
		return false;
	}
	if (parent instanceof SwitchCase) {
		if (node instanceof Name) {
			Name name = (Name) node;
			ITypeBinding typeBinding = name.resolveTypeBinding();
			if (typeBinding != null) {
				return !typeBinding.isEnum();
			}
		}
	}
	return true;
}
 
Example #4
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static RefactorWorkspaceEdit moveStaticMember(CodeActionParams params, String destinationTypeName, IProgressMonitor monitor) {
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
	if (unit == null) {
		return new RefactorWorkspaceEdit("Failed to move static member because cannot find the compilation unit associated with " + params.getTextDocument().getUri());
	}

	BodyDeclaration bodyDeclaration = getSelectedMemberDeclaration(unit, params);
	List<IJavaElement> elements = new ArrayList<>();
	if (bodyDeclaration instanceof MethodDeclaration) {
		elements.add(((MethodDeclaration) bodyDeclaration).resolveBinding().getJavaElement());
	} else if (bodyDeclaration instanceof FieldDeclaration) {
		for (Object fragment : ((FieldDeclaration) bodyDeclaration).fragments()) {
			elements.add(((VariableDeclarationFragment) fragment).resolveBinding().getJavaElement());
		}
	} else if (bodyDeclaration instanceof AbstractTypeDeclaration) {
		elements.add(((AbstractTypeDeclaration) bodyDeclaration).resolveBinding().getJavaElement());
	}

	IMember[] members = elements.stream().filter(element -> element instanceof IMember).map(element -> (IMember) element).toArray(IMember[]::new);
	return moveStaticMember(members, destinationTypeName, monitor);
}
 
Example #5
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the fields which reference the specified ast node.
 *
 * @param node
 *            the ast node
 * @param project
 *            the java project
 * @return the referencing fields
 * @throws JavaModelException
 *             if an error occurs
 */
protected final List<IField> getReferencingFields(final ASTNode node, final IJavaProject project) throws JavaModelException {
	List<IField> result= Collections.emptyList();
	if (node instanceof Type) {
		final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
		if (parent instanceof FieldDeclaration) {
			final List<VariableDeclarationFragment> fragments= ((FieldDeclaration) parent).fragments();
			result= new ArrayList<IField>(fragments.size());
			VariableDeclarationFragment fragment= null;
			for (final Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) {
				fragment= iterator.next();
				final IField field= getCorrespondingField(fragment);
				if (field != null)
					result.add(field);
			}
		}
	}
	return result;
}
 
Example #6
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private FieldDeclaration createField(ParameterInfo pi, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit unit= cuRewrite.getCu();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	String lineDelim= StubUtility.getLineDelimiterUsed(unit);
	SimpleName fieldName= ast.newSimpleName(pi.getNewName());
	fragment.setName(fieldName);
	FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
	if (createComments(unit.getJavaProject())) {
		String comment= StubUtility.getFieldComment(unit, pi.getNewTypeName(), pi.getNewName(), lineDelim);
		if (comment != null) {
			Javadoc doc= (Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	List<Modifier> modifiers= new ArrayList<Modifier>();
	if (fCreateGetter) {
		modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
	} else {
		modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	}
	declaration.modifiers().addAll(modifiers);
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	return declaration;
}
 
Example #8
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean visit(VariableDeclarationExpression node) {
	if (fAddFinalLocals && node.fragments().size() == 1) {
		SimpleName name= ((VariableDeclarationFragment)node.fragments().get(0)).getName();

		IBinding binding= name.resolveBinding();
		if (binding == null)
			return false;

		if (fWrittenVariables.containsKey(binding))
			return false;

		ModifierChangeOperation op= createAddFinalOperation(name, node);
		if (op == null)
			return false;

		fResult.add(op);
		return false;
	}
	return false;
}
 
Example #9
Source File: RefactoringUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static VariableDeclaration findFieldDeclaration(AbstractVariable variable, TypeDeclaration typeDeclaration) {
	for(FieldDeclaration fieldDeclaration : typeDeclaration.getFields()) {
		List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(variable.getVariableBindingKey().equals(fragment.resolveBinding().getKey())) {
				return fragment;
			}
		}
	}
	//fragment was not found in typeDeclaration
	Type superclassType = typeDeclaration.getSuperclassType();
	if(superclassType != null) {
		String superclassQualifiedName = superclassType.resolveBinding().getQualifiedName();
		SystemObject system = ASTReader.getSystemObject();
		ClassObject superclassObject = system.getClassObject(superclassQualifiedName);
		if(superclassObject != null) {
			AbstractTypeDeclaration superclassTypeDeclaration = superclassObject.getAbstractTypeDeclaration();
			if(superclassTypeDeclaration instanceof TypeDeclaration) {
				return findFieldDeclaration(variable, (TypeDeclaration)superclassTypeDeclaration);
			}
		}
	}
	return null;
}
 
Example #10
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) {
	IMethodBinding method= lambdaExpression.resolveMethodBinding();
	if (method != null) {
		ITypeBinding[] parameterTypes= method.getParameterTypes();
		int index= lambdaExpression.parameters().indexOf(declaration);
		ITypeBinding typeBinding= parameterTypes[index];
		if (importRewrite != null) {
			return importRewrite.addImport(typeBinding, ast, context);
		} else {
			String qualifiedName= typeBinding.getQualifiedName();
			if (qualifiedName.length() > 0) {
				return newType(ast, qualifiedName);
			}
		}
	}
	// fall-back
	return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
 
Example #11
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
Example #12
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkClashesWithExistingFields(){
     FieldDeclaration[] existingFields= getFieldDeclarations();
     for (int i= 0; i < existingFields.length; i++) {
         FieldDeclaration declaration= existingFields[i];
VariableDeclarationFragment[] fragments= (VariableDeclarationFragment[]) declaration.fragments().toArray(new VariableDeclarationFragment[declaration.fragments().size()]);
for (int j= 0; j < fragments.length; j++) {
             VariableDeclarationFragment fragment= fragments[j];
             if (fFieldName.equals(fragment.getName().getIdentifier())){
             	//cannot conflict with more than 1 name
             	RefactoringStatusContext context= JavaStatusContext.create(fCu, fragment);
             	return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict_with_field, context);
             }
         }
     }
     return null;
 }
 
Example #13
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private String[] getExcludedFieldNames() {
	if (fExcludedFieldNames == null) {
		List<String> result = new ArrayList<>();
		try {
			final ASTNode type = getEnclosingTypeDeclaration();
			if (type instanceof TypeDeclaration) {
				FieldDeclaration[] fields = ((TypeDeclaration) type).getFields();
				for (int i = 0; i < fields.length; i++) {
					for (Iterator<VariableDeclarationFragment> iter = fields[i].fragments().iterator(); iter.hasNext();) {
						VariableDeclarationFragment field = iter.next();
						result.add(field.getName().getIdentifier());
					}
				}
			}
		} catch (JavaModelException e) {
			// do nothing.
		}

		fExcludedFieldNames = result.toArray(new String[result.size()]);
	}

	return fExcludedFieldNames;
}
 
Example #14
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	Type fieldType = null;
	FieldDeclaration[] fields = sourceTypeDeclaration.getFields();
	for(FieldDeclaration field : fields) {
		List<VariableDeclarationFragment> fragments = field.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) {
				fieldType = field.getType();
				break;
			}
		}
	}
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier());
	this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier());
}
 
Example #15
Source File: AnonymousTypeCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IBinding getEnclosingDeclaration(ASTNode node) {
	while (node != null) {
		if (node instanceof AbstractTypeDeclaration) {
			return ((AbstractTypeDeclaration) node).resolveBinding();
		} else if (node instanceof AnonymousClassDeclaration) {
			return ((AnonymousClassDeclaration) node).resolveBinding();
		} else if (node instanceof MethodDeclaration) {
			return ((MethodDeclaration) node).resolveBinding();
		} else if (node instanceof FieldDeclaration) {
			List<?> fragments = ((FieldDeclaration) node).fragments();
			if (fragments.size() > 0) {
				return ((VariableDeclarationFragment) fragments.get(0)).resolveBinding();
			}
		} else if (node instanceof VariableDeclarationFragment) {
			IVariableBinding variableBinding = ((VariableDeclarationFragment) node).resolveBinding();
			if (variableBinding.getDeclaringMethod() != null || variableBinding.getDeclaringClass() != null) {
				return variableBinding;
				// workaround for incomplete wiring of DOM bindings: keep searching when variableBinding is unparented
			}
		}
		node = node.getParent();
	}
	return null;
}
 
Example #16
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 6 votes vote down vote up
public boolean visit(VariableDeclarationExpression expr) {
	/*
	  VariableDeclarationExpression:
   		{ ExtendedModifier } Type VariableDeclarationFragment
        	{ , VariableDeclarationFragment }
	 */
	activateDiffStyle(expr);
	// Append modifiers
	for (int i = 0; i < expr.modifiers().size(); i++) {
		handleModifier((IExtendedModifier) expr.modifiers().get(i));
		appendSpace();
	}
	// Append Type
	handleType(expr.getType());
	appendSpace();
	// Visit Fragments
	for (int i = 0; i < expr.fragments().size(); i++) {
		visit((VariableDeclarationFragment) expr.fragments().get(i));
		if(i < expr.fragments().size() - 1) {
			appendComma();
		}
	}
	// No semicolon needed as this is an expression
	deactivateDiffStyle(expr);
	return false;
}
 
Example #17
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@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);
}
 
Example #18
Source File: VariableDeclaration.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private static CodeElementType extractVariableDeclarationType(org.eclipse.jdt.core.dom.VariableDeclaration variableDeclaration) {
	if(variableDeclaration instanceof SingleVariableDeclaration) {
		return CodeElementType.SINGLE_VARIABLE_DECLARATION;
	}
	else if(variableDeclaration instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)variableDeclaration;
		if(fragment.getParent() instanceof VariableDeclarationStatement) {
			return CodeElementType.VARIABLE_DECLARATION_STATEMENT;
		}
		else if(fragment.getParent() instanceof VariableDeclarationExpression) {
			return CodeElementType.VARIABLE_DECLARATION_EXPRESSION;
		}
		else if(fragment.getParent() instanceof FieldDeclaration) {
			return CodeElementType.FIELD_DECLARATION;
		}
	}
	return null;
}
 
Example #19
Source File: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * @param fieldInVersion1
 * @param fieldInVersion2
 * @return True, if there is a difference between the fields.
 */
private Boolean thereAreDifferentDefaultValueField(FieldDeclaration fieldInVersion1, FieldDeclaration fieldInVersion2){
	
	List<VariableDeclarationFragment> variable1Fragments = fieldInVersion1.fragments();
	List<VariableDeclarationFragment> variable2Fragments = fieldInVersion2.fragments();
	
	Expression valueVersion1 = variable1Fragments.get(0).getInitializer();
	Expression valueVersion2 = variable2Fragments.get(0).getInitializer();
	
	//If default value was removed/changed
	if((valueVersion1 == null && valueVersion2 != null) || (valueVersion1 != null && valueVersion2 == null)){
		return true;
	}
	
	//If fields have default value and they are different
	if((valueVersion1 != null && valueVersion2 != null) && (!valueVersion1.toString().equals(valueVersion2.toString()))){
		return true;
	}
	
	return false;
}
 
Example #20
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void endVisitFieldVariableDeclaration(Type type, List<VariableDeclarationFragment> list) {
	ConstraintVariable2 typeCv= getConstraintVariable(type);
	if (typeCv == null)
		return;

	for (Iterator<VariableDeclarationFragment> iter= list.iterator(); iter.hasNext();) {
		VariableDeclarationFragment fragment= iter.next();
		ConstraintVariable2 fragmentCv= getConstraintVariable(fragment);
		fTCModel.createElementEqualsConstraints(typeCv, fragmentCv);
	}
}
 
Example #21
Source File: JavaApproximateVariableBindingExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Looks for field declarations (i.e. class member variables).
 */
@Override
public boolean visit(final FieldDeclaration node) {
	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
		addBinding(node, frag.getName().getIdentifier());
	}
	return true;
}
 
Example #22
Source File: VariableScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final VariableDeclarationStatement node) {
	final ASTNode parent = node.getParent();
	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
		variableScopes.put(parent, new Variable(frag.getName()
				.getIdentifier(), node.getType().toString(),
				ScopeType.SCOPE_LOCAL));
	}
	return false;
}
 
Example #23
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final VariableDeclarationStatement it) {
  boolean _isEmpty = IterableExtensions.isEmpty(Iterables.<Annotation>filter(it.modifiers(), Annotation.class));
  final boolean hasAnnotations = (!_isEmpty);
  final Consumer<VariableDeclarationFragment> _function = (VariableDeclarationFragment frag) -> {
    if (hasAnnotations) {
      this.appendToBuffer("/*FIXME Cannot add Annotation to Variable declaration. Java code: ");
    }
    final Function1<ASTNode, StringBuffer> _function_1 = (ASTNode it_1) -> {
      StringBuffer _xifexpression = null;
      if (hasAnnotations) {
        StringBuffer _xblockexpression = null;
        {
          this.appendToBuffer("*/");
          _xblockexpression = this.appendLineWrapToBuffer();
        }
        _xifexpression = _xblockexpression;
      }
      return _xifexpression;
    };
    this.appendModifiers(it, it.modifiers(), _function_1);
    this.appendToBuffer(this._aSTFlattenerUtils.handleVariableDeclaration(it.modifiers()));
    this.appendSpaceToBuffer();
    boolean _isMissingType = this.isMissingType(it.getType());
    boolean _not = (!_isMissingType);
    if (_not) {
      it.getType().accept(this);
    }
    this.appendExtraDimensions(frag.getExtraDimensions());
    this.appendSpaceToBuffer();
    frag.accept(this);
    this.appendSpaceToBuffer();
  };
  it.fragments().forEach(_function);
  return false;
}
 
Example #24
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void replaceSelectedExpressionWithTempDeclaration() throws CoreException {
	ASTRewrite rewrite = fCURewrite.getASTRewrite();
	Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected

	Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression);
	VariableDeclarationStatement tempDeclaration = createTempDeclaration(initializer);
	ASTNode replacement;

	ASTNode parent = selectedExpression.getParent();
	boolean isParentLambda = parent instanceof LambdaExpression;
	AST ast = rewrite.getAST();
	if (isParentLambda) {
		Block blockBody = ast.newBlock();
		blockBody.statements().add(tempDeclaration);
		if (!Bindings.isVoidType(((LambdaExpression) parent).resolveMethodBinding().getReturnType())) {
			List<VariableDeclarationFragment> fragments = tempDeclaration.fragments();
			SimpleName varName = fragments.get(0).getName();
			ReturnStatement returnStatement = ast.newReturnStatement();
			returnStatement.setExpression(ast.newSimpleName(varName.getIdentifier()));
			blockBody.statements().add(returnStatement);
		}
		replacement = blockBody;
	} else if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) {
		Block block = ast.newBlock();
		block.statements().add(tempDeclaration);
		replacement = block;
	} else {
		replacement = tempDeclaration;
	}
	ASTNode replacee = isParentLambda || !ASTNodes.hasSemicolon((ExpressionStatement) parent, fCu) ? selectedExpression : parent;
	rewrite.replace(replacee, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable));
}
 
Example #25
Source File: SourceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #26
Source File: JavaApproximateVariableBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Looks for local variable declarations. For every declaration of a
 * variable, the parent {@link Block} denoting the variable's scope is
 * stored in {@link #variableScope} map.
 *
 * @param node
 *            the node to visit
 */
@Override
public boolean visit(final VariableDeclarationStatement node) {
	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
		addBinding(node, frag.getName().getIdentifier());
	}
	return true;
}
 
Example #27
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ExpressionStatement createInitializer(ParameterInfo pi, String paramName, CompilationUnitRewrite cuRewrite) {
	AST ast= cuRewrite.getAST();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(pi.getOldName()));
	fragment.setInitializer(createFieldReadAccess(pi, paramName, ast, cuRewrite.getCu().getJavaProject(), false, null));
	VariableDeclarationExpression declaration= ast.newVariableDeclarationExpression(fragment);
	IVariableBinding variable= pi.getOldBinding();
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	int modifiers= variable.getModifiers();
	List<Modifier> newModifiers= ast.newModifiers(modifiers);
	declaration.modifiers().addAll(newModifiers);
	return ast.newExpressionStatement(declaration);
}
 
Example #28
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static List<IVariableBinding> getForInitializedVariables(VariableDeclarationExpression variableDeclarations) {
	List<IVariableBinding> forInitializerVariables = new ArrayList<>(1);
	for (Iterator<VariableDeclarationFragment> iter = variableDeclarations.fragments().iterator(); iter.hasNext();) {
		VariableDeclarationFragment fragment = iter.next();
		IVariableBinding binding = fragment.resolveBinding();
		if (binding != null) {
			forInitializerVariables.add(binding);
		}
	}
	return forInitializerVariables;
}
 
Example #29
Source File: JavaParseTreeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
       String name= getFieldName(node);
       ASTNode parent= node.getParent();
       push(JavaNode.FIELD, name, parent.getStartPosition(), parent.getLength());
       return false;
   }
 
Example #30
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void handleResourceDeclarations(TryStatement tryStatement) {
	List<VariableDeclarationExpression> resources= tryStatement.resources();
	for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	//check if the exception is thrown as a result of resource#close()
	boolean exitMarked= false;
	for (VariableDeclarationExpression variable : resources) {
		Type type= variable.getType();
		IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
		if (methodBinding != null) {
			ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
			for (int j= 0; j < exceptionTypes.length; j++) {
				if (matches(exceptionTypes[j])) { // a close() throws the caught exception
					// mark name of resource
					for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
						SimpleName name= fragment.getName();
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
					if (!exitMarked) {
						// mark exit position
						exitMarked= true;
						Block body= tryStatement.getBody();
						int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
						fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
								BasicElementLabels.getJavaElementName(fException.getName()))));
					}
				}
			}
		}
	}
}