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

The following examples show how to use org.eclipse.jdt.core.dom.TypeDeclaration. 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: ModifierRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ListRewrite evaluateListRewrite(ASTRewrite rewrite, ASTNode declNode) {
	switch (declNode.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			return rewrite.getListRewrite(declNode, MethodDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.FIELD_DECLARATION:
			return rewrite.getListRewrite(declNode, FieldDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
			return rewrite.getListRewrite(declNode, VariableDeclarationExpression.MODIFIERS2_PROPERTY);
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
			return rewrite.getListRewrite(declNode, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			return rewrite.getListRewrite(declNode, SingleVariableDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.TYPE_DECLARATION:
			return rewrite.getListRewrite(declNode, TypeDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.ENUM_DECLARATION:
			return rewrite.getListRewrite(declNode, EnumDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.ANNOTATION_TYPE_DECLARATION:
			return rewrite.getListRewrite(declNode, AnnotationTypeDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.ENUM_CONSTANT_DECLARATION:
			return rewrite.getListRewrite(declNode, EnumConstantDeclaration.MODIFIERS2_PROPERTY);
		case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
			return rewrite.getListRewrite(declNode, AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY);
		default:
			throw new IllegalArgumentException("node has no modifiers: " + declNode.getClass().getName()); //$NON-NLS-1$
	}
}
 
Example #2
Source File: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinTypeDeclaration(TypeDeclaration typeDeclaration, TypeCheckElimination originalTypeCheckElimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	for(MethodDeclaration method : typeDeclaration.getMethods()) {
		Block methodBody = method.getBody();
		if(methodBody != null) {
			List<TypeCheckElimination> list = generateTypeCheckEliminationsWithinMethodBody(methodBody);
			for(TypeCheckElimination typeCheckElimination : list) {
				if(!typeCheckElimination.allTypeCheckBranchesAreEmpty()) {
					TypeCheckCodeFragmentAnalyzer analyzer = new TypeCheckCodeFragmentAnalyzer(typeCheckElimination, typeDeclaration, method, null);
					if((typeCheckElimination.getTypeField() != null || typeCheckElimination.getTypeLocalVariable() != null || typeCheckElimination.getTypeMethodInvocation() != null) &&
							typeCheckElimination.allTypeCheckingsContainStaticFieldOrSubclassType() && typeCheckElimination.isApplicable()) {
						if(originalTypeCheckElimination.matchingStatesOrSubTypes(typeCheckElimination))
							typeCheckEliminations.add(typeCheckElimination);
					}
				}
			}
		}
	}
	return typeCheckEliminations;
}
 
Example #3
Source File: FieldDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Searching changed default values
 * @param version1
 * @param version2
 */
private void findDefaultValueFields(APIVersion version1, APIVersion version2){
	for (TypeDeclaration type : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(type)){
			for (FieldDeclaration fieldInVersion1 : type.getFields()) {
				if(this.isFieldAccessible(fieldInVersion1)){
					FieldDeclaration fieldInVersion2 = version2.getVersionField(fieldInVersion1, type);
					if(this.isFieldAccessible(fieldInVersion2) && this.thereAreDifferentDefaultValueField(fieldInVersion1, fieldInVersion2)){
						String description = this.description.changeDefaultValue(UtilTools.getFieldName(fieldInVersion2), UtilTools.getPath(type));
						this.addChange(type, fieldInVersion2, Category.FIELD_CHANGE_DEFAULT_VALUE, true, description);
					}
				}
			}
		}
	}
}
 
Example #4
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String getUniqueMethodName(ASTNode astNode, String suggestedName) throws JavaModelException {
	while (astNode != null && !(astNode instanceof TypeDeclaration || astNode instanceof AnonymousClassDeclaration)) {
		astNode = astNode.getParent();
	}
	if (astNode instanceof TypeDeclaration) {
		ITypeBinding typeBinding = ((TypeDeclaration) astNode).resolveBinding();
		if (typeBinding == null) {
			return suggestedName;
		}
		IType type = (IType) typeBinding.getJavaElement();
		if (type == null) {
			return suggestedName;
		}
		IMethod[] methods = type.getMethods();

		int suggestedPostfix = 2;
		String resultName = suggestedName;
		while (suggestedPostfix < 1000) {
			if (!hasMethod(methods, resultName)) {
				return resultName;
			}
			resultName = suggestedName + suggestedPostfix++;
		}
	}
	return suggestedName;
}
 
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: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addAdditionalMethodsToTargetClass() {
	AST ast = targetTypeDeclaration.getAST();
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		TypeVisitor typeVisitor = new TypeVisitor();
		methodDeclaration.accept(typeVisitor);
		for(ITypeBinding typeBinding : typeVisitor.getTypeBindings()) {
			this.additionalTypeBindingsToBeImportedInTargetClass.add(typeBinding);
		}
		MethodDeclaration newMethodDeclaration = (MethodDeclaration)ASTNode.copySubtree(ast, methodDeclaration);
		ASTRewrite targetRewriter = ASTRewrite.create(targetCompilationUnit.getAST());
		ListRewrite targetClassBodyRewrite = targetRewriter.getListRewrite(targetTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		targetClassBodyRewrite.insertLast(newMethodDeclaration, null);
		try {
			TextEdit targetEdit = targetRewriter.rewriteAST();
			targetMultiTextEdit.addChild(targetEdit);
			targetCompilationUnitChange.addTextEditGroup(new TextEditGroup("Add additional moved method", new TextEdit[] {targetEdit}));
		}
		catch(JavaModelException javaModelException) {
			javaModelException.printStackTrace();
		}
	}
}
 
Example #7
Source File: MethodDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding methods with change in exception list 
 * @param version1
 * @param version2
 */
private void findChangedExceptionTypeMethods(APIVersion version1, APIVersion version2) {
	for(TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()){
		if(version2.containsAccessibleType(typeVersion1)){
			for(MethodDeclaration methodVersion1 : typeVersion1.getMethods()){
				if(this.isMethodAcessible(methodVersion1)){
					MethodDeclaration methodVersion2 = version2.getEqualVersionMethod(methodVersion1, typeVersion1);
					if(this.isMethodAcessible(methodVersion2)){
						List<SimpleType> exceptionsVersion1 = methodVersion1.thrownExceptionTypes();
						List<SimpleType> exceptionsVersion2 = methodVersion2.thrownExceptionTypes();
						if(exceptionsVersion1.size() != exceptionsVersion2.size() || (this.diffListExceptions(exceptionsVersion1, exceptionsVersion2))) {
							String nameMethod = this.getSimpleNameMethod(methodVersion1);
							String nameClass = UtilTools.getPath(typeVersion1);
							String description = this.description.exception(nameMethod, exceptionsVersion1, exceptionsVersion2, nameClass);
							this.addChange(typeVersion1, methodVersion1, Category.METHOD_CHANGE_EXCEPTION_LIST, true, description);
						}
					}
				}
			}
		}
	}
}
 
Example #8
Source File: MethodDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding added methods
 * @param version1
 * @param version2
 */
private void findAddedMethods(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeInVersion2 : version2.getApiAcessibleTypes()) {
		if(version1.containsType(typeInVersion2)){
			for(MethodDeclaration methodInVersion2: typeInVersion2.getMethods()){
				if(this.isMethodAcessible(methodInVersion2)){
					MethodDeclaration methodInVersion1 = version1.findMethodByNameAndParameters(methodInVersion2, typeInVersion2);
					String fullNameAndPathMethodVersion2 = this.getFullNameMethodAndPath(methodInVersion2, typeInVersion2);
					if(methodInVersion1 == null && !this.methodsWithPathChanged.contains(fullNameAndPathMethodVersion2)){
						String nameMethod = this.getSimpleNameMethod(methodInVersion2);
						String nameClass = UtilTools.getPath(typeInVersion2);
						String description = this.description.addition(nameMethod, nameClass);
						this.addChange(typeInVersion2, methodInVersion2, Category.METHOD_ADD, false, description);
					}
				}
			}
		}
	}
}
 
Example #9
Source File: ClassDiagramExporter.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration node) {

	if (ElementTypeTeller.isAssociation(node)) {
		ITypeBinding typeBinding = node.resolveBinding();
		if (typeBinding != null) {
			try {
				allLinks.add(loader.loadClass(typeBinding.getQualifiedName()));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	return false;
}
 
Example #10
Source File: CreateSyncMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static List<IJavaCompletionProposal> createProposalsForProblemOnSyncType(
    ICompilationUnit syncCompilationUnit, ASTNode problemNode,
    String asyncMethodBindingKey) {
  TypeDeclaration syncTypeDecl = (TypeDeclaration) ASTResolving.findAncestor(
      problemNode, ASTNode.TYPE_DECLARATION);
  assert (syncTypeDecl != null);
  String syncQualifiedTypeName = syncTypeDecl.resolveBinding().getQualifiedName();

  // Lookup the async version of the interface
  IType asyncType = RemoteServiceUtilities.findAsyncType(syncTypeDecl);
  if (asyncType == null) {
    return Collections.emptyList();
  }

  MethodDeclaration asyncMethodDecl = JavaASTUtils.findMethodDeclaration(
      asyncType.getCompilationUnit(), asyncMethodBindingKey);
  if (asyncMethodDecl == null) {
    return Collections.emptyList();
  }

  return Collections.<IJavaCompletionProposal> singletonList(new CreateSyncMethodProposal(
      syncCompilationUnit, syncQualifiedTypeName, asyncMethodDecl));
}
 
Example #11
Source File: SwiftTranslator.java    From juniversal with MIT License 6 votes vote down vote up
@Override public void translateFile(SourceFile sourceFile) {
    CompilationUnit compilationUnit = sourceFile.getCompilationUnit();
    TypeDeclaration mainTypeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);

    String typeName = mainTypeDeclaration.getName().getIdentifier();

    String fileName = typeName + ".cs";
    File file = new File(getOutputDirectory(), fileName);

    try (FileWriter writer = new FileWriter(file)) {
        SwiftSourceFileWriter swiftSourceFileWriter = new SwiftSourceFileWriter(this, sourceFile, writer);

        swiftSourceFileWriter.writeRootNode(compilationUnit);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean shouldValidateType(TypeDeclaration type) {
  if (!type.isInterface()) {
    return false;
  }

  ITypeBinding typeBinding = type.resolveBinding();
  if (typeBinding == null) {
    return false;
  }

  if (!ClientBundleUtilities.isClientBundle(typeBinding)) {
    return false;
  }

  // Don't actually validate the built-in ClientBundle and
  // ClientBundleWithLookup types.
  String typeName = typeBinding.getQualifiedName();
  if (typeName.equals(ClientBundleUtilities.CLIENT_BUNDLE_TYPE_NAME)
      || typeName.equals(ClientBundleUtilities.CLIENT_BUNDLE_WITH_LOOKUP_TYPE_NAME)) {
    return false;
  }

  // Passed all tests, so validate
  return true;
}
 
Example #13
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void removeAdditionalMethodsFromSourceClass() {
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
		ListRewrite sourceClassBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		sourceClassBodyRewrite.remove(methodDeclaration, null);
		try {
			TextEdit sourceEdit = sourceRewriter.rewriteAST();
			sourceMultiTextEdit.addChild(sourceEdit);
			sourceCompilationUnitChange.addTextEditGroup(new TextEditGroup("Remove additional moved method", new TextEdit[] {sourceEdit}));
		}
		catch(JavaModelException javaModelException) {
			javaModelException.printStackTrace();
		}
	}
}
 
Example #14
Source File: StagedBuilderCreationWithMethodAdder.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType,
        StagedBuilderProperties currentStage) {
    AST ast = modificationDomain.getAst();
    ListRewrite listRewrite = modificationDomain.getListRewrite();
    BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0);

    StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage);
    MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage);
    staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));

    String parameterName = firstField.getBuilderFieldName();
    String withMethodName = staticWithMethod.getName().toString();
    Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName);

    javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod);

    staticWithMethod.setBody(block);

    listRewrite.insertLast(staticWithMethod, null);
}
 
Example #15
Source File: UiBinderJavaProblem.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static UiBinderJavaProblem createPrivateUiBinderSubtype(
    TypeDeclaration uiBinderSubtypeDecl, Modifier privateModifier) {
  return create(privateModifier,
      UiBinderJavaProblemType.PRIVATE_UI_BINDER_SUBTYPE,
      new String[] {uiBinderSubtypeDecl.getName().getIdentifier()},
      NO_STRINGS);
}
 
Example #16
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void setSuperType(TypeDeclaration declaration) {
      ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
ITypeBinding binding= classInstanceCreation.resolveTypeBinding();
      if (binding == null)
          return;
Type newType= (Type) ASTNode.copySubtree(fAnonymousInnerClassNode.getAST(), classInstanceCreation.getType());
if (binding.getSuperclass().getQualifiedName().equals("java.lang.Object")) { //$NON-NLS-1$
          Assert.isTrue(binding.getInterfaces().length <= 1);
          if (binding.getInterfaces().length == 0)
              return;
          declaration.superInterfaceTypes().add(0, newType);
      } else {
          declaration.setSuperclassType(newType);
      }
  }
 
Example #17
Source File: BuilderOwnerClassFinder.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public CompilationUnitModificationDomain provideBuilderOwnerClass(CompilationUnit compilationUnit, AST ast, ASTRewrite rewriter, ICompilationUnit iCompilationUnit) {
    TypeDeclaration builderType = getBuilderOwnerType(compilationUnit, iCompilationUnit);

    ListRewrite listRewrite = rewriter.getListRewrite(builderType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);

    return CompilationUnitModificationDomain.builder()
            .withAst(ast)
            .withAstRewriter(rewriter)
            .withListRewrite(listRewrite)
            .withOriginalType(builderType)
            .withCompilationUnit(compilationUnit)
            .build();
}
 
Example #18
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary constructors for the extracted supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param superType
 *            the super type, or <code>null</code> if no super type (ie.
 *            <code>java.lang.Object</code>) is available
 * @param targetDeclaration
 *            the type declaration of the target type
 * @param status
 *            the refactoring status
 */
protected final void createNecessaryConstructors(final CompilationUnitRewrite targetRewrite, final IType superType, final AbstractTypeDeclaration targetDeclaration, final RefactoringStatus status) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(targetDeclaration);
	if (superType != null) {
		final ITypeBinding binding= targetDeclaration.resolveBinding();
		if (binding != null && binding.isClass()) {
			final IMethodBinding[] bindings= StubUtility2.getVisibleConstructors(binding, true, true);
			int deprecationCount= 0;
			for (int i= 0; i < bindings.length; i++) {
				if (bindings[i].isDeprecated())
					deprecationCount++;
			}
			final ListRewrite rewrite= targetRewrite.getASTRewrite().getListRewrite(targetDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
			if (rewrite != null) {
				boolean createDeprecated= deprecationCount == bindings.length;
				for (int i= 0; i < bindings.length; i++) {
					IMethodBinding curr= bindings[i];
					if (!curr.isDeprecated() || createDeprecated) {
						MethodDeclaration stub;
						try {
							ImportRewriteContext context= new ContextSensitiveImportRewriteContext(targetDeclaration, targetRewrite.getImportRewrite());
							stub= StubUtility2.createConstructorStub(targetRewrite.getCu(), targetRewrite.getASTRewrite(), targetRewrite.getImportRewrite(), context, curr, binding.getName(),
									Modifier.PUBLIC, false, false, fSettings);
							if (stub != null)
								rewrite.insertLast(stub, null);
						} catch (CoreException exception) {
							JavaPlugin.log(exception);
							status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
						}
					}
				}
			}
		}
	}
}
 
Example #19
Source File: JavadocLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private boolean isSquashRequired(TagElement node, ASTNode declaration) {
	if (declaration instanceof TypeDeclaration) {
		String tagName = node.getTagName();
		return (!node.isNested() && tagName != null && tagName.startsWith("@"));
	}
	return PARAM_TAGS.contains(node.getTagName());
}
 
Example #20
Source File: FieldModifierResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    FieldDeclaration field = getFieldDeclaration(type, bug.getPrimaryField());

    Modifier finalModifier = workingUnit.getAST().newModifier(getModifierToAdd());

    ListRewrite modRewrite = rewrite.getListRewrite(field, FieldDeclaration.MODIFIERS2_PROPERTY);
    modRewrite.insertLast(finalModifier, null);
}
 
Example #21
Source File: SuperClassSetterFieldCollector.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private List<SuperSetterBasedBuilderField> findParametersWithSettersInType(TypeDeclaration parentTypeDeclaration) {
    return ((List<BodyDeclaration>) parentTypeDeclaration.bodyDeclarations())
            .stream()
            .filter(declaration -> isMethod(declaration))
            .map(declaration -> (MethodDeclaration) declaration)
            .filter(method -> isSetter(method))
            .map(method -> createBuilderField(method))
            .collect(Collectors.toList());
}
 
Example #22
Source File: MoveMethodRefactoringDescriptor.java    From JDeodorant with MIT License 5 votes vote down vote up
public MoveMethodRefactoringDescriptor(String project, String description, String comment,
		CompilationUnit sourceCompilationUnit, CompilationUnit targetCompilationUnit, 
		TypeDeclaration sourceTypeDeclaration, TypeDeclaration targetTypeDeclaration, MethodDeclaration sourceMethod,
		Map<MethodInvocation, MethodDeclaration> additionalMethodsToBeMoved, boolean leaveDelegate, String movedMethodName) {
	super(REFACTORING_ID, project, description, comment, RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE);
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.targetCompilationUnit = targetCompilationUnit;
	this.sourceTypeDeclaration = sourceTypeDeclaration;
	this.targetTypeDeclaration = targetTypeDeclaration;
	this.sourceMethod = sourceMethod;
	this.additionalMethodsToBeMoved = additionalMethodsToBeMoved;
	this.leaveDelegate = leaveDelegate;
	this.movedMethodName = movedMethodName;
}
 
Example #23
Source File: TypenameScopeExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(TypeDeclaration node) {
	if (topClass == null) {
		topClass = node;
	}
	types.put(topClass, node.getName().getIdentifier());
	return super.visit(node);
}
 
Example #24
Source File: JavaMethodDeclarationBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final TypeDeclaration node) {
	if (className.isEmpty()) {
		className.push(currentPackageName + "."
				+ node.getName().getIdentifier());
	} else {
		className.push(className.peek() + "."
				+ node.getName().getIdentifier());
	}
	return super.visit(node);
}
 
Example #25
Source File: BuilderFieldAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private int findLastFieldIndex(TypeDeclaration newType) {
    return ((List<BodyDeclaration>) newType.bodyDeclarations())
            .stream()
            .filter(element -> element instanceof FieldDeclaration)
            .collect(Collectors.toList())
            .size();
}
 
Example #26
Source File: Testq12.java    From compiler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preVisit2(ASTNode node) {
	if (node instanceof EnumDeclaration
			|| node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface())
		return false;
	if (node instanceof TypeDeclaration || node instanceof AnonymousClassDeclaration) {
		methodsStack.push(methods2);
		methods2 = 0;
	}
	return true;
}
 
Example #27
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final FieldDeclaration it) {
  Javadoc _javadoc = it.getJavadoc();
  boolean _tripleNotEquals = (_javadoc != null);
  if (_tripleNotEquals) {
    it.getJavadoc().accept(this);
  }
  final Consumer<VariableDeclarationFragment> _function = (VariableDeclarationFragment frag) -> {
    this.appendModifiers(it, it.modifiers());
    boolean _isPackageVisibility = this._aSTFlattenerUtils.isPackageVisibility(Iterables.<Modifier>filter(it.modifiers(), Modifier.class));
    if (_isPackageVisibility) {
      ASTNode _parent = it.getParent();
      if ((_parent instanceof TypeDeclaration)) {
        ASTNode _parent_1 = it.getParent();
        boolean _isInterface = ((TypeDeclaration) _parent_1).isInterface();
        boolean _not = (!_isInterface);
        if (_not) {
          this.appendToBuffer("package ");
        }
      }
    }
    it.getType().accept(this);
    this.appendExtraDimensions(frag.getExtraDimensions());
    this.appendSpaceToBuffer();
    frag.accept(this);
  };
  it.fragments().forEach(_function);
  return false;
}
 
Example #28
Source File: PrivateConstructorBodyCreationFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public Block createBody(AST ast, TypeDeclaration builderType, List<BuilderField> builderFields) {
    Block body = ast.newBlock();
    String builderName = typeDeclarationToVariableNameConverter.convert(builderType);

    populateBodyWithSuperConstructorCall(ast, builderType, body, getFieldsOfClass(builderFields, ConstructorParameterSetterBuilderField.class));
    fieldSetterAdderFragment.populateBodyWithFieldSetCalls(ast, builderName, body,
            getFieldsOfClass(builderFields, ClassFieldSetterBuilderField.class));
    superFieldSetterMethodAdderFragment.populateBodyWithSuperSetterCalls(ast, builderName, body, getFieldsOfClass(builderFields, SuperSetterBasedBuilderField.class));

    return body;
}
 
Example #29
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new type signature of a subtype.
 *
 * @param subRewrite
 *            the compilation unit rewrite of a subtype
 * @param declaration
 *            the type declaration of a subtype
 * @param extractedType
 *            the extracted super type
 * @param extractedBinding
 *            the binding of the extracted super type
 * @param monitor
 *            the progress monitor to use
 * @throws JavaModelException
 *             if the type parameters cannot be retrieved
 */
protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaModelException {
	Assert.isNotNull(subRewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(extractedType);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10);
		final AST ast= subRewrite.getAST();
		Type type= null;
		if (extractedBinding != null) {
			type= subRewrite.getImportRewrite().addImport(extractedBinding, ast);
		} else {
			subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.'));
			type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName()));
		}
		subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.'));
		if (type != null) {
			final ITypeParameter[] parameters= extractedType.getTypeParameters();
			if (parameters.length > 0) {
				final ParameterizedType parameterized= ast.newParameterizedType(type);
				for (int index= 0; index < parameters.length; index++)
					parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
				type= parameterized;
			}
		}
		final ASTRewrite rewriter= subRewrite.getASTRewrite();
		if (type != null && declaration instanceof TypeDeclaration) {
			final TypeDeclaration extended= (TypeDeclaration) declaration;
			final Type superClass= extended.getSuperclassType();
			if (superClass != null) {
				rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
				subRewrite.getImportRemover().registerRemovedNode(superClass);
			} else
				rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
		}
	} finally {
		monitor.done();
	}
}
 
Example #30
Source File: BuilderAstRemover.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void removeBuilder(ASTRewrite rewriter, CompilationUnit compilationUnit) {
    List<TypeDeclaration> types = ((List<AbstractTypeDeclaration>) compilationUnit.types())
            .stream()
            .filter(abstractTypeDeclaration -> abstractTypeDeclaration instanceof TypeDeclaration)
            .map(abstractTypeDeclaration -> (TypeDeclaration) abstractTypeDeclaration)
            .collect(Collectors.toList());
    if (types.size() == 1) {
        builderRemovers.stream()
                .forEach(remover -> remover.remove(rewriter, types.get(0)));
    }
}