/** * 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; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
private boolean testPrimitiveTypeEquals(final Class<?> expected, final Code actual) { String name = actual.toString(); if( name.equals(PrimitiveType.BOOLEAN.toString()) ) { return expected.equals(Boolean.TYPE); } else if(name.equals(PrimitiveType.INT.toString())) { return expected.equals(Integer.TYPE); } else if(name.equals(PrimitiveType.CHAR.toString())) { return expected.equals(Character.TYPE); } else if(name.equals(PrimitiveType.SHORT.toString())) { return expected.equals(Short.TYPE); } else if(name.equals(PrimitiveType.LONG.toString())) { return expected.equals(Long.TYPE); } else if(name.equals(PrimitiveType.FLOAT.toString())) { return expected.equals(Float.TYPE); } else if(name.equals(PrimitiveType.DOUBLE.toString())) { return expected.equals(Double.TYPE); } else if(name.equals(PrimitiveType.BYTE.toString())) { return expected.equals(Byte.TYPE); } else if(name.equals(PrimitiveType.VOID.toString())) { return expected.equals(Void.TYPE); } System.err.println("warning: unknown primitive type: " + actual); throw new UnsupportedOperationException(); //return false; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration .modifiers() .addAll( ASTNodeFactory.newModifiers( ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) continue; if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) rewrite .getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()) .insertAt(declaration, 0, editGroup); else if (node instanceof AnonymousClassDeclaration) rewrite .getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) rewrite .getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); } } else Assert.isTrue(false); addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment( fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit)); if (comment != null && comment.length() > 0) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) return; positionGroups.setEndPosition(rewrite.track(fragment)); }
private void addNewConstructorToSubclass( AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast = subclass.getAST(); MethodDeclaration newConstructor = ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setJavadoc(null); newConstructor .modifiers() .addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body = ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall = ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg = RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description = cuRewrite.createGroupDescription(msg); cuRewrite .getASTRewrite() .getListRewrite(subclass, subclass.getBodyDeclarationsProperty()) .insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
/** * Creates the corresponding statement for the method invocation, based on the return type. * * @param declaration the method declaration where the invocation statement is inserted * @param invocation the method invocation being encapsulated by the resulting statement * @return the corresponding statement */ protected Statement createMethodInvocation( final MethodDeclaration declaration, final MethodInvocation invocation) { Assert.isNotNull(declaration); Assert.isNotNull(invocation); Statement statement = null; final Type type = declaration.getReturnType2(); if (type == null) statement = createExpressionStatement(invocation); else { if (type instanceof PrimitiveType) { final PrimitiveType primitive = (PrimitiveType) type; if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) statement = createExpressionStatement(invocation); else statement = createReturnStatement(invocation); } else statement = createReturnStatement(invocation); } return statement; }
public static boolean isGeneralizeTypeAvailable(final IJavaElement element) throws JavaModelException { if (element != null && element.exists()) { String type = null; if (element instanceof IMethod) type = ((IMethod) element).getReturnType(); else if (element instanceof IField) { final IField field = (IField) element; if (JdtFlags.isEnum(field)) return false; type = field.getTypeSignature(); } else if (element instanceof ILocalVariable) return true; else if (element instanceof IType) { final IType clazz = (IType) element; if (JdtFlags.isEnum(clazz)) return false; return true; } if (type == null || PrimitiveType.toCode(Signature.toString(type)) != null) return false; return true; } return false; }
public static boolean isGeneralizeTypeAvailable(final IStructuredSelection selection) throws JavaModelException { if (selection.size() == 1) { final Object element = selection.getFirstElement(); if (element instanceof IMethod) { final IMethod method = (IMethod) element; if (!method.exists()) return false; final String type = method.getReturnType(); if (PrimitiveType.toCode(Signature.toString(type)) == null) return Checks.isAvailable(method); } else if (element instanceof IField) { final IField field = (IField) element; if (!field.exists()) return false; if (!JdtFlags.isEnum(field)) return Checks.isAvailable(field); } } return false; }
@Override protected MethodDeclaration createMethodDeclaration(AST ast) { MethodDeclaration asyncMethodDecl = ast.newMethodDeclaration(); // New method has same name as original String methodName = getSyncMethodDeclaration().getName().getIdentifier(); asyncMethodDecl.setName(ast.newSimpleName(methodName)); // Async method has void return type by default (the user can also use // Request or RequestBuilder as the return type to get more functionality). // TODO: investigate whether we can enter linked mode after the fix is // applied, so the user can choose what return type to use. See // LinkedCorrectionProposal, which is a subclass of // ASTRewriteCorrectionProposal. asyncMethodDecl.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); addAsyncParameters(ast, asyncMethodDecl); // TODO: generate comments for new method return asyncMethodDecl; }
private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast= subclass.getAST(); MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setJavadoc(null); newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body= ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description= cuRewrite.createGroupDescription(msg); cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
/** * Creates the corresponding statement for the method invocation, based on * the return type. * * @param declaration the method declaration where the invocation statement * is inserted * @param invocation the method invocation being encapsulated by the * resulting statement * @return the corresponding statement */ protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) { Assert.isNotNull(declaration); Assert.isNotNull(invocation); Statement statement= null; final Type type= declaration.getReturnType2(); if (type == null) statement= createExpressionStatement(invocation); else { if (type instanceof PrimitiveType) { final PrimitiveType primitive= (PrimitiveType) type; if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) statement= createExpressionStatement(invocation); else statement= createReturnStatement(invocation); } else statement= createReturnStatement(invocation); } return statement; }
public static boolean isGeneralizeTypeAvailable(final IJavaElement element) throws JavaModelException { if (element != null && element.exists()) { String type= null; if (element instanceof IMethod) type= ((IMethod) element).getReturnType(); else if (element instanceof IField) { final IField field= (IField) element; if (JdtFlags.isEnum(field)) return false; type= field.getTypeSignature(); } else if (element instanceof ILocalVariable) return true; else if (element instanceof IType) { final IType clazz= (IType) element; if (JdtFlags.isEnum(clazz)) return false; return true; } if (type == null || PrimitiveType.toCode(Signature.toString(type)) != null) return false; return true; } return false; }
public static boolean isGeneralizeTypeAvailable(final IStructuredSelection selection) throws JavaModelException { if (selection.size() == 1) { final Object element= selection.getFirstElement(); if (element instanceof IMethod) { final IMethod method= (IMethod) element; if (!method.exists()) return false; final String type= method.getReturnType(); if (PrimitiveType.toCode(Signature.toString(type)) == null) return Checks.isAvailable(method); } else if (element instanceof IField) { final IField field= (IField) element; if (!field.exists()) return false; if (!JdtFlags.isEnum(field)) return Checks.isAvailable(field); } } return false; }
/** * @return a statement in form of <code>final int maxLen = 10;</code> */ protected VariableDeclarationStatement createMaxLenDeclaration() { VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment(); fragment.setName(fAst.newSimpleName(fMaxLenVariableName)); fragment.setInitializer(fAst.newNumberLiteral(String.valueOf(fContext.getLimitItemsValue()))); VariableDeclarationStatement declExpression= fAst.newVariableDeclarationStatement(fragment); declExpression.setType(fAst.newPrimitiveType(PrimitiveType.INT)); declExpression.modifiers().add(fAst.newModifier(ModifierKeyword.FINAL_KEYWORD)); return declExpression; }
private Expression createShiftAssignment(Expression shift1, Expression shift2) { // (int)(element ^ (element >>> 32)); // see implementation in Arrays.hashCode(), Double.hashCode() and // Long.hashCode() CastExpression ce= fAst.newCastExpression(); ce.setType(fAst.newPrimitiveType(PrimitiveType.INT)); InfixExpression unsignedShiftRight= fAst.newInfixExpression(); unsignedShiftRight.setLeftOperand(shift1); unsignedShiftRight.setRightOperand(fAst.newNumberLiteral("32")); //$NON-NLS-1$ unsignedShiftRight.setOperator(Operator.RIGHT_SHIFT_UNSIGNED); InfixExpression xor= fAst.newInfixExpression(); xor.setLeftOperand(shift2); xor.setRightOperand(parenthesize(unsignedShiftRight)); xor.setOperator(InfixExpression.Operator.XOR); ce.setExpression(parenthesize(xor)); return ce; }
private static IMember getMember(IStructuredSelection selection) throws JavaModelException { if (selection.size() != 1) return null; Object element= selection.getFirstElement(); if (!(element instanceof IMember)) return null; if (element instanceof IMethod) { IMethod method= (IMethod)element; String returnType= method.getReturnType(); if (PrimitiveType.toCode(Signature.toString(returnType)) != null) return null; return method; } else if (element instanceof IField && !JdtFlags.isEnum((IMember) element)) { return (IField)element; } return null; }
private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast= subclass.getAST(); MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setExtraDimensions(0); newConstructor.setJavadoc(null); newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body= ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description= cuRewrite.createGroupDescription(msg); cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
/** * Creates a "return super.method(args)" statement for the given method */ private Statement getSuperMethCall(MethodDeclaration md) { SuperMethodInvocation smi = ast.newSuperMethodInvocation(); smi.setName((SimpleName)ASTNode.copySubtree(ast, md.getName())); for (int i = 0; i < md.parameters().size(); i++) { SingleVariableDeclaration svd = (SingleVariableDeclaration)md.parameters().get(i); smi.arguments().add((Name)ASTNode.copySubtree(ast, svd.getName())); } Type type = md.getReturnType2(); if (md.getReturnType2().isPrimitiveType()) { PrimitiveType.Code ptcode = ((PrimitiveType)type).getPrimitiveTypeCode(); if (ptcode == PrimitiveType.VOID) { return ast.newExpressionStatement(smi); } } ReturnStatement rs = ast.newReturnStatement(); rs.setExpression(smi); return rs; }
protected boolean tryToResolve(Type type) { boolean result = false; if (underResolution.getResolverMap().containsKey(type)) { result = true; } else { if (type.isPrimitiveType()) { result = tryToResolve((PrimitiveType)type); } else if (type.isQualifiedType()) { result = tryToResolve((QualifiedType)type); } else if (type.isArrayType()) { result = tryToResolve(((ArrayType)type).getElementType()); } else if (type.isSimpleType()) { result = tryToResolve((SimpleType)type); } else if (type.isParameterizedType()) { result = tryToResolve((ParameterizedType)type); } else if (type.isWildcardType()) { result = tryToResolve((WildcardType)type); } else { CoreActivator.log(IStatus.INFO, "Type not handled " + type.toString()); } } return result; }
protected boolean tryToResolve(PrimitiveType primitiveType) { boolean result = false; PrimitiveType.Code typeCode = primitiveType.getPrimitiveTypeCode(); org.eclipse.uml2.uml.PrimitiveType umlPrimitiveType; if (typeCode.equals(PrimitiveType.VOID)) { umlPrimitiveType = null; underResolution.getResolverMap().put(primitiveType, umlPrimitiveType); result = true; } else { umlPrimitiveType = Utils.searchPrimiveTypeInModels(context, typeCode.toString()); if (umlPrimitiveType != null) { underResolution.getResolverMap().put(primitiveType, umlPrimitiveType); result = true; } } return result; }
protected Type createType(ITypeBinding typeBind, AST ast) { ITypeBinding realType = typeBind; Type result = null; if (typeBind.isArray()) { realType = typeBind.getElementType(); } if (realType.isPrimitive()) { result = ast.newPrimitiveType(PrimitiveType.toCode(realType.getName())); } else if (realType.isParameterizedType()) { String typeName = realType.getName(); result = ast.newSimpleType(ast.newSimpleName(typeName.substring(0, typeName.indexOf('<')))); } else { result = ast.newSimpleType(ast.newSimpleName(realType.getName())); } if (typeBind.isArray()) { return ast.newArrayType(result, typeBind.getDimensions()); } return result; }
/** * Returns true iff 'methodDeclaration' represents a void static method named 'main' that takes a * single String[] parameter. */ private static boolean isMainMethod(MethodDeclaration methodDeclaration) { // Is it static? if ((methodDeclaration.getModifiers() & Modifier.STATIC) == 0) { return false; } // Does it return void? Type returnType = methodDeclaration.getReturnType2(); if (!returnType.isPrimitiveType()) { return false; } if (((PrimitiveType) returnType).getPrimitiveTypeCode() != PrimitiveType.VOID) { return false; } // Is it called 'main'? if (!"main".equals(methodDeclaration.getName().getIdentifier())) { return false; } // Does it have a single parameter? if (methodDeclaration.parameters().size() != 1) { return false; } // Is the parameter's type String[]? SingleVariableDeclaration pt = getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters()); IVariableBinding vb = pt.resolveBinding(); if (vb == null) { return false; } ITypeBinding tb = vb.getType(); return tb != null && "java.lang.String[]".equals(tb.getQualifiedName()); }
/** * Returns an expression that is assignable to the given type. <code>null</code> is * returned if the type is the 'void' type. * * @param ast The AST to create the expression for * @param type The type of the returned expression * @param extraDimensions Extra dimensions to the type * @return the Null-literal for reference types, a boolean-literal for a boolean type, a number * literal for primitive types or <code>null</code> if the type is void. */ public static Expression newDefaultExpression(AST ast, Type type, int extraDimensions) { if (extraDimensions == 0 && type.isPrimitiveType()) { PrimitiveType primitiveType= (PrimitiveType) type; if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) { return ast.newBooleanLiteral(false); } else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) { return null; } else { return ast.newNumberLiteral("0"); //$NON-NLS-1$ } } return ast.newNullLiteral(); }
private Type getNewMethodType(ASTRewrite rewrite, ImportRewriteContext context) throws CoreException { AST ast = rewrite.getAST(); Type newTypeNode = null; if (isGetter) { newTypeNode = getImportRewrite().addImport(fVariableBinding.getType(), ast, context, TypeLocation.RETURN_TYPE); } else { newTypeNode = ast.newPrimitiveType(PrimitiveType.VOID); } return newTypeNode; }
private boolean testTypeEquals(final Class<?> expected, Type actual) { if(actual.isSimpleType()) { SimpleType simpleDeclaration = (SimpleType)actual; return testNameEquals(expected, simpleDeclaration.getName()); } else if (actual.isPrimitiveType()) { PrimitiveType primitive = (PrimitiveType)actual; return testPrimitiveTypeEquals(expected, primitive.getPrimitiveTypeCode()); } else { //unbekannter Typ System.err.println("warning: not simple type, feature not implemented. type is: " + actual.getClass()); throw new UnsupportedOperationException(); } }
/** * Returns an expression that is assignable to the given type. <code>null</code> is returned if * the type is the 'void' type. * * @param ast The AST to create the expression for * @param type The type of the returned expression * @param extraDimensions Extra dimensions to the type * @return the Null-literal for reference types, a boolean-literal for a boolean type, a number * literal for primitive types or <code>null</code> if the type is void. */ public static Expression newDefaultExpression(AST ast, Type type, int extraDimensions) { if (extraDimensions == 0 && type.isPrimitiveType()) { PrimitiveType primitiveType = (PrimitiveType) type; if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) { return ast.newBooleanLiteral(false); } else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) { return null; } else { return ast.newNumberLiteral("0"); // $NON-NLS-1$ } } return ast.newNullLiteral(); }
/** * 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; }
private Statement encapsulateInvocation( MethodDeclaration declaration, MethodInvocation invocation) { final Type type = declaration.getReturnType2(); if (type == null || (type instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType) type).getPrimitiveTypeCode()))) return invocation.getAST().newExpressionStatement(invocation); ReturnStatement statement = invocation.getAST().newReturnStatement(); statement.setExpression(invocation); return statement; }
private static boolean isVoidArrayType(Type type) { if (!type.isArrayType()) return false; ArrayType arrayType = (ArrayType) type; if (!arrayType.getElementType().isPrimitiveType()) return false; PrimitiveType primitiveType = (PrimitiveType) arrayType.getElementType(); return (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID); }
private static Type parseSuperType(String superType, boolean isInterface) { if (!superType.trim().equals(superType)) { return null; } StringBuffer cuBuff = new StringBuffer(); if (isInterface) cuBuff.append("class __X__ implements "); // $NON-NLS-1$ else cuBuff.append("class __X__ extends "); // $NON-NLS-1$ int offset = cuBuff.length(); cuBuff.append(superType).append(" {}"); // $NON-NLS-1$ ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); p.setSource(cuBuff.toString().toCharArray()); Map<String, String> options = new HashMap<String, String>(); JavaModelUtil.setComplianceOptions(options, JavaModelUtil.VERSION_LATEST); p.setCompilerOptions(options); CompilationUnit cu = (CompilationUnit) p.createAST(null); ASTNode selected = NodeFinder.perform(cu, offset, superType.length()); if (selected instanceof Name) selected = selected.getParent(); if (selected.getStartPosition() != offset || selected.getLength() != superType.length() || !(selected instanceof Type) || selected instanceof PrimitiveType) { return null; } Type type = (Type) selected; String typeNodeRange = cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type)); if (!superType.equals(typeNodeRange)) { return null; } return type; }
private PrimitiveType.Code getPrimitiveTypeCode(String type) { PrimitiveType.Code code = PrimitiveType.toCode(type); if (code != null) { return code; } if (fEnclosingElement != null && JavaModelUtil.is50OrHigher(fEnclosingElement.getJavaProject())) { if (code == PrimitiveType.SHORT) { if ("java.lang.Short".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.INT) { if ("java.lang.Integer".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.LONG) { if ("java.lang.Long".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.FLOAT) { if ("java.lang.Float".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.DOUBLE) { if ("java.lang.Double".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.CHAR) { if ("java.lang.Character".equals(type)) { // $NON-NLS-1$ return code; } } else if (code == PrimitiveType.BYTE) { if ("java.lang.Byte".equals(type)) { // $NON-NLS-1$ return code; } } } return null; }
/** * 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; }
@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); }
public static boolean isVoid(Type type) { if (type instanceof PrimitiveType) { return ((PrimitiveType) type).getPrimitiveTypeCode().equals(PrimitiveType.VOID); } else { return false; } }