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

The following examples show how to use org.eclipse.jdt.core.dom.Type. 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-Postfix-Code-Completion   Author: trylimits   File: ReferenceFinderUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
	if (methodDeclaration == null)
		return new HashSet<ITypeBinding>(0);
	Set<ITypeBinding> result= new HashSet<ITypeBinding>();
	ITypeBinding binding= null;
	Type returnType= methodDeclaration.getReturnType2();
	if (returnType != null) {
		binding = returnType.resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
		binding = iter.next().getType().resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
		binding= iter.next().resolveBinding();
		if (binding != null)
			result.add(binding);
	}
	return result;
}
 
Example #2
Source Project: juniversal   Author: juniversal   File: CPlusPlusASTNodeWriter.java    License: MIT License 6 votes vote down vote up
/**
 * Write out a type, when it's used (as opposed to defined).
 *
 * @param type type to write
 */
public void writeType(Type type, boolean useRawPointer) {
    boolean referenceType = !type.isPrimitiveType();

    if (!referenceType)
        writeNode(type);
    else {
        if (useRawPointer) {
            writeNode(type);
            write("*");
        } else {
            write("ptr< ");
            writeNode(type);
            write(" >");
        }
    }
}
 
Example #3
Source Project: SimFix   Author: xgdsmileboy   File: NodeUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Type parsePreExprType(Expr expr, String operator){
	AST ast = AST.newAST(AST.JLS8);
	switch(operator){
	case "++":
	case "--":
		return ast.newPrimitiveType(PrimitiveType.INT);
	case "+":
	case "-":
		return expr.getType();
	case "~":
	case "!":
		return ast.newPrimitiveType(PrimitiveType.BOOLEAN);
	default :
		return null;
	}
}
 
Example #4
@Override
public final boolean visit(final QualifiedName node) {
	Assert.isNotNull(node);
	IBinding binding= node.resolveBinding();
	if (binding instanceof ITypeBinding) {
		final ITypeBinding type= (ITypeBinding) binding;
		if (type.isClass() && type.getDeclaringClass() != null) {
			final Type newType= fTargetRewrite.getImportRewrite().addImport(type, node.getAST());
			fRewrite.replace(node, newType, null);
			return false;
		}
	}
	binding= node.getQualifier().resolveBinding();
	if (Bindings.equals(fTarget, binding)) {
		fRewrite.replace(node, getFieldReference(node.getName(), fRewrite), null);
		return false;
	}
	node.getQualifier().accept(this);
	return false;
}
 
Example #5
Source Project: SimFix   Author: xgdsmileboy   File: NodeUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean visit(VariableDeclarationStatement node) {
	ASTNode parent = node.getParent();
	while(parent != null){
		if(parent instanceof Block){
			break;
		}
		parent = parent.getParent();
	}
	if(parent != null) {
		int start = _unit.getLineNumber(node.getStartPosition());
		int end = _unit.getLineNumber(parent.getStartPosition() + parent.getLength());
		for (Object o : node.fragments()) {
			VariableDeclarationFragment vdf = (VariableDeclarationFragment) o;
			Pair<String, Type> pair = new Pair<String, Type>(vdf.getName().getFullyQualifiedName(), node.getType());
			Pair<Integer, Integer> range = new Pair<Integer, Integer>(start, end);
			_tmpVars.put(pair, range);
		}
	}
	return true;
}
 
Example #6
Source Project: eclipse.jdt.ls   Author: eclipse   File: ImplementInterfaceProposal.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding);
	ASTNode declNode= null;
	CompilationUnit newRoot= fAstRoot;
	if (boundNode != null) {
		declNode= boundNode; // is same CU
	} else {
		newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		declNode= newRoot.findDeclaringNode(fBinding.getKey());
	}
	ImportRewrite imports= createImportRewrite(newRoot);

	if (declNode instanceof TypeDeclaration) {
		AST ast= declNode.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports);
		Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER);
		ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
		listRewrite.insertLast(newInterface, null);

		return rewrite;
	}
	return null;
}
 
Example #7
Source Project: RefactoringMiner   Author: tsantalis   File: VariableDeclaration.java    License: MIT License 6 votes vote down vote up
public VariableDeclaration(CompilationUnit cu, String filePath, SingleVariableDeclaration fragment) {
	this.annotations = new ArrayList<UMLAnnotation>();
	List<IExtendedModifier> extendedModifiers = fragment.modifiers();
	for(IExtendedModifier extendedModifier : extendedModifiers) {
		if(extendedModifier.isAnnotation()) {
			Annotation annotation = (Annotation)extendedModifier;
			this.annotations.add(new UMLAnnotation(cu, filePath, annotation));
		}
	}
	this.locationInfo = new LocationInfo(cu, filePath, fragment, extractVariableDeclarationType(fragment));
	this.variableName = fragment.getName().getIdentifier();
	this.initializer = fragment.getInitializer() != null ? new AbstractExpression(cu, filePath, fragment.getInitializer(), CodeElementType.VARIABLE_DECLARATION_INITIALIZER) : null;
	Type astType = extractType(fragment);
	this.type = UMLType.extractTypeObject(cu, filePath, astType, fragment.getExtraDimensions());
	int startOffset = fragment.getStartPosition();
	ASTNode scopeNode = getScopeNode(fragment);
	int endOffset = scopeNode.getStartPosition() + scopeNode.getLength();
	this.scope = new VariableScope(cu, filePath, startOffset, endOffset);
}
 
Example #8
Source Project: windup   Author: windup   File: ReferenceResolvingVisitor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The method determines if the type can be resolved and if not, will try to guess the qualified name using the information from the imports.
 */
private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length,
            String line)
{
    if (type == null)
        return null;

    ITypeBinding resolveBinding = type.resolveBinding();
    if (resolveBinding == null)
    {
        ResolveClassnameResult resolvedResult = resolveClassname(type.toString());
        ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;
        PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result);

        return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status,
                    typeReferenceLocation, lineNumber,
                    columnNumber, length, line);
    }
    else
    {
        return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber,
                    columnNumber, length, line);
    }

}
 
Example #9
public String initialize(CompilationUnit root, ASTNode node) {
	if (!(node instanceof Name))
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fSelectedNode= ASTNodes.getNormalizedNode(node);
	if (!(fSelectedNode instanceof Type))
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	StructuralPropertyDescriptor location= fSelectedNode.getLocationInParent();
	if (location != TypeDeclaration.SUPERCLASS_TYPE_PROPERTY && location != TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY && location != EnumDeclaration.SUPER_INTERFACE_TYPES_PROPERTY)
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fSelectedType= ((Type)fSelectedNode).resolveBinding();
	if (fSelectedType == null)
		return SearchMessages.ImplementOccurrencesFinder_invalidTarget;

	fStart= fSelectedNode.getParent(); // type declaration
	fASTRoot= root;
	fDescription= Messages.format(SearchMessages.ImplementOccurrencesFinder_occurrence_description, BasicElementLabels.getJavaElementName(fSelectedType.getName()));

	return null;
}
 
Example #10
Source Project: JDeodorant   Author: tsantalis   File: RefactoringUtility.java    License: MIT License 6 votes vote down vote up
private static Type extractType(VariableDeclaration variableDeclaration) {
	Type returnedVariableType = null;
	if(variableDeclaration instanceof SingleVariableDeclaration) {
		SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration)variableDeclaration;
		returnedVariableType = singleVariableDeclaration.getType();
	}
	else if(variableDeclaration instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)variableDeclaration;
		if(fragment.getParent() instanceof VariableDeclarationStatement) {
			VariableDeclarationStatement variableDeclarationStatement = (VariableDeclarationStatement)fragment.getParent();
			returnedVariableType = variableDeclarationStatement.getType();
		}
		else if(fragment.getParent() instanceof VariableDeclarationExpression) {
			VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression)fragment.getParent();
			returnedVariableType = variableDeclarationExpression.getType();
		}
		else if(fragment.getParent() instanceof FieldDeclaration) {
			FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
			returnedVariableType = fieldDeclaration.getType();
		}
	}
	return returnedVariableType;
}
 
Example #11
Source Project: SimFix   Author: xgdsmileboy   File: CodeBlock.java    License: GNU General Public License v2.0 6 votes vote down vote up
private PostfixExpr visit(PostfixExpression node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	PostfixExpr postfixExpr = new PostfixExpr(startLine, endLine, node);
	
	Expr expression = (Expr) process(node.getOperand());
	expression.setParent(postfixExpr);
	postfixExpr.setExpression(expression);
	
	postfixExpr.setOperator(node.getOperator());
	
	Type exprType = NodeUtils.parseExprType(expression, node.getOperator().toString(), null);
	postfixExpr.setType(exprType);
	
	return postfixExpr;
}
 
Example #12
Source Project: SimFix   Author: xgdsmileboy   File: CodeBlock.java    License: GNU General Public License v2.0 6 votes vote down vote up
private SuperFieldAcc visit(SuperFieldAccess node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	SuperFieldAcc superFieldAcc = new SuperFieldAcc(startLine, endLine, node);
	
	SName identifier = (SName) process(node.getName());
	identifier.setParent(superFieldAcc);
	superFieldAcc.setIdentifier(identifier);
	
	if(node.getQualifier() != null){
		Label name = (Label) process(node.getQualifier());
		name.setParent(superFieldAcc);
		superFieldAcc.setName(name);
	}
	
	Pair<String, String> pair = NodeUtils.getTypeDecAndMethodDec(node);
	Type exprType = ProjectInfo.getVariableType(pair.getFirst(), pair.getSecond(), node.getName().getFullyQualifiedName());
	superFieldAcc.setType(exprType);
	
	return superFieldAcc;
}
 
Example #13
Source Project: JDeodorant   Author: tsantalis   File: StyledStringVisitor.java    License: MIT License 6 votes vote down vote up
public boolean visit(ParameterizedType type) {
	/*
	 * ParameterizedType: Type < Type { , Type } >
	 */
	activateDiffStyle(type);
	handleType(type.getType());
	appendOpenBrace();
	for (int i = 0; i < type.typeArguments().size(); i++) {
		handleType((Type) type.typeArguments().get(i));
		if (i < type.typeArguments().size() - 1) {
			appendComma();
		}
	}
	appendClosedBrace();
	deactivateDiffStyle(type);
	return false;
}
 
Example #14
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodes.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static int getDimensions(VariableDeclaration declaration) {
	int dim= declaration.getExtraDimensions();
	if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) {
		LambdaExpression lambda= (LambdaExpression) declaration.getParent();
		IMethodBinding methodBinding= lambda.resolveMethodBinding();
		if (methodBinding != null) {
			ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
			int index= lambda.parameters().indexOf(declaration);
			ITypeBinding typeBinding= parameterTypes[index];
			return typeBinding.getDimensions();
		}
	} else {
		Type type= getType(declaration);
		if (type instanceof ArrayType) {
			dim+= ((ArrayType) type).getDimensions();
		}
	}
	return dim;
}
 
Example #15
Source Project: KodeBeagle   Author: Imaginea   File: TypeResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param type
 * @return
 */
private String getParametrizedType(final ParameterizedType type, final Boolean innerTypes) {
	final StringBuilder sb = new StringBuilder(getFullyQualifiedNameFor(type
			.getType().toString()));

	if(innerTypes) {
		sb.append("<");
		for (final Object typeArg : type.typeArguments()) {
			final Type arg = (Type) typeArg;
			final String argString = getNameOfType(arg);
			sb.append(argString);
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append(">");
	}
	return sb.toString();
}
 
Example #16
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: MethodExitsFinder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void performSearch() {
	fResult= new ArrayList<OccurrenceLocation>();
	markReferences();
	if (!fResult.isEmpty()) {
		Type returnType= fMethodDeclaration.getReturnType2();
		if (returnType != null) {
			String desc= Messages.format(SearchMessages.MethodExitsFinder_occurrence_return_description, BasicElementLabels.getJavaElementName(fMethodDeclaration.getName().toString()));
			fResult.add(new OccurrenceLocation(returnType.getStartPosition(), returnType.getLength(), 0, desc));
		}
	}
}
 
Example #17
/**
 * Creates and adds the necessary argument declarations to the given factory method.<br>
 * An argument is needed for each original constructor argument for which the
 * evaluation of the actual arguments across all calls was not able to be
 * pushed inside the factory method (e.g. arguments with side-effects, references
 * to fields if the factory method is to be static or reside in a factory class,
 * or arguments that varied across the set of constructor calls).<br>
 * <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
 * @param ast utility object used to create AST nodes
 * @param newMethod the <code>MethodDeclaration</code> for the factory method
 */
private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) {
	List<SingleVariableDeclaration> argDecls= newMethod.parameters();

	for(int i=0; i < fArgTypes.length; i++) {
		SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
		Type argType;

		if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
			// The trailing varargs arg has an extra array dimension, compared to
			// what we need to pass to setType()...
			argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
					fArgTypes[i].getDimensions()-1, ast);
			argDecl.setVarargs(true);
		} else
			argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);

		argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
		argDecl.setType(argType);
		argDecls.add(argDecl);
	}

	ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes();
	List<Type> exceptions= newMethod.thrownExceptionTypes();

	for(int i=0; i < ctorExcepts.length; i++) {
		exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast));
	}

       copyTypeParameters(ast, newMethod);
}
 
Example #18
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
	AST ast= rewrite.getAST();

	List<Expression> arguments= fArguments;
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(getInvocationNode()), getImportRewrite());

	for (int i= 0; i < arguments.size(); i++) {
		Expression elem= arguments.get(i);
		SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

		// argument type
		String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
		Type type= evaluateParameterType(ast, elem, argTypeKey, context);
		param.setType(type);

		// argument name
		String argNameKey= "arg_name_" + i; //$NON-NLS-1$
		String name= evaluateParameterName(takenNames, elem, type, argNameKey);
		param.setName(ast.newSimpleName(name));

		params.add(param);

		addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey);
		addLinkedPosition(rewrite.track(param.getName()), false, argNameKey);
	}
}
 
Example #19
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ConvertForLoopOperation.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
	CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot();
	AST ast= compilationUnit.getAST();

	SingleVariableDeclaration result= ast.newSingleVariableDeclaration();

	SimpleName name= ast.newSimpleName(parameterName);
	pg.addPosition(rewrite.track(name), true);
	result.setName(name);

	ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
	Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
	if (arrayTypeBinding.getDimensions() != 1) {
		type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
	}
	result.setType(type);

	if (fragement != null) {
		VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
		ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
	}
	if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) {
		ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
	}

	return result;
}
 
Example #20
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodeFactory.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns an {@link ArrayType} that adds one dimension to the given type node.
 * If the given node is already an ArrayType, then a new {@link Dimension}
 * without annotations is inserted at the first position.
 * 
 * @param type the type to be wrapped
 * @return the array type
 * @since 3.10
 */
public static ArrayType newArrayType(Type type) {
	if (type instanceof ArrayType) {
		Dimension dimension= type.getAST().newDimension();
		ArrayType arrayType= (ArrayType) type;
		arrayType.dimensions().add(0, dimension); // first dimension is outermost
		return arrayType;
	} else {
		return type.getAST().newArrayType(type);
	}
}
 
Example #21
Source Project: compiler   Author: boalang   File: TreedUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static char buildLabelForVector(ASTNode node) {
	char label = (char) node.getNodeType();
	if (node instanceof Expression) {
		if (node.getClass().getSimpleName().endsWith("Literal")) {
			return (char) (label | (node.toString().hashCode() << 7));
		}
		int type = node.getNodeType();
		switch (type) {
		case ASTNode.INFIX_EXPRESSION:
			return (char) (label | (((InfixExpression) node).getOperator().toString().hashCode() << 7));
		case ASTNode.SIMPLE_NAME:
			return (char) (label | (node.toString().hashCode() << 7));
		case ASTNode.POSTFIX_EXPRESSION:
			return (char) (label | (((PostfixExpression) node).getOperator().toString().hashCode() << 7));
		case ASTNode.PREFIX_EXPRESSION:
			return (char) (label | (((PrefixExpression) node).getOperator().toString().hashCode() << 7));
		default:
			break;
		}
	} else if (node instanceof Modifier) {
		return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof Type) {
		if (node instanceof PrimitiveType)
			return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof TextElement) {
		return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof TagElement) {
		String tag = ((TagElement) node).getTagName();
		if (tag != null)
			return (char) (label | (((TagElement) node).getTagName().hashCode() << 7));
	}
	return label;
}
 
Example #22
private void addExceptionsToNewConstructor(MethodDeclaration newConstructor, ImportRewrite importRewrite) {
     IMethodBinding constructorBinding= getSuperConstructorBinding();
     if (constructorBinding == null)
         return;
     ITypeBinding[] exceptions= constructorBinding.getExceptionTypes();
     for (int i= 0; i < exceptions.length; i++) {
Type exceptionType= importRewrite.addImport(exceptions[i], fAnonymousInnerClassNode.getAST());
newConstructor.thrownExceptionTypes().add(exceptionType);
     }
 }
 
Example #23
@Override
protected void addNewExceptions(ASTRewrite rewrite, List<Type> exceptions) throws CoreException {
	AST ast= rewrite.getAST();
	ImportRewrite importRewrite= getImportRewrite();
	ITypeBinding[] bindings= fMethod.getExceptionTypes();
	for (int i= 0; i < bindings.length; i++) {
		Type newType= importRewrite.addImport(bindings[i], ast);
		exceptions.add(newType);

		addLinkedPosition(rewrite.track(newType), false, "exc_type_" + i); //$NON-NLS-1$
	}
}
 
Example #24
Source Project: DesigniteJava   Author: tushartushar   File: SM_Type.java    License: Apache License 2.0 5 votes vote down vote up
private void setSuperInterface() {
	List<Type> superInterfaces = typeDeclaration.superInterfaceTypes();
	if (superInterfaces != null)
	{
		for (Type superInterface : superInterfaces)  {
			SM_Type inferredType = (new Resolver()).resolveType(superInterface, parentPkg.getParentProject());
			if(inferredType != null) {
				superTypes.add(inferredType);
				inferredType.addThisAsChildToSuperType(this);
			}
		}
	}
		
}
 
Example #25
/** 
 * Create a fresh type reference
 * @param typeBinding the type we want to refer to
 * @param ast AST for creating new nodes
 * @param imports use this for optimal type names
 * @return a fully features non-null type reference (can be parameterized and/or array).
 */
public static Type newType(ITypeBinding typeBinding, AST ast, ImportRewrite imports) {
	// unwrap array type:
	int dimensions= typeBinding.getDimensions();
	if (dimensions > 0)
		typeBinding= typeBinding.getElementType();
	
	// unwrap parameterized type:
	ITypeBinding[] typeArguments= typeBinding.getTypeArguments();
	typeBinding= typeBinding.getErasure();	

	// create leaf type:
	Type elementType = (typeBinding.isPrimitive())
				? ast.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName()))
				: ast.newSimpleType(ast.newName(imports.addImport(typeBinding)));

	// re-wrap as parameterized type:
	if (typeArguments.length > 0) {
		ParameterizedType parameterizedType= ast.newParameterizedType(elementType);
		for (ITypeBinding typeArgument : typeArguments)
			parameterizedType.typeArguments().add(newType(typeArgument, ast, imports));
		elementType = parameterizedType;
	}
	
	// re-wrap as array type:
	if (dimensions > 0)
		return ast.newArrayType(elementType, dimensions);
	else
		return elementType;
}
 
Example #26
Source Project: SimFix   Author: xgdsmileboy   File: CodeBlockMatcherTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void searchAndPrint(String buggyFile, int buggyLine, String searchPath){
		CodeBlock codeBlock = BuggyCode.getBuggyCodeBlock(buggyFile, buggyLine);
		System.out.println(codeBlock.toSrcString());
		System.out.println(codeBlock.getFeatureVector());
		
		Map<String, Type> allUsableVariabes = NodeUtils.getUsableVarTypes(buggyFile, buggyLine);
		
		SimpleFilter simpleFilter = new SimpleFilter(codeBlock);
		List<Pair<CodeBlock, Double>> candidates = simpleFilter.filter(searchPath, 0.5);
		int i = 1;
		for(Pair<CodeBlock, Double> block : candidates){
			System.out.println("---------------- " + (i++) + " ----Similarity : " + block.getSecond() + "-------------------------------------");
			System.out.println(block.getFirst().getFeatureVector());
			System.out.println(block.getFirst().toSrcString());
			
			List<Modification> modifications = CodeBlockMatcher.match(codeBlock, block.getFirst(), allUsableVariabes);
			for(Modification modification : modifications){
				modification.apply(allUsableVariabes);
				System.out.println("====================changed=====================");
				System.out.println(codeBlock.toSrcString().toString());
				modification.restore();
				System.out.println("====================original=====================");
				System.out.println(codeBlock.toSrcString().toString());
			}
//			break;
		}
		System.out.println("-----------" + candidates.size() + "-------------");
	}
 
Example #27
@Override
public boolean visit(MethodDeclaration node) {
	Javadoc javadoc= node.getJavadoc();
	if (javadoc != null) {
		List<TagElement> tags= javadoc.tags();
		for (TagElement tag : tags) {
			String tagName= tag.getTagName();
			if (TagElement.TAG_EXCEPTION.equals(tagName) || TagElement.TAG_THROWS.equals(tagName)) {
				ASTNode name= (ASTNode) tag.fragments().get(0);
				if (name instanceof Name) {
					if (name != fSelectedNode && Bindings.equals(fException, ((Name) name).resolveBinding())) {
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
				}
			}
		}
	}
	List<Type> thrownExceptionTypes= node.thrownExceptionTypes();
	for (Iterator<Type> iter= thrownExceptionTypes.iterator(); iter.hasNext(); ) {
		Type type = iter.next();
		if (type != fSelectedNode && Bindings.equals(fException, type.resolveBinding())) {
			fResult.add(new OccurrenceLocation(type.getStartPosition(), type.getLength(), 0, fDescription));
		}
	}
	Block body= node.getBody();
	if (body != null) {
		node.getBody().accept(this);
	}
	return false;
}
 
Example #28
private void handleResourceDeclarations(TryStatement tryStatement) {
	List<VariableDeclarationExpression> resources= tryStatement.resources();
	for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	//check if the exception is thrown as a result of resource#close()
	boolean exitMarked= false;
	for (VariableDeclarationExpression variable : resources) {
		Type type= variable.getType();
		IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
		if (methodBinding != null) {
			ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
			for (int j= 0; j < exceptionTypes.length; j++) {
				if (matches(exceptionTypes[j])) { // a close() throws the caught exception
					// mark name of resource
					for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
						SimpleName name= fragment.getName();
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
					if (!exitMarked) {
						// mark exit position
						exitMarked= true;
						Block body= tryStatement.getBody();
						int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
						fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
								BasicElementLabels.getJavaElementName(fException.getName()))));
					}
				}
			}
		}
	}
}
 
Example #29
Source Project: juniversal   Author: juniversal   File: VariableDeclarationWriter.java    License: MIT License 5 votes vote down vote up
private void writeVariableDeclaration(List<?> modifiers, Type type, List<?> fragments) {
	// Turn "final" into "const"
	if (ASTUtil.containsFinal(modifiers)) {
		write("const");
		skipModifiers(modifiers);

		copySpaceAndComments();
	}

	// Write the type
       writeType(type, false);

	boolean needStar = false;
	getContext().setWritingVariableDeclarationNeedingStar(needStar);

	// Write the variable declaration(s)
	boolean first = true;
	for (Object fragment : fragments) {
		VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment) fragment;

		copySpaceAndComments();
		if (!first) {
			matchAndWrite(",");
			copySpaceAndComments();
		}
           writeNode(variableDeclarationFragment);

		first = false;
	}

	getContext().setWritingVariableDeclarationNeedingStar(false);
}
 
Example #30
Source Project: windup   Author: windup   File: ReferenceResolvingVisitor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(InstanceofExpression node)
{
    Type type = node.getRightOperand();
    processType(type, TypeReferenceLocation.INSTANCE_OF, compilationUnit.getLineNumber(node.getStartPosition()),
                compilationUnit.getColumnNumber(type.getStartPosition()), type.getLength(), node.toString());

    return super.visit(node);
}