List of usage examples for org.eclipse.jdt.core.dom VariableDeclarationFragment getParent
public final ASTNode getParent()
null if this is the root node. From source file:ch.acanda.eclipse.pmd.java.resolution.design.SingularFieldQuickFix.java
License:Open Source License
/** * Replaces the field declaration with a local variable declaration. *///www. j av a 2s. co m @Override protected boolean apply(final VariableDeclarationFragment node) { final String name = node.getName().getIdentifier(); final AssignmentNodeFinder finder = new AssignmentNodeFinder(name); final Optional<Assignment> assignment = finder.findNode(node.getParent().getParent()); if (assignment.isPresent()) { replaceAssignment(node, assignment.get(), !finder.hasMoreThanOneAssignment()); updateFieldDeclaration(node); } return assignment.isPresent(); }
From source file:ch.acanda.eclipse.pmd.java.resolution.design.SingularFieldQuickFix.java
License:Open Source License
/** * Replaces the assignment with a variable declaration. If the assignment is the only one in the block for this * variable, the final modifier is added to the declaration. *///from www . j a v a 2 s . c o m @SuppressWarnings("unchecked") private void replaceAssignment(final VariableDeclarationFragment node, final Assignment assignment, final boolean finalDeclaration) { final FieldDeclaration fieldDeclaration = (FieldDeclaration) node.getParent(); final VariableDeclarationStatement declaration = (VariableDeclarationStatement) node.getAST() .createInstance(VariableDeclarationStatement.class); declaration.setType(ASTUtil.copy(fieldDeclaration.getType())); final VariableDeclarationFragment fragment = (VariableDeclarationFragment) node.getAST() .createInstance(VariableDeclarationFragment.class); fragment.setName(ASTUtil.copy(node.getName())); fragment.setInitializer(ASTUtil.copy(assignment.getRightHandSide())); declaration.fragments().add(fragment); if (finalDeclaration) { final Modifier modifier = (Modifier) node.getAST().createInstance(Modifier.class); modifier.setKeyword(ModifierKeyword.FINAL_KEYWORD); declaration.modifiers().add(modifier); } ASTUtil.replace(assignment.getParent(), declaration); }
From source file:ch.acanda.eclipse.pmd.java.resolution.design.SingularFieldQuickFix.java
License:Open Source License
/** * Updates the field declaration. If the replaced field was the only fragment, the entire field declaration is * removed. Otherwise the field declaration stays and only the respective fragment is removed. *///w w w . j a v a 2s .c o m private void updateFieldDeclaration(final VariableDeclarationFragment node) { final FieldDeclaration fieldDeclaration = (FieldDeclaration) node.getParent(); @SuppressWarnings("unchecked") final List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); if (fragments.size() > 1) { for (final VariableDeclarationFragment fragment : fragments) { if (fragment.getName().getIdentifier().equals(node.getName().getIdentifier())) { fragment.delete(); } } } else { fieldDeclaration.delete(); } }
From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ReplaceStringsVisitor.java
License:Open Source License
/** * Examines if the StringLiteral is part of an assignment corresponding to the * a string variable declaration, e.g. String foo = id. * * The parent fragment is of syntax "var = expr" or "var[] = expr". * We want the type of the variable, which is either held by a * VariableDeclarationStatement ("type [fragment]") or by a * VariableDeclarationExpression. In either case, the type can be an array * but for us all that matters is to know whether the type is an int or * a string.//w w w. java2 s . c o m */ private boolean examineVariableDeclaration(StringLiteral node) { VariableDeclarationFragment fragment = findParentClass(node, VariableDeclarationFragment.class); if (fragment != null) { ASTNode parent = fragment.getParent(); Type type = null; if (parent instanceof VariableDeclarationStatement) { type = ((VariableDeclarationStatement) parent).getType(); } else if (parent instanceof VariableDeclarationExpression) { type = ((VariableDeclarationExpression) parent).getType(); } if (type instanceof SimpleType) { return isJavaString(type.resolveBinding()); } } return false; }
From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java
License:Open Source License
/** * Add an initializer expression to a field declaration fragment. *//*from w w w .j a v a2 s. c o m*/ private void addFieldInitializer(VariableDeclarationFragment var) { AST ast = var.getAST(); ITypeBinding type = ((FieldDeclaration) var.getParent()).getType().resolveBinding(); var.setInitializer(getDefaultValue(ast, type)); }
From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java
License:Open Source License
private CAstNode visit(VariableDeclarationFragment n, WalkContext context) { int modifiers; if (n.getParent() instanceof VariableDeclarationStatement) modifiers = ((VariableDeclarationStatement) n.getParent()).getModifiers(); else if (n.getParent() instanceof VariableDeclarationExpression) modifiers = ((VariableDeclarationExpression) n.getParent()).getModifiers(); else/*w ww .j a v a2 s . co m*/ modifiers = ((FieldDeclaration) n.getParent()).getModifiers(); boolean isFinal = (modifiers & Modifier.FINAL) != 0; ITypeBinding type = n.resolveBinding().getType(); Expression init = n.getInitializer(); CAstNode initNode; String t = type.getBinaryName(); if (init == null) { if (JDT2CAstUtils.isLongOrLess(type)) // doesn't include boolean initNode = fFactory.makeConstant(0); else if (t.equals("D") || t.equals("F")) initNode = fFactory.makeConstant(0.0); else initNode = fFactory.makeConstant(null); } else initNode = visitNode(init, context); Object defaultValue = JDT2CAstUtils.defaultValueForType(type); return makeNode(context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant(new CAstSymbolImpl(n.getName().getIdentifier(), fTypeDict.getCAstTypeFor(type), isFinal, defaultValue)), initNode); }
From source file:de.ovgu.cide.export.physical.ahead.FieldMethodVisibilityLifter.java
License:Open Source License
private boolean visitName(Name node) { IBinding binding = node.resolveBinding(); if (binding == null) return true; ASTNode declaration = compUnit.findDeclaringNode(binding); if (declaration instanceof MethodDeclaration) { makeProtected((MethodDeclaration) declaration); } else if (declaration instanceof VariableDeclarationFragment) { VariableDeclarationFragment variableFragment = (VariableDeclarationFragment) declaration; if (variableFragment.getParent() instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) variableFragment.getParent(); makeProtected(fieldDecl);/*w w w . j a v a2 s .c o m*/ } } return false; }
From source file:edu.buffalo.cse.green.relationship.dependency.DependencyLRecognizer.java
License:Open Source License
/** * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.VariableDeclarationFragment) *//*from ww w.ja va 2 s.c om*/ public boolean visit(VariableDeclarationFragment node) { checkForDependency(node.getParent(), node.getName(), node.getInitializer()); return true; }
From source file:edu.illinois.compositerefactorings.refactorings.copymembertosubtype.CopyMemberToSubtypeRefactoringProcessor.java
License:Open Source License
private void copyMembers(Collection<MemberVisibilityAdjustor> adjustors, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, RefactoringStatus status, MemberActionInfo[] infos, IType[] destinations, CompilationUnitRewrite sourceRewriter, CompilationUnitRewrite unitRewriter, IProgressMonitor monitor) throws JavaModelException { try {//w ww . ja v a 2s .c o m monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 1); IType type = null; TypeVariableMaplet[] mapping = null; for (int index = 0; index < destinations.length; index++) { type = destinations[index]; mapping = TypeVariableUtil.superTypeToInheritedType(getDeclaringType(), type); if (unitRewriter.getCu().equals(type.getCompilationUnit())) { IMember member = null; MemberVisibilityAdjustor adjustor = null; AbstractTypeDeclaration declaration = ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, unitRewriter.getRoot()); ImportRewriteContext context = new ContextSensitiveImportRewriteContext(declaration, unitRewriter.getImportRewrite()); for (int offset = infos.length - 1; offset >= 0; offset--) { member = infos[offset].getMember(); adjustor = new MemberVisibilityAdjustor(type, member); if (infos[offset].isNewMethodToBeDeclaredAbstract()) adjustor.setIncoming(false); adjustor.setRewrite(sourceRewriter.getASTRewrite(), sourceRewriter.getRoot()); adjustor.setRewrites(rewrites); // TW: set to error if bug 78387 is fixed adjustor.setFailureSeverity(RefactoringStatus.WARNING); adjustor.setStatus(status); adjustor.setAdjustments(adjustments); adjustor.adjustVisibility(new SubProgressMonitor(monitor, 1)); adjustments.remove(member); adjustors.add(adjustor); status.merge(checkProjectCompliance( getCompilationUnitRewrite(rewrites, getDeclaringType().getCompilationUnit()), type, new IMember[] { infos[offset].getMember() })); if (infos[offset].isFieldInfo()) { final VariableDeclarationFragment oldField = ASTNodeSearchUtil .getFieldDeclarationFragmentNode((IField) infos[offset].getMember(), sourceRewriter.getRoot()); if (oldField != null) { FieldDeclaration newField = createNewFieldDeclarationNode(infos[offset], sourceRewriter.getRoot(), mapping, unitRewriter.getASTRewrite(), oldField); unitRewriter.getASTRewrite() .getListRewrite(declaration, declaration.getBodyDeclarationsProperty()) .insertAt(newField, ASTNodes.getInsertionIndex(newField, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription( RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN)); ImportRewriteUtil.addImports(unitRewriter, context, oldField.getParent(), new HashMap<Name, String>(), new HashMap<Name, String>(), false); } } else { final MethodDeclaration oldMethod = ASTNodeSearchUtil.getMethodDeclarationNode( (IMethod) infos[offset].getMember(), sourceRewriter.getRoot()); if (oldMethod != null) { MethodDeclaration newMethod = createNewMethodDeclarationNode(infos[offset], mapping, unitRewriter, oldMethod); unitRewriter.getASTRewrite() .getListRewrite(declaration, declaration.getBodyDeclarationsProperty()) .insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription( RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN)); ImportRewriteUtil.addImports(unitRewriter, context, oldMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); } } } } } } finally { monitor.done(); } }
From source file:edu.uci.ics.sourcerer.extractor.ast.ReferenceExtractorVisitor.java
License:Open Source License
/** * This method writes://from w w w.j av a 2 s.c om * <ul> * <li>Field entity to <code>IEntityWriter</code>. * <ul> * <li>Inside relation to <code>IRelationWriter</code>.</li> * <li>Holds relation to <code>IRelationWriter</code>.</li> * </ul></li> * <li>Local variable to <code>ILocalVariableWriter</code>. * <ul> * <li>Uses relation to <code>IRelationWriter</codE>.</li> * </ul></li> * </ul> * * Field fully qualified names (FQNs) adhere to the following format:<br> * parent fqn + . + simple name */ @Override public boolean visit(VariableDeclarationFragment node) { if (node.getParent() instanceof FieldDeclaration) { FieldDeclaration parent = (FieldDeclaration) node.getParent(); // Get the fqn String fqn = fqnStack.getTypeFqn(node.getName().getIdentifier()); // Write the entity entityWriter.writeField(fqn, parent.getModifiers(), MetricsCalculator.computeLinesOfCode(getSource(node)), getLocation(node)); // Write the inside relation relationWriter.writeInside(fqn, fqnStack.getFqn(), getUnknownLocation()); Type type = parent.getType(); String typeFqn = getTypeFqn(type); // Write the holds relation relationWriter.writeHolds(fqn, typeFqn, getLocation(type)); // Add the field to the fqnstack fqnStack.push(fqn, Entity.FIELD); // Write the uses relation accept(parent.getType()); // Write the javadoc comment accept(parent.getJavadoc()); } else if (node.getParent() instanceof VariableDeclarationStatement) { VariableDeclarationStatement parent = (VariableDeclarationStatement) node.getParent(); Type type = parent.getType(); String typeFqn = getTypeFqn(type); // Write the local variable localVariableWriter.writeLocalVariable(node.getName().getIdentifier(), parent.getModifiers(), typeFqn, type.getStartPosition(), type.getLength(), fqnStack.getFqn(), getLocation(node)); } else if (node.getParent() instanceof VariableDeclarationExpression) { VariableDeclarationExpression parent = (VariableDeclarationExpression) node.getParent(); Type type = parent.getType(); String typeFqn = getTypeFqn(type); // Write the local variable localVariableWriter.writeLocalVariable(node.getName().getIdentifier(), parent.getModifiers(), typeFqn, type.getStartPosition(), type.getLength(), fqnStack.getFqn(), getLocation(node)); } else { logger.log(Level.SEVERE, "Unknown parent for variable declaration fragment."); } IVariableBinding binding = node.resolveBinding(); if (binding != null && binding.isField() && !(node.getParent() instanceof FieldDeclaration)) { logger.log(Level.SEVERE, "It's a field but it shouldn't be!"); } if (node.getInitializer() != null) { inLhsAssignment = true; accept(node.getName()); inLhsAssignment = false; accept(node.getInitializer()); } return false; }