Java Code Examples for org.eclipse.jdt.core.dom.AST#newPrimitiveType()

The following examples show how to use org.eclipse.jdt.core.dom.AST#newPrimitiveType() . 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: NodeUtils.java    From SimFix with 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 2
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
private InstanceofExpr visit(InstanceofExpression node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	InstanceofExpr instanceofExpr = new InstanceofExpr(startLine, endLine, node);
	
	Expr expression = (Expr) process(node.getLeftOperand());
	expression.setParent(instanceofExpr);
	instanceofExpr.setExpression(expression);
	
	instanceofExpr.setInstanceType(node.getRightOperand());
	
	AST ast = AST.newAST(AST.JLS8);
	Type exprType = ast.newPrimitiveType(PrimitiveType.BOOLEAN);
	instanceofExpr.setType(exprType);
	
	return instanceofExpr;
}
 
Example 3
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private BoolLiteral visit(BooleanLiteral node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	BoolLiteral literal = new BoolLiteral(startLine, endLine, node);
	literal.setValue(node.booleanValue());
	AST ast = AST.newAST(AST.JLS8);
	Type type = ast.newPrimitiveType(PrimitiveType.BOOLEAN);
	literal.setType(type);
	
	return literal;
}
 
Example 4
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private CharLiteral visit(CharacterLiteral node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	CharLiteral charLiteral = new CharLiteral(startLine, endLine, node);
	
	charLiteral.setValue(node.charValue());
	
	AST ast = AST.newAST(AST.JLS8);
	Type type = ast.newPrimitiveType(PrimitiveType.CHAR);
	charLiteral.setType(type);
	
	return charLiteral;
}
 
Example 5
Source File: UpdateAsyncSignatureProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Type computeReturnType(AST ast, MethodDeclaration srcMethod,
    MethodDeclaration dstMethod, ImportRewrite imports) {

  // Use the previous async return type if valid
  ITypeBinding typeBinding = dstMethod.getReturnType2().resolveBinding();
  if (typeBinding != null
      && Util.VALID_ASYNC_RPC_RETURN_TYPES.contains(typeBinding.getQualifiedName())) {
    return JavaASTUtils.normalizeTypeAndAddImport(ast,
        dstMethod.getReturnType2(), imports);
  }

  return ast.newPrimitiveType(PrimitiveType.VOID);
}
 
Example 6
Source File: GetterSetterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the assignment needs a downcast and inserts it if necessary
 *
 * @param expression the right hand-side
 * @param expressionType the type of the right hand-side. Can be null
 * @param ast the AST
 * @param variableType the Type of the variable the expression will be assigned to
 * @param is50OrHigher if <code>true</code> java 5.0 code will be assumed
 * @return the casted expression if necessary
 */
private static Expression createNarrowCastIfNessecary(Expression expression, ITypeBinding expressionType, AST ast, ITypeBinding variableType, boolean is50OrHigher) {
	PrimitiveType castTo= null;
	if (variableType.isEqualTo(expressionType))
		return expression; //no cast for same type
	if (is50OrHigher) {
		if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
		if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
		if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	}
	if (ast.resolveWellKnownType("char").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
	if (ast.resolveWellKnownType("byte").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
	if (ast.resolveWellKnownType("short").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	if (castTo != null) {
		CastExpression cast= ast.newCastExpression();
		if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
			ParenthesizedExpression parenthesized= ast.newParenthesizedExpression();
			parenthesized.setExpression(expression);
			cast.setExpression(parenthesized);
		} else
			cast.setExpression(expression);
		cast.setType(castTo);
		return cast;
	}
	return expression;
}
 
Example 7
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Generates a {@link VariableDeclarationExpression}, which initializes the loop variable to
 * iterate over an array.
 * 
 * @param ast the current {@link AST} instance
 * @param loopVariableName the name of the variable which should be initialized
 * @return a filled {@link VariableDeclarationExpression}, declaring a int variable, which is
 *         initializes with 0
 */
private VariableDeclarationExpression getForInitializer(AST ast, SimpleName loopVariableName) {
	// initializing fragment
	VariableDeclarationFragment firstDeclarationFragment= ast.newVariableDeclarationFragment();
	firstDeclarationFragment.setName(loopVariableName);
	NumberLiteral startIndex= ast.newNumberLiteral();
	firstDeclarationFragment.setInitializer(startIndex);

	// declaration
	VariableDeclarationExpression variableDeclaration= ast.newVariableDeclarationExpression(firstDeclarationFragment);
	PrimitiveType variableType= ast.newPrimitiveType(PrimitiveType.INT);
	variableDeclaration.setType(variableType);

	return variableDeclaration;
}
 
Example 8
Source File: ExtractToNullCheckedLocalProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/** 
 * 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 9
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
public static Type parseExprType(Expr left, String operator, Expr right){
	if(left == null){
		return parsePreExprType(right, operator);
	}
	
	if(right == null){
		return parsePostExprType(left, operator);
	}
	
	AST ast = AST.newAST(AST.JLS8);
	switch(operator){
	case "*":
	case "/":
	case "+":
	case "-":
		Type type = union(left.getType(), right.getType());
		if(type == null){
			type = ast.newPrimitiveType(PrimitiveType.DOUBLE);
		}
		return type;
	case "%":
	case "<<":
	case ">>":
	case ">>>":
	case "^":
	case "&":
	case "|":
		return ast.newPrimitiveType(PrimitiveType.INT);
	case "<":
	case ">":
	case "<=":
	case ">=":
	case "==":
	case "!=":
	case "&&":
	case "||":
		return ast.newPrimitiveType(PrimitiveType.BOOLEAN);
	default :
		return null;
	}
	
}
 
Example 10
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
private static Type parsePostExprType(Expr expr, String operator){
	// ++/--
	AST ast = AST.newAST(AST.JLS8);
	return ast.newPrimitiveType(PrimitiveType.INT);
}
 
Example 11
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast = fEnclosingBodyDeclaration.getAST();
	fReturnType = null;
	fReturnTypeBinding = null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration = ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType = ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding = declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression = (Expression) getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding();
			} else {
				fExpressionBinding = expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding = Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType = rewriter.addImport(normalizedBinding, ast, context, TypeLocation.RETURN_TYPE);
						fReturnTypeBinding = normalizedBinding;
					}
				}
			} else {
				fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 12
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Sync method has same return type as parameterization of last async
 * parameter (AsyncCallback). If the async callback parameter type is raw,
 * just assume sync return type of void.
 *
 * @param ast {@link AST} associated with the destination compilation unit
 * @param asyncMethod the GWT RPC async method declaration
 * @param imports {@link ImportRewrite} associated with the destination
 *          compilation unit
 * @return the computed return {@link Type}
 */
public static Type computeSyncReturnType(AST ast,
    MethodDeclaration asyncMethod, ImportRewrite imports) {
  Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
  @SuppressWarnings("unchecked")
  List<SingleVariableDeclaration> asyncParameters = asyncMethod.parameters();

  // Check for no parameters on async method... just in case
  if (asyncParameters.isEmpty()) {
    return returnType;
  }

  // Grab the last parameter type, which should be the callback
  Type callbackType = asyncParameters.get(asyncParameters.size() - 1).getType();

  // Make sure we have a parameterized callback type; otherwise, we can't
  // infer the return type of the sync method.
  if (callbackType.isParameterizedType()) {
    ParameterizedType callbackParamType = (ParameterizedType) callbackType;

    ITypeBinding callbackBinding = callbackParamType.getType().resolveBinding();
    if (callbackBinding == null) {
      return returnType;
    }

    // Make sure the callback is of type AsyncCallback
    String callbackBaseTypeName = callbackBinding.getErasure().getQualifiedName();
    if (callbackBaseTypeName.equals(RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME)) {
      @SuppressWarnings("unchecked")
      List<Type> callbackTypeArgs = callbackParamType.typeArguments();

      // Make sure we only have one type argument
      if (callbackTypeArgs.size() == 1) {
        Type callbackTypeParameter = callbackTypeArgs.get(0);

        // Check for primitive wrapper type; if we have one use the actual
        // primitive for the sync return type.
        // TODO(): Maybe used linked mode to let the user choose whether to
        // return the primitive or its wrapper type.
        String qualifiedName = callbackTypeParameter.resolveBinding().getQualifiedName();
        String primitiveTypeName = JavaASTUtils.getPrimitiveTypeName(qualifiedName);
        if (primitiveTypeName != null) {
          return ast.newPrimitiveType(PrimitiveType.toCode(primitiveTypeName));
        }

        returnType = JavaASTUtils.normalizeTypeAndAddImport(ast,
            callbackTypeParameter, imports);
      }
    }
  }

  return returnType;
}
 
Example 13
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast= fEnclosingBodyDeclaration.getAST();
	fReturnType= null;
	fReturnTypeBinding= null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration= ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType= ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding= declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression= (Expression)getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding= ((ClassInstanceCreation)expression).getType().resolveBinding();
			} else {
				fExpressionBinding= expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding= Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType= rewriter.addImport(normalizedBinding, ast, context);
						fReturnTypeBinding= normalizedBinding;
					}
				}
			} else {
				fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType= ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding= methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType= ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding= fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 14
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Type createType(String typeSig, AST ast) {
	int sigKind = Signature.getTypeSignatureKind(typeSig);
       switch (sigKind) {
           case Signature.BASE_TYPE_SIGNATURE:
               return ast.newPrimitiveType(PrimitiveType.toCode(Signature.toString(typeSig)));
           case Signature.ARRAY_TYPE_SIGNATURE:
               Type elementType = createType(Signature.getElementType(typeSig), ast);
               return ast.newArrayType(elementType, Signature.getArrayCount(typeSig));
           case Signature.CLASS_TYPE_SIGNATURE:
               String erasureSig = Signature.getTypeErasure(typeSig);

               String erasureName = Signature.toString(erasureSig);
               if (erasureSig.charAt(0) == Signature.C_RESOLVED) {
                   erasureName = addImport(erasureName);
               }
               
               Type baseType= ast.newSimpleType(ast.newName(erasureName));
               String[] typeArguments = Signature.getTypeArguments(typeSig);
               if (typeArguments.length > 0) {
                   ParameterizedType type = ast.newParameterizedType(baseType);
                   List argNodes = type.typeArguments();
                   for (int i = 0; i < typeArguments.length; i++) {
                       String curr = typeArguments[i];
                       if (containsNestedCapture(curr)) {
                           argNodes.add(ast.newWildcardType());
                       } else {
                           argNodes.add(createType(curr, ast));
                       }
                   }
                   return type;
               }
               return baseType;
           case Signature.TYPE_VARIABLE_SIGNATURE:
               return ast.newSimpleType(ast.newSimpleName(Signature.toString(typeSig)));
           case Signature.WILDCARD_TYPE_SIGNATURE:
               WildcardType wildcardType= ast.newWildcardType();
               char ch = typeSig.charAt(0);
               if (ch != Signature.C_STAR) {
                   Type bound= createType(typeSig.substring(1), ast);
                   wildcardType.setBound(bound, ch == Signature.C_EXTENDS);
               }
               return wildcardType;
           case Signature.CAPTURE_TYPE_SIGNATURE:
               return createType(typeSig.substring(1), ast);
       }
       
       return ast.newSimpleType(ast.newName("java.lang.Object"));
}
 
Example 15
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 2 votes vote down vote up
private static Type union(Type ty1, Type ty2){
	if(ty1 == null){
		return ty2;
	} else if(ty2 == null){
		return ty1;
	}
	
	if(!ty1.isPrimitiveType() || !ty2.isPrimitiveType()){
		return null;
	}
	
	String ty1String = ty1.toString().toLowerCase().replace("integer", "int");
	String ty2String = ty2.toString().toLowerCase().replace("integer", "int");
	
	AST ast = AST.newAST(AST.JLS8);
	if(ty1String.equals("double") || ty2String.equals("double")){
		
		return ast.newPrimitiveType(PrimitiveType.DOUBLE);
		
	} else if(ty1String.equals("float") || ty2String.equals("float")){
		
		return ast.newPrimitiveType(PrimitiveType.FLOAT);
		
	} else if(ty1String.equals("long") || ty2String.equals("long")){
		
		return ast.newPrimitiveType(PrimitiveType.LONG);
		
	} else if(ty1String.equals("int") || ty2String.equals("int")){
		
		return ast.newPrimitiveType(PrimitiveType.INT);
		
	} else if(ty1String.equals("short") || ty2String.equals("short")){
		
		return ast.newPrimitiveType(PrimitiveType.SHORT);
		
	} else {
		
		return ast.newPrimitiveType(PrimitiveType.BYTE);
		
	}
	
}