/** * @param methodname * @return */ public FieldDeclaration getField( ) { ASTParser parser = ASTParser.newParser(AST.JLS8); String s = getStaticVariable ( ); if (s==null) return null; parser.setSource(s.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(FieldDeclaration node) { field = node; return true; } }); return field; }
@Override public boolean visit(FieldDeclaration fieldDeclaration) { Type fieldType = fieldDeclaration.getType(); int fieldModifiers = fieldDeclaration.getModifiers(); Visibility visibility = getVisibility(fieldModifiers); // boolean isFinal = (fieldModifiers & Modifier.FINAL) != 0; boolean isStatic = (fieldModifiers & Modifier.STATIC) != 0; List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { String fieldName = fragment.getName().getIdentifier(); final SDAttribute attribute = model.createAttribute(fieldName, containerStack.peek()); attribute.setStatic(isStatic); attribute.setVisibility(visibility); attribute.setType(AstUtils.normalizeTypeName(fieldType, fragment.getExtraDimensions(), false)); Expression expression = fragment.getInitializer(); if (expression != null) { //attribute.setAssignment(srbForAttributes.buildSourceRepresentation(fileContent, expression.getStartPosition(), expression.getLength())); addClientCode(attribute.key().toString(), srbForAttributes.buildPartialSourceRepresentation(fileContent, expression)); } attribute.setClientCode(srbForAttributes.buildEmptySourceRepresentation()); } return true; }
@Override public boolean visit(FieldDeclaration node) { int modifiers = node.getModifiers(); if (Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers)) { List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment varDeclFrag : fragments) { IVariableBinding varBinding = varDeclFrag.resolveBinding(); String enclosingClass = varBinding.getDeclaringClass().getQualifiedName(); if(!varBinding.getType().isPrimitive() && !varBinding.getType().getQualifiedName().equals("java.lang.String")){ final TACVariable fieldVar = new TACVariable(varBinding); if(!enclosingClass.equals(Config.MAINCLASS)){ context.addEncapsulatedVariable(fieldVar); } } } } return super.visit(node); }
private static boolean hasFieldInitializers(TypeDeclaration typeDecl) { boolean returnFlag = false; for (FieldDeclaration fd : typeDecl.getFields()) { // Skip over primitive types if (fd.getType().isPrimitiveType() ) { continue; } if (fd.fragments().size() > 0) if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) fd.fragments().get(0); if (vdf.getInitializer() != null) returnFlag = true; } } return returnFlag; }
private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) { AST ast = getAST(); VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); SimpleName variableName = ast.newSimpleName(fFieldName); fragment.setName(variableName); addLinkedName(rewrite, variableName, false); List<Dimension> extraDimensions = DimensionRewrite.copyDimensions(fTempDeclarationNode.extraDimensions(), rewrite); fragment.extraDimensions().addAll(extraDimensions); if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()) { Expression initializer = (Expression) rewrite.createCopyTarget(getTempInitializer()); fragment.setInitializer(initializer); } FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); VariableDeclarationStatement vds = getTempDeclarationStatement(); Type type = (Type) rewrite.createCopyTarget(vds.getType()); fieldDeclaration.setType(type); fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers())); return fieldDeclaration; }
@Override public boolean visit(VariableDeclarationFragment node) { boolean result = super.visit(node); if (isFirstSelectedNode(node)) { if (node.getParent() instanceof FieldDeclaration) { invalidSelection( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node)); } else { invalidSelection( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node)); } return false; } return result; }
/** {@inheritDoc} */ @Override public boolean visit(FieldDeclaration fieldDeclaration) { if (Modifier.isStatic(fieldDeclaration.getModifiers())) { testCase.setCurrentScope(TestScope.STATICFIELDS); } VariableDeclarationFragment varDeclFrgmnt = (VariableDeclarationFragment) fieldDeclaration.fragments().get(0); Expression expression = varDeclFrgmnt.getInitializer(); VariableReference varRef; if (expression == null) { varRef = retrieveDefaultValueAssignment(retrieveTypeClass(varDeclFrgmnt)); } else { varRef = retrieveVariableReference(expression, null); } varRef.setOriginalCode(fieldDeclaration.toString()); // TODO Use the name here as well? // String name = varDeclFrgmt.getName().getIdentifier(); // new BoundVariableReferenceImpl(testCase, varType, name); testCase.addVariable(varDeclFrgmnt.resolveBinding(), varRef); testCase.setCurrentScope(TestScope.FIELDS); return true; }
private void visitFragment(VariableDeclarationFragment fragment, FieldDeclaration field) { Attribute attribute = importer.ensureAttributeForFragment(fragment, field); importer.createSourceAnchor(attribute, fragment, (CompilationUnit) field.getRoot()); importer.ensureCommentFromBodyDeclaration(attribute, field); /* only the last fragment of a field contains the initializer code. * thus, to create the access to each variable in the fragment we need to ask that last fragment * we do not have to check the existence of that last fragment, because we already know that the field has at least one fragment */ VariableDeclarationFragment lastFragment = (VariableDeclarationFragment) field.fragments().get(field.fragments().size() - 1); if (lastFragment.getInitializer() != null) { Access access = importer.createAccessFromExpression(fragment.getName()); access.setIsWrite(true); importer.createAccessFromExpression((Expression) lastFragment.getInitializer()); } attribute.setIsStub(false); }
ClassModel(ASTNodeFactory astNodeFactory, String className, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<TypeModel> innerTypes, List<ASTNode> modifiers) { groovism = provide(); this.className = className; this.packageDeclaration = packageDeclaration; this.fields = fieldDeclarations(fields); this.methods = unmodifiableList(new LinkedList<>(methods)); this.modifiers = unmodifiableList(new LinkedList<>(modifiers)); this.imports = imports; this.innerTypes = unmodifiableList(new LinkedList<>(innerTypes)); if (isTestClass(methods)) { this.superClassType = Optional.of(astNodeFactory.simpleType(Specification.class.getSimpleName())); imports.add(0, astNodeFactory.importDeclaration(Specification.class)); } else { this.superClassType = Optional.ofNullable(superClassType); } }
InterfaceModel(String typeName, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<ASTNode> modifiers) { groovism = provide(); LinkedList<ImportDeclaration> importDeclarations = new LinkedList<>(imports); this.superClassType = Optional.ofNullable(superClassType).map(Object::toString); this.typeName = typeName; this.packageDeclaration = packageDeclaration; this.fields = unmodifiableList(new LinkedList<>(fields)); this.methods = unmodifiableList(new LinkedList<>(methods)); this.imports = unmodifiableList(importDeclarations); this.modifiers = unmodifiableList(modifiers); }
@Override public boolean visit(FieldDeclaration node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); ASTNode parent = node.getParent(); Scope scope = new Scope(cunit.getLineNumber(parent.getStartPosition()), getEndLine(parent, cunit)); TypeDeclaration dec = (TypeDeclaration) node.getParent(); String qName = dec.getName().getFullyQualifiedName(); PackageDeclaration packageDec = cunit.getPackage(); if(packageDec != null) qName = packageDec.getName().getFullyQualifiedName() + "." + qName; String type = !Modifier.isStatic(node.getModifiers()) ? qName : null; VariableTags tags = new VariableTags(varName, type, line, scope, true); variables.add(tags); } return false; }
@Override public boolean visit(TypeDeclaration node) { System.out.println(node.getParent().getClass()); if(info == null) info = new ClassInfo(node.resolveBinding().getQualifiedName(), VisibilityInfo.from(node)); for(FieldDeclaration f : node.getFields()) { if(!Modifier.isStatic(f.getModifiers())) { for(Object o : f.fragments()) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; info.addField(new FieldInfo(frag.getName().toString())); } } } return true; }
@SuppressWarnings("unchecked") private static String getVisibilityModifier(FieldDeclaration pInstanceVariableNode) { Iterator<Object> it = pInstanceVariableNode.modifiers().iterator(); // Find the visibility in the modifiers while (it.hasNext()) { String modifier = it.next().toString(); switch (modifier) { case "private": return "private"; case "protected": return "protected"; case "public": return "public"; default: break; } } // No visibility found return null; }
private List<FieldInfo> createFieldInfos(FieldDeclaration node, String belongTo) { List<FieldInfo> fieldInfos = new ArrayList<>(); Type type = node.getType(); Set<String> types = getTypes(type); String typeString = type.toString(); String visibility = getVisibility(node); boolean isStatic = isStatic(node); boolean isFinal = isFinal(node); String comment = ""; if (node.getJavadoc() != null) comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength()); List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment fragment : fragments) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.belongTo = belongTo; fieldInfo.name = fragment.getName().getFullyQualifiedName(); fieldInfo.typeString = typeString; fieldInfo.types = types; fieldInfo.visibility = visibility; fieldInfo.isFinal = isFinal; fieldInfo.isStatic = isStatic; fieldInfo.comment = comment; fieldInfos.add(fieldInfo); } return fieldInfos; }
/** * Method to get class attributes and add them in a list. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void getClassAttributes(CompilationUnit node){ for (Object type : node.types()){ if (type instanceof TypeDeclaration){ FieldDeclaration [] attributes = ((TypeDeclaration) type).getFields(); for (FieldDeclaration attribute: attributes){ List<FieldDeclaration> fragments = attribute.fragments(); Object obj = fragments.get(0); if (obj instanceof VariableDeclarationFragment){ String str = ((VariableDeclarationFragment) obj).getName().toString(); this.listOfAttributes.add(str); } } } } }
/** * Method to get all attributes or fields of a class. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void getClassAttributes(CompilationUnit node){ for (Object type : node.types()){ if (type instanceof TypeDeclaration){ FieldDeclaration [] attributes = ((TypeDeclaration) type).getFields(); for (FieldDeclaration attribute: attributes){ List<FieldDeclaration> fragments = attribute.fragments(); Object obj = fragments.get(0); if (obj instanceof VariableDeclarationFragment){ String s = ((VariableDeclarationFragment) obj).getName().toString(); this.listOfAttributes.add(s); } } } } }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
public static 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; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
@Override public boolean visit(VariableDeclarationFragment node) { boolean result = super.visit(node); if (isFirstSelectedNode(node)) { if (node.getParent() instanceof FieldDeclaration) { invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node)); } else { invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node)); } return false; } return result; }
private void initializeDestinations() { List<ASTNode> result = new ArrayList<>(); BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration(); ASTNode current = ASTResolving.findParentType(decl.getParent()); if (fAnalyzer.isValidDestination(current)) { result.add(current); } if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding = ASTNodes.getEnclosingType(current); ASTNode next = ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { if (fAnalyzer.isValidDestination(next)) { result.add(next); } current = next; binding = ASTNodes.getEnclosingType(current); next = ASTResolving.findParentType(next.getParent()); } } fDestinations = result.toArray(new ASTNode[result.size()]); fDestination = fDestinations[fDestinationIndex]; }
private void setFieldAnnotation(ASTRewrite rewrite, FieldDeclaration fieldDeclaration, String annotation) { SingleMemberAnnotation newFieldAnnotation = fieldDeclaration.getAST().newSingleMemberAnnotation(); newFieldAnnotation.setTypeName(rewrite.getAST().newSimpleName("Domain")); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(annotation); newFieldAnnotation.setValue(newStringLiteral); ASTNode modifier = getModifier(fieldDeclaration.modifiers()); if (modifier != null) { ListRewrite paramRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); paramRewrite.insertAfter(newFieldAnnotation, modifier, null); } else { ListRewrite fieldRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); fieldRewrite.insertFirst(newFieldAnnotation, null); } }
private void populateMethodDeclarations(TypeDeclaration declaration){ TypeDeclaration[] nestedTypes = declaration.getTypes(); for (int i = 0; i < nestedTypes.length; i++) { TypeDeclaration nestedType = nestedTypes[i]; populateMethodDeclarations(nestedType); } FieldDeclaration[] fields = declaration.getFields(); for (FieldDeclaration fieldDeclaration : fields) { fieldDeclaration.accept(new HeuristicOwnedVisitor()); } MethodDeclaration[] methods = declaration.getMethods(); for (MethodDeclaration methodDeclaration : methods) { methodDeclaration.accept(new HeuristicOwnedVisitor()); methodDeclaration.accept(new HeuristicOwnedLocalsVisitor()); this.methodDecls.add(methodDeclaration); } }
/** * returns all field bodies declared in a type, and its supertype, * recursively TODO: actual/formal substitution * */ public static Set<FieldDeclaration> fieldBody(TypeDeclaration typeDecl, TypeHierarchy hierarchy, Map<ast.Type, TypeDeclaration> types, QualifiedClassName cThis) { Set<FieldDeclaration> returnSet = new HashSet<FieldDeclaration>(); for (FieldDeclaration fd : typeDecl.getFields()) returnSet.add(fd); Type superclassType = typeDecl.getSuperclassType(); if (superclassType == null) return returnSet; if (superclassType.resolveBinding().getQualifiedName().equals(Utils.JAVA_LANG_OBJECT)) return returnSet; TypeDeclaration superTypeDecl = types.get(new QualifiedClassName(superclassType.resolveBinding(), cThis) .getType()); if (superTypeDecl != null) { Set<FieldDeclaration> auxSet = fieldBody(superTypeDecl, hierarchy, types, cThis); returnSet.addAll(auxSet); } return returnSet; }
/** * @param methodBinding * @return *//* private ast.TypeDeclaration getEnclosingType(IMethodBinding methodBinding) { ast.TypeDeclaration typeDeclaration = getTypeDeclaration(methodBinding.getDeclaringClass()); return typeDeclaration; }*/ public static List<ast.FieldDeclaration> getDeclaredFields( TypeDeclaration td) { List<ast.FieldDeclaration> fieldList = new ArrayList<ast.FieldDeclaration>(); for(FieldDeclaration fieldDec: td.getFields()){ List<VariableDeclarationFragment> fragments = fieldDec.fragments(); for(VariableDeclarationFragment varDecFrag: fragments){ fieldList.add(getFieldDeclaration(varDecFrag)); } } return fieldList; }
/*** * Lookup an ast.FieldDeclaration based on qualifiedClassName and fieldName * @param qualifiedClassName - fully qualified typeName name as in package.Foo.f * @param fieldName - simple field name as in f * @return an ast.FieldDeclaration already stored in the map * @return null if no such declaration exists in the map */ public static ast.FieldDeclaration getFieldDeclaration(String qualifiedClassName, String fieldName) { ast.FieldDeclaration fieldDeclaration = Adapter.getInstance().getFieldDeclaration(qualifiedClassName + fieldName); if(fieldDeclaration != null) return fieldDeclaration; // If not found, it may not have been added yet? // XXX. But why not do this once? Collection<ast.TypeDeclaration> allNodes = Adapter.getInstance().getTypeDeclarations(); for (AstNode astNode : allNodes) { ast.TypeDeclaration td = (ast.TypeDeclaration) astNode; if (td.type.getFullyQualifiedName().equals(qualifiedClassName)) { List<ast.FieldDeclaration> fields = td.fields; if (fields != null) for (ast.FieldDeclaration fd : fields) { if (fd.fieldName.endsWith(fieldName)) { Adapter.getInstance().mapFieldDeclaration(fd); return fd; } } } } return null; }
private void populateMethodDeclarations(TypeDeclaration declaration){ TypeDeclaration[] nestedTypes = declaration.getTypes(); for (int i = 0; i < nestedTypes.length; i++) { TypeDeclaration nestedType = nestedTypes[i]; populateMethodDeclarations(nestedType); } FieldDeclaration[] fields = declaration.getFields(); // for (FieldDeclaration fieldDeclaration : fields) { // fieldDeclaration.accept(new HeuristicOwnedVisitor()); // } MethodDeclaration[] methods = declaration.getMethods(); for (MethodDeclaration methodDeclaration : methods) { // methodDeclaration.accept(new HeuristicOwnedVisitor()); // methodDeclaration.accept(new HeuristicOwnedLocalsVisitor()); this.methodDecls.add(methodDeclaration); } }
@Override public boolean visit(FieldDeclaration fieldDeclaration) { List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { IVariableBinding binding = fragment.resolveBinding(); if (binding == null) continue; IField field = (IField) binding.getJavaElement(); FieldDetails fieldDetails = new FieldDetails(); fieldDetails.setModifiers(fieldDeclaration.getModifiers()); allDetails.put(field.getHandleIdentifier(), fieldDetails); } return true; }
private void processInlineLicense(IDocument doc) throws Exception { CompilationUnit cu = getAST(doc); cu.recordModifications(); AST ast = cu.getAST(); if (cu.types().get(0) instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration)cu.types().get(0); FieldDeclaration[] fd = td.getFields(); if (fd.length == 0) { td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } else { FieldDeclaration firstFd = fd[0]; VariableDeclarationFragment vdf = (VariableDeclarationFragment)firstFd.fragments().get(0); if (vdf.getName().getIdentifier().equals("COPYRIGHT")) { td.bodyDeclarations().remove(0); td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } else { td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } } } //record changes TextEdit edits = cu.rewrite(doc, null); edits.apply(doc); }
private FieldDeclaration createLiceseInLineField(AST ast) { VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("COPYRIGHT")); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(license_inline); vdf.setInitializer(sl); FieldDeclaration fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)); fd.setType(ast.newSimpleType(ast.newSimpleName("String"))); return fd; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration .modifiers() .addAll( ASTNodeFactory.newModifiers( ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) continue; if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) rewrite .getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()) .insertAt(declaration, 0, editGroup); else if (node instanceof AnonymousClassDeclaration) rewrite .getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) rewrite .getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); } } else Assert.isTrue(false); addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment( fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit)); if (comment != null && comment.length() > 0) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) return; positionGroups.setEndPosition(rewrite.track(fragment)); }
private void createFieldsForAccessedLocals( CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException { final ImportRewrite importRewrite = rewrite.getImportRewrite(); final ASTRewrite astRewrite = rewrite.getASTRewrite(); final AST ast = astRewrite.getAST(); for (int i = 0; i < varBindings.length; i++) { VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); fragment.setInitializer(null); fragment.setName(ast.newSimpleName(fieldNames[i])); FieldDeclaration field = ast.newFieldDeclaration(fragment); ITypeBinding varType = varBindings[i].getType(); field.setType(importRewrite.addImport(varType, ast)); field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL)); if (doAddComments()) { String string = CodeGeneration.getFieldComment( rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu)); if (string != null) { Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC); field.setJavadoc(javadoc); } } newBodyDeclarations.add(field); addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false); } }
private List<VariableDeclarationFragment> getFieldsToInitializeInConstructor() { List<VariableDeclarationFragment> result = new ArrayList<VariableDeclarationFragment>(0); for (Iterator<BodyDeclaration> iter = fAnonymousInnerClassNode.bodyDeclarations().iterator(); iter.hasNext(); ) { Object element = iter.next(); if (element instanceof FieldDeclaration) { List<VariableDeclarationFragment> fragments = ((FieldDeclaration) element).fragments(); for (Iterator<VariableDeclarationFragment> fragmentIter = fragments.iterator(); fragmentIter.hasNext(); ) { VariableDeclarationFragment fragment = fragmentIter.next(); if (isToBeInitializerInConstructor(fragment, result)) result.add(fragment); } } } return result; }
private String[] getNamesOfFieldsInDeclaringType() { final AbstractTypeDeclaration type = getEnclosingType(); if (type instanceof TypeDeclaration) { FieldDeclaration[] fields = ((TypeDeclaration) type).getFields(); List<String> result = new ArrayList<String>(fields.length); 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()); } } return result.toArray(new String[result.size()]); } return new String[] {}; }
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; }
private void initializeDestinations() { List<ASTNode> result = new ArrayList<ASTNode>(); BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration(); ASTNode current = ASTResolving.findParentType(decl.getParent()); if (fAnalyzer.isValidDestination(current)) { result.add(current); } if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding = ASTNodes.getEnclosingType(current); ASTNode next = ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { if (fAnalyzer.isValidDestination(next)) { result.add(next); } current = next; binding = ASTNodes.getEnclosingType(current); next = ASTResolving.findParentType(next.getParent()); } } fDestinations = result.toArray(new ASTNode[result.size()]); fDestination = fDestinations[fDestinationIndex]; }
private void computeConstantDeclarationLocation() throws JavaModelException { if (isDeclarationLocationComputed()) return; BodyDeclaration lastStaticDependency = null; Iterator<BodyDeclaration> decls = getContainingTypeDeclarationNode().bodyDeclarations().iterator(); while (decls.hasNext()) { BodyDeclaration decl = decls.next(); int modifiers; if (decl instanceof FieldDeclaration) modifiers = ((FieldDeclaration) decl).getModifiers(); else if (decl instanceof Initializer) modifiers = ((Initializer) decl).getModifiers(); else { continue; /* this declaration is not a field declaration or initializer, so the placement of the constant declaration relative to it does not matter */ } if (Modifier.isStatic(modifiers) && depends(getSelectedExpression(), decl)) lastStaticDependency = decl; } if (lastStaticDependency == null) fInsertFirst = true; else fToInsertAfter = lastStaticDependency; }
private static boolean depends(IExpressionFragment selected, BodyDeclaration bd) { /* We currently consider selected to depend on bd only if db includes a declaration * of a static field on which selected depends. * * A more accurate strategy might be to also check if bd contains (or is) a * static initializer containing code which changes the value of a static field on * which selected depends. However, if a static is written to multiple times within * during class initialization, it is difficult to predict which value should be used. * This would depend on which value is used by expressions instances for which the new * constant will be substituted, and there may be many of these; in each, the * static field in question may have taken on a different value (if some of these uses * occur within static initializers). */ if (bd instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) bd; for (Iterator<VariableDeclarationFragment> fragments = fieldDecl.fragments().iterator(); fragments.hasNext(); ) { VariableDeclarationFragment fragment = fragments.next(); SimpleName staticFieldName = fragment.getName(); if (selected.getSubFragmentsMatching( ASTFragmentFactory.createFragmentForFullSubtree(staticFieldName)) .length != 0) return true; } } return false; }