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 Project: eclipse.jdt.ls   Author: eclipse   File: RefactorProposalUtility.java    License: 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 #2
Source Project: JDeodorant   Author: tsantalis   File: TypeCheckingEvolution.java    License: 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 Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: 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 Project: apidiff   Author: aserg-ufmg   File: FieldDiff.java    License: 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 #5
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: 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 #6
Source Project: apidiff   Author: aserg-ufmg   File: MethodDiff.java    License: 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 #7
Source Project: apidiff   Author: aserg-ufmg   File: MethodDiff.java    License: 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 #8
Source Project: txtUML   Author: ELTE-Soft   File: ClassDiagramExporter.java    License: 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 #9
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: CreateSyncMethodProposal.java    License: 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 #10
Source Project: juniversal   Author: juniversal   File: SwiftTranslator.java    License: 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 #11
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: ClientBundleValidator.java    License: 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 #12
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoring.java    License: 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 #13
Source Project: SparkBuilderGenerator   Author: helospark   File: StagedBuilderCreationWithMethodAdder.java    License: 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 #14
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ModifierRewrite.java    License: 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 #15
Source Project: compiler   Author: boalang   File: TestQ16.java    License: 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 #16
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: UiBinderJavaProblem.java    License: 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 #17
Source Project: spring-javaformat   Author: spring-io   File: JavadocLineBreakPreparator.java    License: 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 #18
Source Project: xtext-xtend   Author: eclipse   File: JavaASTFlattener.java    License: 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 #19
Source Project: SparkBuilderGenerator   Author: helospark   File: TypeDeclarationFromSuperclassExtractor.java    License: MIT License 5 votes vote down vote up
private List<TypeDeclaration> getTypes(CompilationUnit iCompilationUnit) {
    return ((List<AbstractTypeDeclaration>) iCompilationUnit.types())
            .stream()
            .filter(abstractTypeDeclaration -> abstractTypeDeclaration instanceof TypeDeclaration)
            .map(abstractTypeDeclaration -> (TypeDeclaration) abstractTypeDeclaration)
            .collect(Collectors.toList());
}
 
Example #20
Source Project: JDeodorant   Author: tsantalis   File: MoveMethodRefactoringDescriptor.java    License: 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 #21
@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 #22
Source Project: eclipse.jdt.ls   Author: eclipse   File: JavadocTagsSubProcessor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	ASTRewrite rewrite= ASTRewrite.create(fBodyDecl.getAST());
	if (fBodyDecl instanceof MethodDeclaration) {
		insertAllMissingMethodTags(rewrite, (MethodDeclaration) fBodyDecl);
	} else {
		insertAllMissingTypeTags(rewrite, (TypeDeclaration) fBodyDecl);
	}
	return rewrite;
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodeFactory.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static TypeParameter newTypeParameter(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(TYPEPARAM_HEADER);
	buffer.append(content);
	buffer.append(TYPEPARAM_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	List<AbstractTypeDeclaration> list= root.types();
	TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
	MethodDeclaration methodDecl= typeDecl.getMethods()[0];
	TypeParameter tp= (TypeParameter) methodDecl.typeParameters().get(0);
	ASTNode result= ASTNode.copySubtree(ast, tp);
	result.accept(new PositionClearer());
	return (TypeParameter) result;
}
 
Example #24
Source Project: txtUML   Author: ELTE-Soft   File: ElementTypeTeller.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isBehavioralPort(TypeDeclaration typeDeclaration) {
	for (IAnnotationBinding annot : typeDeclaration.resolveBinding().getAnnotations()) {
		if (annot.getAnnotationType().getQualifiedName().equals(BehaviorPort.class.getCanonicalName())) {
			return true;
		}
	}
	return false;
}
 
Example #25
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: PasteAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static List<ParsedCu> parseCus(IJavaProject javaProject, String compilerCompliance, String text) {
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	if (javaProject != null) {
		parser.setProject(javaProject);
	} else if (compilerCompliance != null) {
		Map<String, String> options= JavaCore.getOptions();
		JavaModelUtil.setComplianceOptions(options, compilerCompliance);
		parser.setCompilerOptions(options);
	}
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	CompilationUnit unit= (CompilationUnit) parser.createAST(null);

	if (unit.types().size() > 0)
		return parseAsTypes(text, unit);

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
	ASTNode root= parser.createAST(null);
	if (root instanceof TypeDeclaration) {
		List<BodyDeclaration> bodyDeclarations= ((TypeDeclaration) root).bodyDeclarations();
		if (bodyDeclarations.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_CLASS_BODY_DECLARATIONS, null, null));
	}

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	root= parser.createAST(null);
	if (root instanceof Block) {
		List<Statement> statements= ((Block) root).statements();
		if (statements.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_STATEMENTS, null, null));
	}

	return Collections.emptyList();
}
 
Example #26
Source Project: JDeodorant   Author: tsantalis   File: TypeCheckCodeFragmentAnalyzer.java    License: MIT License 5 votes vote down vote up
public TypeCheckCodeFragmentAnalyzer(TypeCheckElimination typeCheckElimination,
		TypeDeclaration typeDeclaration, MethodDeclaration typeCheckMethod, IFile iFile) {
	this.typeCheckElimination = typeCheckElimination;
	this.typeDeclaration = typeDeclaration;
	this.typeCheckMethod = typeCheckMethod;
	this.fields = typeDeclaration.getFields();
	this.methods = typeDeclaration.getMethods();
	this.typeVariableCounterMap = new LinkedHashMap<SimpleName, Integer>();
	this.typeMethodInvocationCounterMap = new LinkedHashMap<MethodInvocation, Integer>();
	this.complexExpressionMap = new LinkedHashMap<Expression, IfStatementExpressionAnalyzer>();
	typeCheckElimination.setTypeCheckClass(typeDeclaration);
	typeCheckElimination.setTypeCheckMethod(typeCheckMethod);
	typeCheckElimination.setTypeCheckIFile(iFile);
	processTypeCheckCodeFragment();
}
 
Example #27
private static void addMakeTypeAbstractProposal(IInvocationContext context, TypeDeclaration parentTypeDecl, Collection<ICommandAccess> proposals) {
	MakeTypeAbstractOperation operation= new UnimplementedCodeFix.MakeTypeAbstractOperation(parentTypeDecl);

	String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_addabstract_description, BasicElementLabels.getJavaElementName(parentTypeDecl.getName().getIdentifier()));
	UnimplementedCodeFix fix= new UnimplementedCodeFix(label, context.getASTRoot(), new CompilationUnitRewriteOperation[] { operation });

	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	FixCorrectionProposal proposal= new FixCorrectionProposal(fix, null, IProposalRelevance.MAKE_TYPE_ABSTRACT_FIX, image, context);
	proposals.add(proposal);
}
 
Example #28
Source Project: SparkBuilderGenerator   Author: helospark   File: StagedBuilderInterfaceRemover.java    License: MIT License 5 votes vote down vote up
@Override
public void remove(ASTRewrite rewriter, TypeDeclaration mainType) {
    List<TypeDeclaration> nestedInterfaces = getNestedInterfaces(mainType);
    List<TypeDeclaration> interfacesWithGeneratedAnnotation = generatedAnnotationContainingBodyDeclarationFilter.filterAnnotatedClasses(nestedInterfaces);

    if (!interfacesWithGeneratedAnnotation.isEmpty()) {
        interfacesWithGeneratedAnnotation.stream()
                .forEach(interfaceToRemove -> rewriter.remove(interfaceToRemove, null));
    } else {
        fallbackFilterMatchingInterfaces(nestedInterfaces, mainType)
                .forEach(interfaceToRemove -> rewriter.remove(interfaceToRemove, null));
    }

}
 
Example #29
public TypeDeclaration createStageBuilderInterface(AST ast, String interfaceName) {
    TypeDeclaration addedInterface = ast.newTypeDeclaration();
    addedInterface.setInterface(true);
    addedInterface.setName(ast.newSimpleName(interfaceName));
    addedInterface.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    javadocAdder.addJavadocForStagedInterface(ast, interfaceName, addedInterface);
    return addedInterface;
}
 
Example #30
/**
 * 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();
	}
}