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

The following examples show how to use org.eclipse.jdt.core.dom.AbstractTypeDeclaration. 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: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected final void adjustTypeVisibility(final ITypeBinding binding) throws JavaModelException {
	Assert.isNotNull(binding);
	final IJavaElement element= binding.getJavaElement();
	if (element instanceof IType) {
		final IType type= (IType) element;
		if (!type.isBinary() && !type.isReadOnly() && !Flags.isPublic(type.getFlags())) {
			boolean same= false;
			final CompilationUnitRewrite rewrite= getCompilationUnitRewrite(fRewrites, type.getCompilationUnit());
			final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, rewrite.getRoot());
			if (declaration != null) {
				final ITypeBinding declaring= declaration.resolveBinding();
				if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
					same= true;
				final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
				final String modifier= same ? RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default : RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
				if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue()) && MemberVisibilityAdjustor.needsVisibilityAdjustments(type, keyword, fAdjustments))
					fAdjustments.put(type, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(type, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(type.getCompilationUnit(), declaration))));
			}
		}
	}
}
 
Example #2
Source File: JavaFileParser.java    From buck with Apache License 2.0 6 votes vote down vote up
@Nullable
private String getFullyQualifiedTypeName(AbstractTypeDeclaration node) {
  LinkedList<String> nameParts = new LinkedList<>();
  nameParts.add(node.getName().toString());
  ASTNode parent = node.getParent();
  while (!(parent instanceof CompilationUnit)) {
    if (parent instanceof AbstractTypeDeclaration) {
      nameParts.addFirst(((AbstractTypeDeclaration) parent).getName().toString());
      parent = parent.getParent();
    } else if (parent instanceof AnonymousClassDeclaration) {
      // If this is defined in an anonymous class, then there is no meaningful fully qualified
      // name.
      return null;
    } else {
      throw new RuntimeException("Unexpected parent " + parent + " for " + node);
    }
  }

  // A Java file might not have a package. Hopefully all of ours do though...
  PackageDeclaration packageDecl = ((CompilationUnit) parent).getPackage();
  if (packageDecl != null) {
    nameParts.addFirst(packageDecl.getName().toString());
  }

  return Joiner.on(".").join(nameParts);
}
 
Example #3
Source File: TypeDiff.java    From apidiff with MIT License 6 votes vote down vote up
private Boolean processExtractSuperType(final AbstractTypeDeclaration type){
	List<SDRefactoring> listRenames = new ArrayList<SDRefactoring>();
	
	if(this.refactorings.containsKey(RefactoringType.EXTRACT_SUPERCLASS)){
		listRenames.addAll(this.refactorings.get(RefactoringType.EXTRACT_SUPERCLASS));
	}
	if(this.refactorings.containsKey(RefactoringType.EXTRACT_INTERFACE)){
		listRenames.addAll(this.refactorings.get(RefactoringType.EXTRACT_INTERFACE));
	}
	
	if(listRenames != null){
		for(SDRefactoring ref : listRenames){
			if(UtilTools.getPath(type).equals(ref.getEntityBefore().fullName())){
				this.typesWithPathChanged.add(ref.getEntityAfter().fullName());
				this.addChange(type, Category.TYPE_EXTRACT_SUPERTYPE, false, ""); //TODO: create description
				return true;
			}
		}
	}
	return false;
}
 
Example #4
Source File: AddUnimplementedConstructorsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new add unimplemented constructors operation.
 *
 * @param astRoot the compilation unit AST node
 * @param type the type to add the methods to
 * @param constructorsToImplement the method binding keys to implement
 * @param insertPos the insertion point, or <code>-1</code>
 * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
	if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
		throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
	}
	if (type == null) {
		throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
	}
	ASTNode node= astRoot.findDeclaringNode(type);
	if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
		throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
	}

	fType= type;
	fInsertPos= insertPos;
	fASTRoot= astRoot;
	fConstructorsToImplement= constructorsToImplement;
	fSave= save;
	fApply= apply;
	fImports= imports;

	fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
	fVisibility= Modifier.PUBLIC;
	fOmitSuper= false;
}
 
Example #5
Source File: CPlusPlusTranslator.java    From juniversal with MIT License 6 votes vote down vote up
@Override
public String translateNode(SourceFile sourceFile, ASTNode astNode) {
    try (StringWriter writer = new StringWriter()) {
        CPlusPlusSourceFileWriter cPlusPlusSourceFileWriter = new CPlusPlusSourceFileWriter(this, sourceFile, writer,
                OutputType.SOURCE);

        // Set the type declaration part of the context
        AbstractTypeDeclaration typeDeclaration = (AbstractTypeDeclaration) sourceFile.getCompilationUnit().types().get(0);
        cPlusPlusSourceFileWriter.getContext().setTypeDeclaration(typeDeclaration);

        cPlusPlusSourceFileWriter.writeRootNode(astNode);

        return writer.getBuffer().toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addEnclosingInstanceTypeParameters(final ITypeBinding[] parameters, final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) {
	Assert.isNotNull(parameters);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	if (declaration instanceof TypeDeclaration) {
		final TypeDeclaration type= (TypeDeclaration) declaration;
		final List<TypeParameter> existing= type.typeParameters();
		final Set<String> names= new HashSet<String>();
		TypeParameter parameter= null;
		for (final Iterator<TypeParameter> iterator= existing.iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			names.add(parameter.getName().getIdentifier());
		}
		final ListRewrite rewriter= rewrite.getListRewrite(type, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		String name= null;
		for (int index= 0; index < parameters.length; index++) {
			name= parameters[index].getName();
			if (!names.contains(name)) {
				parameter= type.getAST().newTypeParameter();
				parameter.setName(type.getAST().newSimpleName(name));
				rewriter.insertLast(parameter, null);
			}
		}
	}
}
 
Example #7
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static AbstractTypeDeclaration getSelectedTypeDeclaration(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 AbstractTypeDeclaration)) {
		node = node.getParent();
	}

	return (AbstractTypeDeclaration) node;
}
 
Example #8
Source File: CorrectMainTypeNameProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= fContext.getASTRoot();

	AST ast= astRoot.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);

	AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName);
	if (decl != null) {
		ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName());
		for (int i= 0; i < sameNodes.length; i++) {
			rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null);
		}
	}
	return rewrite;
}
 
Example #9
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static IType getSelectionType(IInvocationContext context) {
	ICompilationUnit unit = context.getCompilationUnit();
	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	ITypeBinding typeBinding = null;
	while (node != null && !(node instanceof CompilationUnit)) {
		if (node instanceof AbstractTypeDeclaration) {
			typeBinding = ((AbstractTypeDeclaration) node).resolveBinding();
			break;
		} else if (node instanceof AnonymousClassDeclaration) { // Anonymous
			typeBinding = ((AnonymousClassDeclaration) node).resolveBinding();
			break;
		}

		node = node.getParent();
	}

	if (typeBinding != null && typeBinding.getJavaElement() instanceof IType) {
		return (IType) typeBinding.getJavaElement();
	}

	return unit.findPrimaryType();
}
 
Example #10
Source File: JavaTextSelection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean resolveInClassInitializer() {
	if (fInClassInitializerRequested)
		return fInClassInitializer;
	fInClassInitializerRequested= true;
	resolveSelectedNodes();
	ASTNode node= getStartNode();
	if (node == null) {
		fInClassInitializer= true;
	} else {
		while (node != null) {
			int nodeType= node.getNodeType();
			if (node instanceof AbstractTypeDeclaration) {
				fInClassInitializer= false;
				break;
			} else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
				fInClassInitializer= false;
				break;
			} else if (nodeType == ASTNode.INITIALIZER) {
				fInClassInitializer= true;
				break;
			}
			node= node.getParent();
		}
	}
	return fInClassInitializer;
}
 
Example #11
Source File: ExtractMethodInputPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String getLabel(ASTNode node) {
	if (node instanceof AbstractTypeDeclaration) {
		return ((AbstractTypeDeclaration)node).getName().getIdentifier();
	} else if (node instanceof AnonymousClassDeclaration) {
		if (node.getLocationInParent() == ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY) {
			ClassInstanceCreation creation= (ClassInstanceCreation)node.getParent();
			return Messages.format(
				RefactoringMessages.ExtractMethodInputPage_anonymous_type_label,
				BasicElementLabels.getJavaElementName(ASTNodes.asString(creation.getType())));
		} else if (node.getLocationInParent() == EnumConstantDeclaration.ANONYMOUS_CLASS_DECLARATION_PROPERTY) {
			EnumConstantDeclaration decl= (EnumConstantDeclaration)node.getParent();
			return decl.getName().getIdentifier();
		}
	}
	return "UNKNOWN"; //$NON-NLS-1$
}
 
Example #12
Source File: UnimplementedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ASTNode getSelectedTypeNode(CompilationUnit root, IProblemLocation problem) {
	ASTNode selectedNode= problem.getCoveringNode(root);
	if (selectedNode == null)
		return null;

	if (selectedNode.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION) { // bug 200016
		selectedNode= selectedNode.getParent();
	}

	if (selectedNode.getLocationInParent() == EnumConstantDeclaration.NAME_PROPERTY) {
		selectedNode= selectedNode.getParent();
	}
	if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent() instanceof AbstractTypeDeclaration) {
		return selectedNode.getParent();
	} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
		return ((ClassInstanceCreation) selectedNode).getAnonymousClassDeclaration();
	} else if (selectedNode.getNodeType() == ASTNode.ENUM_CONSTANT_DECLARATION) {
		EnumConstantDeclaration enumConst= (EnumConstantDeclaration) selectedNode;
		if (enumConst.getAnonymousClassDeclaration() != null)
			return enumConst.getAnonymousClassDeclaration();
		return enumConst;
	} else {
		return null;
	}
}
 
Example #13
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String getCatchBodyContent(ICompilationUnit cu, String exceptionType, String variableName, ASTNode locationInAST, String lineDelimiter) throws CoreException {
	String enclosingType= ""; //$NON-NLS-1$
	String enclosingMethod= ""; //$NON-NLS-1$

	if (locationInAST != null) {
		MethodDeclaration parentMethod= ASTResolving.findParentMethodDeclaration(locationInAST);
		if (parentMethod != null) {
			enclosingMethod= parentMethod.getName().getIdentifier();
			locationInAST= parentMethod;
		}
		ASTNode parentType= ASTResolving.findParentType(locationInAST);
		if (parentType instanceof AbstractTypeDeclaration) {
			enclosingType= ((AbstractTypeDeclaration)parentType).getName().getIdentifier();
		}
	}
	return getCatchBodyContent(cu, exceptionType, variableName, enclosingType, enclosingMethod, lineDelimiter);
}
 
Example #14
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addMethodStubForAbstractMethod(final IMethod sourceMethod, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration typeToCreateStubIn, final ICompilationUnit newCu, final CompilationUnitRewrite rewriter, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
	final MethodDeclaration methodToCreateStubFor= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
	final AST ast= rewriter.getRoot().getAST();
	final MethodDeclaration newMethod= ast.newMethodDeclaration();
	newMethod.setBody(createMethodStub(methodToCreateStubFor, ast));
	newMethod.setConstructor(false);
	copyExtraDimensions(methodToCreateStubFor, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status)));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName())));
	final TypeVariableMaplet[] mapping= TypeVariableUtil.composeMappings(TypeVariableUtil.subTypeToSuperType(getDeclaringType(), getDestinationType()), TypeVariableUtil.superTypeToInheritedType(getDestinationType(), ((IType) typeToCreateStubIn.resolveBinding().getJavaElement())));
	copyReturnType(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping);
	copyParameters(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping);
	copyThrownExceptions(methodToCreateStubFor, newMethod);
	newMethod.setJavadoc(createJavadocForStub(typeToCreateStubIn.getName().getIdentifier(), methodToCreateStubFor, newMethod, newCu, rewriter.getASTRewrite()));
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(typeToCreateStubIn, rewriter.getImportRewrite());
	ImportRewriteUtil.addImports(rewriter, context, newMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false);
	rewriter.getASTRewrite().getListRewrite(typeToCreateStubIn, typeToCreateStubIn.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, typeToCreateStubIn.bodyDeclarations()), rewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_method_stub, SET_PULL_UP));
}
 
Example #15
Source File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the declaration node for the originally selected node.
 * @param name the name of the node
 *
 * @return the declaration node
 */
private static ASTNode getDeclarationNode(SimpleName name) {
	ASTNode parent= name.getParent();
	if (!(parent instanceof AbstractTypeDeclaration)) {

		parent= parent.getParent();
		if (parent instanceof ParameterizedType || parent instanceof Type)
			parent= parent.getParent();
		if (parent instanceof ClassInstanceCreation) {

			final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
			parent= creation.getAnonymousClassDeclaration();
		}
	}
	return parent;
}
 
Example #16
Source File: CSharpTranslator.java    From juniversal with MIT License 6 votes vote down vote up
@Override public void translateFile(SourceFile sourceFile) {
    CompilationUnit compilationUnit = sourceFile.getCompilationUnit();
    AbstractTypeDeclaration mainTypeDeclaration = (AbstractTypeDeclaration) compilationUnit.types().get(0);

    String typeName = mainTypeDeclaration.getName().getIdentifier();
    String fileName = typeName + ".cs";

    File file = new File(getPackageDirectory(mainTypeDeclaration), fileName);
    try (FileWriter writer = new FileWriter(file)) {
        CSharpSourceFileWriter cSharpSourceFileWriter = new CSharpSourceFileWriter(this, sourceFile, writer);

        cSharpSourceFileWriter.writeRootNode(compilationUnit);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<CommentObject> processComments(IFile iFile, IDocument iDocument,
		AbstractTypeDeclaration typeDeclaration, List<Comment> comments) {
	List<CommentObject> commentList = new ArrayList<CommentObject>();
	int typeDeclarationStartPosition = typeDeclaration.getStartPosition();
	int typeDeclarationEndPosition = typeDeclarationStartPosition + typeDeclaration.getLength();
	for(Comment comment : comments) {
		int commentStartPosition = comment.getStartPosition();
		int commentEndPosition = commentStartPosition + comment.getLength();
		int commentStartLine = 0;
		int commentEndLine = 0;
		String text = null;
		try {
			commentStartLine = iDocument.getLineOfOffset(commentStartPosition);
			commentEndLine = iDocument.getLineOfOffset(commentEndPosition);
			text = iDocument.get(commentStartPosition, comment.getLength());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		CommentType type = null;
		if(comment.isLineComment()) {
			type = CommentType.LINE;
		}
		else if(comment.isBlockComment()) {
			type = CommentType.BLOCK;
		}
		else if(comment.isDocComment()) {
			type = CommentType.JAVADOC;
		}
		CommentObject commentObject = new CommentObject(text, type, commentStartLine, commentEndLine);
		commentObject.setComment(comment);
		String fileExtension = iFile.getFileExtension() != null ? "." + iFile.getFileExtension() : "";
		if(typeDeclarationStartPosition <= commentStartPosition && typeDeclarationEndPosition >= commentEndPosition) {
			commentList.add(commentObject);
		}
		else if(iFile.getName().equals(typeDeclaration.getName().getIdentifier() + fileExtension)) {
			commentList.add(commentObject);
		}
	}
	return commentList;
}
 
Example #18
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static MethodDeclaration[] getAllConstructors(AbstractTypeDeclaration typeDeclaration) {
	if (typeDeclaration instanceof TypeDeclaration) {
		MethodDeclaration[] allMethods = ((TypeDeclaration) typeDeclaration).getMethods();
		List<MethodDeclaration> result = new ArrayList<>(Math.min(allMethods.length, 1));
		for (int i = 0; i < allMethods.length; i++) {
			MethodDeclaration declaration = allMethods[i];
			if (declaration.isConstructor()) {
				result.add(declaration);
			}
		}
		return result.toArray(new MethodDeclaration[result.size()]);
	}
	return new MethodDeclaration[] {};
}
 
Example #19
Source File: DelegateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ChildListPropertyDescriptor getTypeBodyDeclarationsProperty() {
	ASTNode parent= fDeclaration.getParent();

	if (parent instanceof AbstractTypeDeclaration)
		return ((AbstractTypeDeclaration) parent).getBodyDeclarationsProperty();
	else if (parent instanceof AnonymousClassDeclaration)
		return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;

	Assert.isTrue(false);
	return null;
}
 
Example #20
Source File: BuilderOwnerClassFinder.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private TypeDeclaration getFirstType(CompilationUnit compilationUnit) {
    return ((List<AbstractTypeDeclaration>) compilationUnit.types())
            .stream()
            .filter(abstractTypeDeclaration -> abstractTypeDeclaration instanceof TypeDeclaration)
            .map(abstractTypeDeclaration -> (TypeDeclaration) abstractTypeDeclaration)
            .findFirst()
            .orElseThrow(() -> new PluginException("No types are present in the current java file"));
}
 
Example #21
Source File: SwiftTranslator.java    From juniversal with MIT License 5 votes vote down vote up
@Override public String translateNode(SourceFile sourceFile, ASTNode astNode) {
    try (StringWriter writer = new StringWriter()) {
        SwiftSourceFileWriter swiftSourceFileWriter = new SwiftSourceFileWriter(this, sourceFile, writer);

        // Set the type declaration part of the context
        AbstractTypeDeclaration typeDeclaration = (AbstractTypeDeclaration) sourceFile.getCompilationUnit().types().get(0);
        swiftSourceFileWriter.getContext().setTypeDeclaration(typeDeclaration);

        swiftSourceFileWriter.writeRootNode(astNode);

        return writer.getBuffer().toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static AbstractTypeDeclaration findTypeDeclaration(IType type, CompilationUnit unit) {
	final List<IType> types= getDeclaringTypes(type);
	types.add(type);
	AbstractTypeDeclaration[] declarations= (AbstractTypeDeclaration[]) unit.types().toArray(new AbstractTypeDeclaration[unit.types().size()]);
	AbstractTypeDeclaration declaration= null;
	for (final Iterator<IType> iterator= types.iterator(); iterator.hasNext();) {
		IType enclosing= iterator.next();
		declaration= findTypeDeclaration(enclosing, declarations);
		Assert.isNotNull(declaration);
		declarations= getAbstractTypeDeclarations(declaration);
	}
	Assert.isNotNull(declaration);
	return declaration;
}
 
Example #23
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private void convertAndAddType(
    AbstractTypeDeclaration typeDeclaration, Function<Type, Void> typeProcessor) {
  convertAndAddType(
      typeDeclaration.resolveBinding(),
      JdtUtils.asTypedList(typeDeclaration.bodyDeclarations()),
      typeDeclaration.getName(),
      typeProcessor);
}
 
Example #24
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final void createMemberDeclarations(final CompilationUnitRewrite sourceRewrite, final ASTRewrite targetRewrite, final AbstractTypeDeclaration targetDeclaration) throws CoreException {
	Assert.isNotNull(sourceRewrite);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(targetDeclaration);
	Arrays.sort(fMembers, new Comparator<IMember>() {

		public final int compare(final IMember first, final IMember second) {
			try {
				return first.getSourceRange().getOffset() - second.getSourceRange().getOffset();
			} catch (JavaModelException exception) {
				return first.hashCode() - second.hashCode();
			}
		}
	});
	fTypeBindings.clear();
	fStaticBindings.clear();
	if (fMembers.length > 0) {
		IMember member= null;
		for (int index= fMembers.length - 1; index >= 0; index--) {
			member= fMembers[index];
			if (member instanceof IField) {
				createFieldDeclaration(sourceRewrite, targetRewrite, targetDeclaration, ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, sourceRewrite.getRoot()));
			} else if (member instanceof IMethod) {
				createMethodDeclaration(sourceRewrite, targetRewrite, targetDeclaration, ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) member, sourceRewrite.getRoot()));
			}
		}
	}
}
 
Example #25
Source File: LocalTypeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean visitType(AbstractTypeDeclaration node) {
	int mode= fSelection.getVisitSelectionMode(node);
	switch (mode) {
		case Selection.BEFORE:
			fTypeDeclarationsBefore.add(node);
			break;
		case Selection.SELECTED:
			fTypeDeclarationsSelected.add(node);
			break;
	}
	return true;
}
 
Example #26
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private BodyDeclaration createNewTypeDeclarationNode(final IType type, final AbstractTypeDeclaration oldType, final CompilationUnit declaringCuNode, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite) throws JavaModelException {
	final ICompilationUnit declaringCu= getDeclaringType().getCompilationUnit();
	if (!JdtFlags.isPublic(type) && !JdtFlags.isProtected(type)) {
		if (mapping.length > 0)
			return createPlaceholderForTypeDeclaration(oldType, declaringCu, mapping, rewrite, true);

		return createPlaceholderForProtectedTypeDeclaration(oldType, declaringCuNode, declaringCu, rewrite, true);
	}
	if (mapping.length > 0)
		return createPlaceholderForTypeDeclaration(oldType, declaringCu, mapping, rewrite, true);

	return createPlaceholderForTypeDeclaration(oldType, declaringCu, rewrite, true);
}
 
Example #27
Source File: JavaTextSelection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean resolveInVariableInitializer() {
	if (fInVariableInitializerRequested)
		return fInVariableInitializer;
	fInVariableInitializerRequested= true;
	resolveSelectedNodes();
	ASTNode node= getStartNode();
	ASTNode last= null;
	while (node != null) {
		int nodeType= node.getNodeType();
		if (node instanceof AbstractTypeDeclaration) {
			fInVariableInitializer= false;
			break;
		} else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
			fInVariableInitializer= false;
			break;
		} else if (nodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT &&
				   ((VariableDeclarationFragment)node).getInitializer() == last) {
			fInVariableInitializer= true;
			break;
		} else if (nodeType == ASTNode.SINGLE_VARIABLE_DECLARATION &&
			       ((SingleVariableDeclaration)node).getInitializer() == last) {
			fInVariableInitializer= true;
			break;
		} else if (nodeType == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION &&
			       ((AnnotationTypeMemberDeclaration)node).getDefault() == last) {
			fInVariableInitializer= true;
			break;
		}
		last= node;
		node= node.getParent();
	}
	return fInVariableInitializer;
}
 
Example #28
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the type parameters of the new supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param subType
 *            the subtype
 * @param sourceDeclaration
 *            the type declaration of the source type
 * @param targetDeclaration
 *            the type declaration of the target type
 */
protected final void createTypeParameters(final ASTRewrite targetRewrite, final IType subType, final AbstractTypeDeclaration sourceDeclaration, final AbstractTypeDeclaration targetDeclaration) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(sourceDeclaration);
	Assert.isNotNull(targetDeclaration);
	if (sourceDeclaration instanceof TypeDeclaration) {
		TypeParameter parameter= null;
		final ListRewrite rewrite= targetRewrite.getListRewrite(targetDeclaration, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		for (final Iterator<TypeParameter> iterator= ((TypeDeclaration) sourceDeclaration).typeParameters().iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			rewrite.insertLast(ASTNode.copySubtree(targetRewrite.getAST(), parameter), null);
			ImportRewriteUtil.collectImports(subType.getJavaProject(), sourceDeclaration, fTypeBindings, fStaticBindings, false);
		}
	}
}
 
Example #29
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ChildListPropertyDescriptor getBodyDeclarationsProperty(ASTNode declaration) {
	if (declaration instanceof AnonymousClassDeclaration) {
		return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
	} else if (declaration instanceof AbstractTypeDeclaration) {
		return ((AbstractTypeDeclaration) declaration).getBodyDeclarationsProperty();
	}
	Assert.isTrue(false);
	return null;
}
 
Example #30
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void endVisit(final SimpleName node) {
	final ASTNode parent= node.getParent();
	if (!(parent instanceof ImportDeclaration) && !(parent instanceof PackageDeclaration) && !(parent instanceof AbstractTypeDeclaration)) {
		final IBinding binding= node.resolveBinding();
		if (binding instanceof IVariableBinding && !(parent instanceof MethodDeclaration))
			endVisit((IVariableBinding) binding, null, node);
		else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
			endVisit((ITypeBinding) binding, node);
	}
}