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

The following examples show how to use org.eclipse.jdt.core.dom.FieldDeclaration. 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: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding removed fields. If class was removed, class removal is a breaking change.
 * @param version1
 * @param version2
 */
private void findRemoveAndRefactoringFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(type)){
			for (FieldDeclaration fieldInVersion1 : type.getFields()) {
				if(!UtilTools.isVisibilityPrivate(fieldInVersion1)){
					FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
					if(fieldInVersion2 == null){
						Boolean refactoring = this.checkAndProcessRefactoring(fieldInVersion1, type);
						if(!refactoring){
							this.processRemoveField(fieldInVersion1, type);
						}
					}
				}
			}
		}
	}
}
 
Example #2
Source File: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Searching changed fields type
 * @param version1
 * @param version2
 */
private void findChangedTypeFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(type)){
			for (FieldDeclaration fieldInVersion1 : type.getFields()) {
				if(!UtilTools.isVisibilityPrivate(fieldInVersion1) && !UtilTools.isVisibilityDefault(fieldInVersion1)){
					FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
					if(fieldInVersion2 != null && !UtilTools.isVisibilityPrivate(fieldInVersion2)){
						if(!fieldInVersion1.getType().toString().equals(fieldInVersion2.getType().toString())){
							String description = this.description.returnType(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(type));
							this.addChange(type, fieldInVersion2, Category.FIELD_CHANGE_TYPE, true, description);
						}
					}
				}
			}
		}
	}
}
 
Example #3
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initializeDeclaration(TypeDeclaration node) {
	FieldDeclaration[] fields= node.getFields();
	for (int i= 0; i < fields.length; i++) {
		FieldDeclaration fieldDeclaration= fields[i];
		List<VariableDeclarationFragment> fragments= fieldDeclaration.fragments();
		for (Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) {
			VariableDeclarationFragment vdf= iterator.next();
			FieldInfo fieldInfo= getFieldInfo(vdf.getName().getIdentifier());
			if (fieldInfo != null) {
				Assert.isNotNull(vdf);
				fieldInfo.declaration= vdf;
				fieldInfo.pi.setOldBinding(vdf.resolveBinding());
			}
		}
	}
}
 
Example #4
Source File: ASTUtil.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the <CODE>FieldDeclaration</CODE> for the specified field name.
 * The field has to be declared in the specified
 * <CODE>TypeDeclaration</CODE>.
 *
 * @param type
 *            The <CODE>TypeDeclaration</CODE>, where the
 *            <CODE>FieldDeclaration</CODE> is declared in.
 * @param fieldName
 *            The simple field name to search for.
 * @return the <CODE>FieldDeclaration</CODE> found in the specified
 *         <CODE>TypeDeclaration</CODE>.
 * @throws FieldDeclarationNotFoundException
 *             if no matching <CODE>FieldDeclaration</CODE> was found.
 */
public static FieldDeclaration getFieldDeclaration(TypeDeclaration type, String fieldName)
        throws FieldDeclarationNotFoundException {
    requireNonNull(type, "type declaration");
    requireNonNull(fieldName, "field name");

    for (FieldDeclaration field : type.getFields()) {
        for (Object fragObj : field.fragments()) {
            VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragObj;
            if (fieldName.equals(fragment.getName().getIdentifier())) {
                return field;
            }
        }
    }

    throw new FieldDeclarationNotFoundException(type, fieldName);
}
 
Example #5
Source File: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding added fields
 * @param version1
 * @param version2
 */
private void findAddedFields(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeVersion2 : version2.getApiAcessibleTypes()) {
		if(version1.containsAccessibleType(typeVersion2)){
			for (FieldDeclaration fieldInVersion2 : typeVersion2.getFields()) {
				String fullNameAndPath = this.getNameAndPath(fieldInVersion2, typeVersion2);
				if(!UtilTools.isVisibilityPrivate(fieldInVersion2) && !UtilTools.isVisibilityDefault(fieldInVersion2) && !this.fieldWithPathChanged.contains(fullNameAndPath)){
					FieldDeclaration fieldInVersion1;
						fieldInVersion1 = version1.getVersionField(fieldInVersion2, typeVersion2);
						if(fieldInVersion1 == null){
							String description = this.description.addition(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(typeVersion2));
							this.addChange(typeVersion2, fieldInVersion2, Category.FIELD_ADD, false, description);
						}
				}
			}
		} 
	}
}
 
Example #6
Source File: AddGetterSetterOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a new setter method for the specified field
 * 
 * @param field the field
 * @param astRewrite the AST rewrite to use
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
	final IType type= field.getDeclaringType();
	final String name= GetterSetterUtil.getSetterName(field, null);
	final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
	if (existing == null || !querySkipExistingMethods(existing)) {
		IJavaElement sibling= null;
		if (existing != null) {
			sibling= StubUtility.findNextSibling(existing);
			removeExistingAccessor(existing, rewrite);
		} else
			sibling= fInsert;
		ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
		addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
		if (Flags.isFinal(field.getFlags())) {
			ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
			if (fieldDecl != null) {
				ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
			}
		}

	}
}
 
Example #7
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 #8
Source File: CodeLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(FieldDeclaration node) {
	int index = this.tokenManager.lastIndexIn(node, TerminalTokens.TokenNameSEMICOLON);
	while (tokenIsOfType(index + 1, TerminalTokens.TokenNameCOMMENT_LINE,
			TerminalTokens.TokenNameCOMMENT_BLOCK)) {
		if (this.tokenManager.get(index).getLineBreaksAfter() > 0
				|| this.tokenManager.get(index + 1).getLineBreaksBefore() > 0) {
			break;
		}
		index++;
	}
	Token token = this.tokenManager.get(index);
	if (tokenIsOfType(index + 1, TerminalTokens.TokenNamestatic)) {
		return true;
	}
	token.clearLineBreaksAfter();
	token.putLineBreaksAfter(2);
	return true;
}
 
Example #9
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static BodyDeclaration getSelectedMemberDeclaration(ICompilationUnit unit, CodeActionParams params) {
	int start = DiagnosticsHelper.getStartOffset(unit, params.getRange());
	int end = DiagnosticsHelper.getEndOffset(unit, params.getRange());
	InnovationContext context = new InnovationContext(unit, start, end - start);
	context.setASTRoot(CodeActionHandler.getASTRoot(unit));

	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	while (node != null && !(node instanceof BodyDeclaration)) {
		node = node.getParent();
	}

	if (node != null && (node instanceof MethodDeclaration || node instanceof FieldDeclaration || node instanceof AbstractTypeDeclaration) && JdtFlags.isStatic((BodyDeclaration) node)) {
		return (BodyDeclaration) node;
	}

	return null;
}
 
Example #10
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 #11
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException {
	if (declaration instanceof MethodDeclaration) {
		IMethodBinding method = ((MethodDeclaration) declaration).resolveBinding();
		return method != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IMember) method.getJavaElement());
	} else if (declaration instanceof FieldDeclaration) {
		List<IMember> members = new ArrayList<>();
		for (Object fragment : ((FieldDeclaration) declaration).fragments()) {
			IVariableBinding variable = ((VariableDeclarationFragment) fragment).resolveBinding();
			if (variable != null) {
				members.add((IField) variable.getJavaElement());
			}
		}
		return RefactoringAvailabilityTesterCore.isMoveStaticMembersAvailable(members.toArray(new IMember[0]));
	} else if (declaration instanceof AbstractTypeDeclaration) {
		ITypeBinding type = ((AbstractTypeDeclaration) declaration).resolveBinding();
		return type != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IType) type.getJavaElement());
	}

	return false;
}
 
Example #12
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #13
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 #14
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * We pass both the fragment and the field because we need the field type when
 * the binding cannot be resolved
 */
public Attribute ensureAttributeForFragment(VariableDeclarationFragment fragment, FieldDeclaration field) {
	IVariableBinding binding = fragment.resolveBinding();
	Attribute attribute;
	if (binding == null)
		attribute = ensureAttributeFromFragmentIntoParentType(fragment, field,
				this.topFromContainerStack(Type.class));
	else {
		attribute = ensureAttributeForVariableBinding(binding);
		extractBasicModifiersFromBinding(binding.getModifiers(), attribute);
		if (Modifier.isStatic(binding.getModifiers()))
			attribute.setHasClassScope(true);
	}
	attribute.setIsStub(true);
	return attribute;
}
 
Example #15
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private List<Field> convert(FieldDeclaration fieldDeclaration) {
  List<Field> fields = new ArrayList<>();
  for (Object object : fieldDeclaration.fragments()) {
    org.eclipse.jdt.core.dom.VariableDeclarationFragment fragment =
        (org.eclipse.jdt.core.dom.VariableDeclarationFragment) object;
    Expression initializer;
    IVariableBinding variableBinding = fragment.resolveBinding();
    if (variableBinding.getConstantValue() == null) {
      initializer = convertOrNull(fragment.getInitializer());
    } else {
      initializer =
          convertConstantToLiteral(
              variableBinding.getConstantValue(),
              JdtUtils.createTypeDescriptor(variableBinding.getType()));
    }
    Field field =
        Field.Builder.from(JdtUtils.createFieldDescriptor(variableBinding))
            .setInitializer(initializer)
            .setSourcePosition(getSourcePosition(fieldDeclaration))
            .setNameSourcePosition(Optional.of(getSourcePosition(fragment.getName())))
            .build();
    fields.add(field);
  }
  return fields;
}
 
Example #16
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) {
	if (decl == null)
		return null;

	IBinding binding= name.resolveBinding();
	if (!canAddFinal(binding, decl))
		return null;

	if (decl instanceof SingleVariableDeclaration) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationExpression) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationFragment){
		VariableDeclarationFragment frag= (VariableDeclarationFragment)decl;
		decl= decl.getParent();
		if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
			List<VariableDeclarationFragment> list= new ArrayList<VariableDeclarationFragment>();
			list.add(frag);
			return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE);
		} else if (decl instanceof VariableDeclarationExpression) {
			return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
		}
	}

	return null;
}
 
Example #17
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Type getType(ASTNode node) {
	switch(node.getNodeType()){
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			return ((SingleVariableDeclaration) node).getType();
		case ASTNode.FIELD_DECLARATION:
			return ((FieldDeclaration) node).getType();
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
			return ((VariableDeclarationStatement) node).getType();
		case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
			return ((VariableDeclarationExpression) node).getType();
		case ASTNode.METHOD_DECLARATION:
			return ((MethodDeclaration)node).getReturnType2();
		case ASTNode.PARAMETERIZED_TYPE:
			return ((ParameterizedType)node).getType();
		default:
			Assert.isTrue(false);
			return null;
	}
}
 
Example #18
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #19
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 #20
Source File: TestQ20.java    From compiler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(TypeDeclaration node) {
//	classes++;
	for (Object d : node.bodyDeclarations()) {
		if (d instanceof FieldDeclaration)
			((FieldDeclaration)d).accept(this);
		if (d instanceof MethodDeclaration)
			((MethodDeclaration)d).accept(this);
	}
	return false;
}
 
Example #21
Source File: UiBinderJavaValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private void validateUiField(FieldDeclaration uiFieldDecl) {
  if (JavaASTUtils.hasSuppressWarnings(uiFieldDecl,
      SUPPRESS_WARNINGS_UIBINDER)) {
    return;
  }

  validateUiFieldVisibility(uiFieldDecl);
  validateUiFieldExistenceInUiXml(uiFieldDecl);
}
 
Example #22
Source File: NodeInfoStore.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a placeholder node of the given type. <code>null</code> if the type is not supported
 * @param nodeType Type of the node to create. Use the type constants in {@link NodeInfoStore}.
 * @return Returns a place holder node.
 */
public final ASTNode newPlaceholderNode(int nodeType) {
	try {
		ASTNode node= this.ast.createInstance(nodeType);
		switch (node.getNodeType()) {
			case ASTNode.FIELD_DECLARATION:
				((FieldDeclaration) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.MODIFIER:
				((Modifier) node).setKeyword(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
				break;
			case ASTNode.TRY_STATEMENT :
				((TryStatement) node).setFinally(this.ast.newBlock()); // have to set at least a finally block to be legal code
				break;
			case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
				((VariableDeclarationExpression) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.VARIABLE_DECLARATION_STATEMENT :
				((VariableDeclarationStatement) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.PARAMETERIZED_TYPE :
				((ParameterizedType) node).typeArguments().add(this.ast.newWildcardType());
				break;
		}
		return node;
	} catch (IllegalArgumentException e) {
		return null;
	}
	}
 
Example #23
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private List<UMLAttribute> processFieldDeclaration(CompilationUnit cu, FieldDeclaration fieldDeclaration, boolean isInterfaceField, String sourceFile) {
	UMLJavadoc javadoc = generateJavadoc(fieldDeclaration);
	List<UMLAttribute> attributes = new ArrayList<UMLAttribute>();
	Type fieldType = fieldDeclaration.getType();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		UMLType type = UMLType.extractTypeObject(cu, sourceFile, fieldType, fragment.getExtraDimensions());
		String fieldName = fragment.getName().getFullyQualifiedName();
		LocationInfo locationInfo = generateLocationInfo(cu, sourceFile, fragment, CodeElementType.FIELD_DECLARATION);
		UMLAttribute umlAttribute = new UMLAttribute(fieldName, type, locationInfo);
		VariableDeclaration variableDeclaration = new VariableDeclaration(cu, sourceFile, fragment);
		variableDeclaration.setAttribute(true);
		umlAttribute.setVariableDeclaration(variableDeclaration);
		umlAttribute.setJavadoc(javadoc);
		
		int fieldModifiers = fieldDeclaration.getModifiers();
		if((fieldModifiers & Modifier.PUBLIC) != 0)
			umlAttribute.setVisibility("public");
		else if((fieldModifiers & Modifier.PROTECTED) != 0)
			umlAttribute.setVisibility("protected");
		else if((fieldModifiers & Modifier.PRIVATE) != 0)
			umlAttribute.setVisibility("private");
		else if(isInterfaceField)
			umlAttribute.setVisibility("public");
		else
			umlAttribute.setVisibility("package");
		
		if((fieldModifiers & Modifier.FINAL) != 0)
			umlAttribute.setFinal(true);
		
		if((fieldModifiers & Modifier.STATIC) != 0)
			umlAttribute.setStatic(true);
		
		attributes.add(umlAttribute);
	}
	return attributes;
}
 
Example #24
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
private Attribute ensureAttributeFromFragmentIntoParentType(VariableDeclarationFragment fragment,
		FieldDeclaration field, Type parentType) {
	String name = fragment.getName().toString();
	String qualifiedName = Famix.qualifiedNameOf(parentType) + "." + name;
	if (attributes.has(qualifiedName))
		return attributes.named(qualifiedName);
	Attribute attribute = ensureBasicAttribute(parentType, name, qualifiedName,
			ensureTypeFromDomType(field.getType()));
	return attribute;
}
 
Example #25
Source File: TypeVisitor.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean visit(FieldDeclaration node) {
	List<AbstractField> fields2 = new ArrayList<>();
	ITypeBinding bind = node.getType().resolveBinding();
	
	String type = "";
	boolean primitive = false;
	
	if (bind != null) {
		type = bind.getQualifiedName();
		primitive = bind.isPrimitive();
	}
	
	List<String> modifiers = new ArrayList<String>();
	for (Object modifier : node.modifiers()) {
		modifiers.add(modifier.toString());
	}

	boolean builtIn = type.startsWith("java.") || type.startsWith("javax.") ? true : false;
	
	for (VariableDeclarationFragment vdf : (List<VariableDeclarationFragment>) node.fragments()) {
		fields2.add(new AbstractField(vdf.getName().getIdentifier(), type, modifiers, primitive, builtIn));
	}

	fields.addAll(fields2);
	return true;
}
 
Example #26
Source File: JavaASTVisitor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
private static String getVisibility(FieldDeclaration decl) {
    int modifiers = decl.getModifiers();
    if (Modifier.isPrivate(modifiers))
        return "private";
    if (Modifier.isProtected(modifiers))
        return "protected";
    if (Modifier.isPublic(modifiers))
        return "public";
    return "package";
}
 
Example #27
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type= field.getType();
	MethodDeclaration result= ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType= DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

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

	String body= CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		ASTNode getterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
    	block.statements().add(getterNode);
	} else {
		ReturnStatement rs= ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
    if (fGenerateJavadoc) {
		String string= CodeGeneration.getGetterComment(
			fField.getCompilationUnit() , getTypeName(field.getParent()), fGetterName,
			fField.getElementName(), ASTNodes.asString(type),
			StubUtility.getBaseName(fField),
			lineDelimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example #28
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FieldDeclaration createNewFieldDeclarationNode(MemberActionInfo info, CompilationUnit declaringCuNode, TypeVariableMaplet[] mapping, ASTRewrite rewrite, VariableDeclarationFragment oldFieldFragment) throws JavaModelException {
	Assert.isTrue(info.isFieldInfo());
	IField field= (IField) info.getMember();
	AST ast= rewrite.getAST();
	VariableDeclarationFragment newFragment= ast.newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	Expression initializer= oldFieldFragment.getInitializer();
	if (initializer != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(ast.newSimpleName(oldFieldFragment.getName().getIdentifier()));
	FieldDeclaration newField= ast.newFieldDeclaration(newFragment);
	FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, declaringCuNode);
	if (info.copyJavadocToCopiesInSubclasses())
		copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldField.getModifiers())));
	Type oldType= oldField.getType();
	ICompilationUnit cu= field.getCompilationUnit();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, cu, mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, cu, rewrite);
	newField.setType(newType);
	return newField;
}
 
Example #29
Source File: JavaASTVisitor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
private boolean visitInterface(TypeDeclaration node) {

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.name = node.getName().getFullyQualifiedName();
        interfaceInfo.fullName = NameResolver.getFullName(node);
        interfaceInfo.visibility = getVisibility(node);
        List<Type> superInterfaceList = node.superInterfaceTypes();
        for (Type superInterface : superInterfaceList)
            interfaceInfo.superInterfaceTypeList.add(NameResolver.getFullName(superInterface));
        if (node.getJavadoc() != null)
            interfaceInfo.comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength());
        interfaceInfo.content = sourceContent.substring(node.getStartPosition(), node.getStartPosition() + node.getLength());
        elementInfoPool.interfaceInfoMap.put(interfaceInfo.fullName, interfaceInfo);

        MethodDeclaration[] methodDeclarations = node.getMethods();
        for (MethodDeclaration methodDeclaration : methodDeclarations) {
            MethodInfo methodInfo = createMethodInfo(methodDeclaration, interfaceInfo.fullName);
            elementInfoPool.methodInfoMap.put(methodInfo.hashName(), methodInfo);
        }

        FieldDeclaration[] fieldDeclarations = node.getFields();
        for (FieldDeclaration fieldDeclaration : fieldDeclarations) {
            List<FieldInfo> fieldInfos = createFieldInfos(fieldDeclaration, interfaceInfo.fullName);
            for (FieldInfo fieldInfo : fieldInfos)
                elementInfoPool.fieldInfoMap.put(fieldInfo.hashName(), fieldInfo);
        }
        return true;
    }
 
Example #30
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int evaluateFieldModifiers(ASTNode newTypeDecl) {
	if (fSenderBinding.isAnnotation()) {
		return 0;
	}
	if (fSenderBinding.isInterface()) {
		// for interface members copy the modifiers from an existing field
		FieldDeclaration[] fieldDecls= ((TypeDeclaration) newTypeDecl).getFields();
		if (fieldDecls.length > 0) {
			return fieldDecls[0].getModifiers();
		}
		return 0;
	}
	int modifiers= 0;

	if (fVariableKind == CONST_FIELD) {
		modifiers |= Modifier.FINAL | Modifier.STATIC;
	} else {
		ASTNode parent= fOriginalNode.getParent();
		if (parent instanceof QualifiedName) {
			IBinding qualifierBinding= ((QualifiedName)parent).getQualifier().resolveBinding();
			if (qualifierBinding instanceof ITypeBinding) {
				modifiers |= Modifier.STATIC;
			}
		} else if (ASTResolving.isInStaticContext(fOriginalNode)) {
			modifiers |= Modifier.STATIC;
		}
	}
	ASTNode node= ASTResolving.findParentType(fOriginalNode, true);
	if (newTypeDecl.equals(node)) {
		modifiers |= Modifier.PRIVATE;
	} else if (node instanceof AnonymousClassDeclaration) {
		modifiers |= Modifier.PROTECTED;
	} else {
		modifiers |= Modifier.PUBLIC;
	}

	return modifiers;
}