Example usage for org.eclipse.jdt.core.dom PrimitiveType FLOAT

List of usage examples for org.eclipse.jdt.core.dom PrimitiveType FLOAT

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom PrimitiveType FLOAT.

Prototype

Code FLOAT

To view the source code for org.eclipse.jdt.core.dom PrimitiveType FLOAT.

Click Source Link

Document

Type code for the primitive type "float".

Usage

From source file:com.motorola.studio.android.generateviewbylayout.codegenerators.RatingBarCodeGenerator.java

License:Apache License

/**
 * Adds methods (event handler) for RatingBar 
 * /*from  ww  w .j  a v  a 2  s.  com*/
 * <br>
 * GENERATED_CODE_FORMAT:
 * <br>
 * $GUI_ID.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
 * <br>
   public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
   <br>     
}
   <br>
});    
 * 
 * @param monitor
 */
private void addOnRatingBarChangeListener(IProgressMonitor monitor) throws JavaModelException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    subMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_AddingRatingBarHandler,
            codeGeneratorData.getGuiItems().size());
    for (LayoutNode node : codeGeneratorData.getGuiItems()) {
        if (node.shouldInsertCode()
                && node.getNodeType().equals(LayoutNode.LayoutNodeViewType.RatingBar.name())) {
            boolean containMethodDeclared = checkIfInvokeMethodIsDeclared(node,
                    JavaViewBasedOnLayoutModifierConstants.SET_ON_RATING_BAR_CHANGE_LISTENER);
            if (!containMethodDeclared) {
                List<SingleVariableDeclaration> parameters1 = new ArrayList<SingleVariableDeclaration>();
                SingleVariableDeclaration param1 = createVariableDeclarationFromStrings(
                        LayoutNode.LayoutNodeViewType.RatingBar.name(),
                        JavaViewBasedOnLayoutModifierConstants.RATING_BAR_VARIABLE); //$NON-NLS-1$
                parameters1.add(param1);
                SingleVariableDeclaration param2 = createVariableDeclarationPrimitiveCode(PrimitiveType.FLOAT,
                        JavaViewBasedOnLayoutModifierConstants.RATING_VARIABLE); //$NON-NLS-1$
                parameters1.add(param2);
                SingleVariableDeclaration param3 = createVariableDeclarationPrimitiveCode(PrimitiveType.BOOLEAN,
                        JavaViewBasedOnLayoutModifierConstants.FROM_USER_VARIABLE); //$NON-NLS-1$
                parameters1.add(param3);
                MethodDeclaration methodDeclaration1 = addMethodDeclaration(ModifierKeyword.PUBLIC_KEYWORD,
                        JavaViewBasedOnLayoutModifierConstants.ON_RATING_CHANGED, PrimitiveType.VOID,
                        parameters1);
                Block block1 = onCreateDeclaration.getAST().newBlock();
                methodDeclaration1.setBody(block1);

                addMethodInvocationToListenerHandler(node.getNodeId(),
                        JavaViewBasedOnLayoutModifierConstants.SET_ON_RATING_BAR_CHANGE_LISTENER,
                        LayoutNode.LayoutNodeViewType.RatingBar.name(),
                        JavaViewBasedOnLayoutModifierConstants.ON_RATING_BAR_CHANGE_LISTENER,
                        methodDeclaration1);
            }
        }
        subMonitor.worked(1);
    }
}

From source file:de.crowdcode.kissmda.core.jdt.DataTypeUtils.java

License:Apache License

private void createPrimitiveTypeCodes() {
    primitiveTypeCodes = new HashMap<String, Code>();
    primitiveTypeCodes.put("integer", PrimitiveType.INT);
    primitiveTypeCodes.put("int", PrimitiveType.INT);
    primitiveTypeCodes.put("short", PrimitiveType.SHORT);
    primitiveTypeCodes.put("double", PrimitiveType.DOUBLE);
    primitiveTypeCodes.put("long", PrimitiveType.LONG);
    primitiveTypeCodes.put("boolean", PrimitiveType.BOOLEAN);
    primitiveTypeCodes.put("byte", PrimitiveType.BYTE);
    primitiveTypeCodes.put("character", PrimitiveType.CHAR);
    primitiveTypeCodes.put("char", PrimitiveType.CHAR);
    primitiveTypeCodes.put("float", PrimitiveType.FLOAT);
    primitiveTypeCodes.put("void", PrimitiveType.VOID);

    // Publish an event to the bus
    eventBus.post(new PrimitiveTypeCodesCreatedEvent(primitiveTypeCodes));
}

From source file:lang.java.jdt.internal.JdtAstToRascalAstConverter.java

License:Open Source License

public boolean visit(PrimitiveType node) {
    IValue type;/*from  w  w  w .  j a va 2s  .co  m*/

    if (node.getPrimitiveTypeCode().equals(PrimitiveType.BOOLEAN)) {
        type = values.constructor(Java.CONS_BOOLEAN);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.BYTE)) {
        type = values.constructor(Java.CONS_BYTE);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.CHAR)) {
        type = values.constructor(Java.CONS_CHAR);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.DOUBLE)) {
        type = values.constructor(Java.CONS_DOUBLE);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.FLOAT)) {
        type = values.constructor(Java.CONS_FLOAT);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.INT)) {
        type = values.constructor(Java.CONS_INT);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.LONG)) {
        type = values.constructor(Java.CONS_LONG);
    } else if (node.getPrimitiveTypeCode().equals(PrimitiveType.SHORT)) {
        type = values.constructor(Java.CONS_SHORT);
    } else {
        type = values.constructor(Java.CONS_VOID);
    }

    ownValue = constructRascalNode(node, type);
    return false;
}

From source file:net.sf.j2s.core.astvisitors.ASTScriptVisitor.java

License:Open Source License

private String prepareSimpleSerializable(TypeDeclaration node, List bodyDeclarations) {
    StringBuffer fieldsSerializables = new StringBuffer();
    ITypeBinding binding = node.resolveBinding();
    boolean isSimpleSerializable = binding != null
            && (Bindings.findTypeInHierarchy(binding, "net.sf.j2s.ajax.SimpleSerializable") != null);
    for (Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
        ASTNode element = (ASTNode) iter.next();
        if (element instanceof FieldDeclaration) {
            if (node.isInterface()) {
                /*/* w  ww.  j av a2 s.  c o m*/
                 * As members of interface should be treated
                 * as final and for javascript interface won't
                 * get instantiated, so the member will be
                 * treated specially. 
                 */
                continue;
            }
            FieldDeclaration fieldDeclaration = (FieldDeclaration) element;

            if (isSimpleSerializable) {
                List fragments = fieldDeclaration.fragments();
                int modifiers = fieldDeclaration.getModifiers();
                if ((Modifier.isPublic(modifiers)/* || Modifier.isProtected(modifiers)*/)
                        && !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    Type type = fieldDeclaration.getType();
                    int dims = 0;
                    if (type.isArrayType()) {
                        dims = 1;
                        type = ((ArrayType) type).getComponentType();
                    }
                    String mark = null;
                    if (type.isPrimitiveType()) {
                        PrimitiveType pType = (PrimitiveType) type;
                        Code code = pType.getPrimitiveTypeCode();
                        if (code == PrimitiveType.FLOAT) {
                            mark = "F";
                        } else if (code == PrimitiveType.DOUBLE) {
                            mark = "D";
                        } else if (code == PrimitiveType.INT) {
                            mark = "I";
                        } else if (code == PrimitiveType.LONG) {
                            mark = "L";
                        } else if (code == PrimitiveType.SHORT) {
                            mark = "S";
                        } else if (code == PrimitiveType.BYTE) {
                            mark = "B";
                        } else if (code == PrimitiveType.CHAR) {
                            mark = "C";
                        } else if (code == PrimitiveType.BOOLEAN) {
                            mark = "b";
                        }
                    }
                    ITypeBinding resolveBinding = type.resolveBinding();
                    if ("java.lang.String".equals(resolveBinding.getQualifiedName())) {
                        mark = "s";
                    } else {
                        ITypeBinding t = resolveBinding;
                        do {
                            String typeName = t.getQualifiedName();
                            if ("java.lang.Object".equals(typeName)) {
                                break;
                            }
                            if ("net.sf.j2s.ajax.SimpleSerializable".equals(typeName)) {
                                mark = "O";
                                break;
                            }
                            t = t.getSuperclass();
                            if (t == null) {
                                break;
                            }
                        } while (true);
                    }
                    if (mark != null) {
                        for (Iterator xiter = fragments.iterator(); xiter.hasNext();) {
                            VariableDeclarationFragment var = (VariableDeclarationFragment) xiter.next();
                            int curDim = dims + var.getExtraDimensions();
                            if (curDim <= 1) {
                                if (fieldsSerializables.length() > 0) {
                                    fieldsSerializables.append(", ");
                                }
                                /*
                                 * Fixed bug for the following scenario:
                                 * class NT extends ... {
                                 *    public boolean typing;
                                 *    public void typing() {
                                 *    }
                                 * }
                                 */
                                String fieldName = var.getName().toString();
                                if (checkKeyworkViolation(fieldName)) {
                                    fieldName = "$" + fieldName;
                                }
                                String prefix = null;
                                if (binding != null && checkSameName(binding, fieldName)) {
                                    prefix = "$";
                                }
                                if (binding != null && isInheritedFieldName(binding, fieldName)) {
                                    fieldName = getFieldName(binding, fieldName);
                                }
                                if (prefix != null) {
                                    fieldName = prefix + fieldName;
                                }

                                fieldsSerializables.append("\"" + fieldName + "\", \"");
                                if (mark.charAt(0) == 's' && curDim == 1) {
                                    fieldsSerializables.append("AX");
                                } else if (curDim == 1) {
                                    fieldsSerializables.append("A");
                                    fieldsSerializables.append(mark);
                                } else {
                                    fieldsSerializables.append(mark);
                                }
                                fieldsSerializables.append("\"");
                            }
                        }
                    }
                }
            }
        }
    }
    return fieldsSerializables.toString();
}

From source file:net.sf.j2s.core.astvisitors.ASTTigerVisitor.java

License:Open Source License

protected void boxingNode(ASTNode element) {
    if (element instanceof Expression) {
        Expression exp = (Expression) element;
        if (exp.resolveBoxing()) {
            ITypeBinding typeBinding = exp.resolveTypeBinding();
            if (typeBinding.isPrimitive()) {
                String name = typeBinding.getName();
                Code type = PrimitiveType.toCode(name);
                String primitiveTypeName = null;
                if (type == PrimitiveType.INT) {
                    primitiveTypeName = "Integer";
                } else if (type == PrimitiveType.LONG) {
                    primitiveTypeName = "Long";
                } else if (type == PrimitiveType.FLOAT) {
                    primitiveTypeName = "Float";
                } else if (type == PrimitiveType.DOUBLE) {
                    primitiveTypeName = "Double";
                } else if (type == PrimitiveType.BOOLEAN) {
                    primitiveTypeName = "Boolean";
                } else if (type == PrimitiveType.BYTE) {
                    primitiveTypeName = "Byte";
                } else if (type == PrimitiveType.SHORT) {
                    primitiveTypeName = "Short";
                } else if (type == PrimitiveType.CHAR) {
                    primitiveTypeName = "Character";
                }/*from  w  w  w . j  a  va2s  .c om*/
                if (primitiveTypeName != null) {
                    getBuffer().append("new " + primitiveTypeName + " (");
                    element.accept(this.visitor);
                    getBuffer().append(")");
                    return;
                }
            }
        } else if (exp.resolveUnboxing()) {
            ITypeBinding typeBinding = exp.resolveTypeBinding();
            if (!typeBinding.isPrimitive()) {
                String name = typeBinding.getQualifiedName();
                String primitiveName = null;
                if ("java.lang.Integer".equals(name)) {
                    primitiveName = "int";
                } else if ("java.lang.Long".equals(name)) {
                    primitiveName = "long";
                } else if ("java.lang.Float".equals(name)) {
                    primitiveName = "float";
                } else if ("java.lang.Double".equals(name)) {
                    primitiveName = "double";
                } else if ("java.lang.Boolean".equals(name)) {
                    primitiveName = "boolean";
                } else if ("java.lang.Byte".equals(name)) {
                    primitiveName = "byte";
                } else if ("java.lang.Short".equals(name)) {
                    primitiveName = "short";
                } else if ("java.lang.Character".equals(name)) {
                    primitiveName = "char";
                }

                if (primitiveName != null) {
                    getBuffer().append("(");
                    element.accept(this.visitor);
                    getBuffer().append(")." + primitiveName + "Value ()");
                    return;
                }
            }
        }
    }
    element.accept(this.visitor);
}

From source file:org.decojer.cavaj.utils.Expressions.java

License:Open Source License

/**
 * New type./*from  ww w. java  2 s  .c  om*/
 *
 * @param t
 *            type
 * @param context
 *            context
 * @return AST type
 */
@SuppressWarnings("deprecation")
public static Type newType(@Nonnull final T t, @Nonnull final Element context) {
    final AST ast = context.getCu().getAst();
    // handle array first because annot(array()) is special
    if (t.isArray()) {
        if (ast.apiLevel() <= AST.JLS4) {
            final T componentT = t.getComponentT();
            assert componentT != null;
            return ast.newArrayType(newType(componentT, context));
        }
        final T elementT = t.getElementT();
        assert elementT != null;
        for (T checkT = t; checkT != null && checkT.isArray(); checkT = checkT.getComponentT()) {
            if (checkT.isAnnotated()) {
                final ArrayType arrayType = ast.newArrayType(newType(elementT, context));
                final List<Dimension> dimensions = arrayType.dimensions();
                dimensions.clear();
                for (T componentT = t; componentT != null
                        && componentT.isArray(); componentT = componentT.getComponentT()) {
                    final Dimension dimension = ast.newDimension();
                    final List<IExtendedModifier> annotations = dimension.annotations();
                    assert annotations != null;
                    if (componentT.isAnnotated()) {
                        Annotations.decompileAnnotations(componentT, annotations, context);
                    }
                    dimensions.add(dimension);
                }
                return arrayType;
            }
        }
        return ast.newArrayType(newType(elementT, context), t.getDimensions());
    }
    if (t.isAnnotated()) {
        Type type = newType(t.getRawT(), context);
        if (ast.apiLevel() <= AST.JLS4) {
            log.warn("Cannot decompile type annotations for type '" + t + "' in Eclipse AST JLS4!");
            return type;
        }
        // parameterized type is not directly annotateable in Eclipse; but DecoJer thinks the
        // whole type is meant, not just the generic type, hence translate here
        AnnotatableType annotatableType = (AnnotatableType) (type instanceof ParameterizedType
                ? ((ParameterizedType) type).getType()
                : type);
        qualified: if (annotatableType instanceof SimpleType) {
            // direct annotation of qualified types adds the annotations as first element,
            // strange Java spec doesn't allow "@A package.Name" but wants "package.@A Name"
            final Name typeName = ((SimpleType) annotatableType).getName();
            if (!(typeName instanceof QualifiedName)) {
                break qualified;
            }
            final Name qualifier = ((QualifiedName) typeName).getQualifier();
            final SimpleName name = ((QualifiedName) typeName).getName();
            // cannot delete mandory childs, copy them
            annotatableType = ast.newNameQualifiedType((Name) ASTNode.copySubtree(ast, qualifier),
                    (SimpleName) ASTNode.copySubtree(ast, name));
            if (type instanceof ParameterizedType) {
                ((ParameterizedType) type).setType(annotatableType);
            } else {
                type = annotatableType;
            }
        }
        final List<IExtendedModifier> annotations = annotatableType.annotations();
        assert annotations != null;
        Annotations.decompileAnnotations(t, annotations, context);
        return type;
    }
    // doesn't work, now with Dimension (see above): if (t.isArray()) { return
    // ast.newArrayType(newType(t.getComponentT(), contextT)); }
    if (t.isParameterized()) {
        final T genericT = t.getGenericT();
        assert genericT != null;
        final ParameterizedType parameterizedType = ast.newParameterizedType(newType(genericT, context));
        for (final T typeArg : t.getTypeArgs()) {
            assert typeArg != null;
            parameterizedType.typeArguments().add(newType(typeArg, context));
        }
        return parameterizedType;
    }
    if (t.isWildcard()) {
        final T boundT = t.getBoundT();
        if (boundT == null) {
            return ast.newWildcardType();
        }
        if (t.isSubclassOf()) {
            final WildcardType wildcardType = ast.newWildcardType();
            // default...newWildcardType.setUpperBound(true);
            wildcardType.setBound(newType(boundT, context));
            return wildcardType;
        }
        final WildcardType wildcardType = ast.newWildcardType();
        wildcardType.setUpperBound(false);
        wildcardType.setBound(newType(boundT, context));
        return wildcardType;
    }
    if (t.isMulti()) {
        log.warn("Convert type for multi-type '" + t + "'!");
        // prefer boolean for multi-type with 0 or 1, synchronous to newLiteral()!
        // prefer byte before char if no explicit char type given
    }
    if (t.is(T.BOOLEAN)) {
        return ast.newPrimitiveType(PrimitiveType.BOOLEAN);
    }
    if (t.is(T.BYTE)) {
        return ast.newPrimitiveType(PrimitiveType.BYTE);
    }
    if (t.is(T.CHAR)) {
        return ast.newPrimitiveType(PrimitiveType.CHAR);
    }
    if (t.is(T.SHORT)) {
        return ast.newPrimitiveType(PrimitiveType.SHORT);
    }
    if (t.is(T.INT)) {
        return ast.newPrimitiveType(PrimitiveType.INT);
    }
    if (t.is(T.FLOAT)) {
        return ast.newPrimitiveType(PrimitiveType.FLOAT);
    }
    if (t.is(T.LONG)) {
        return ast.newPrimitiveType(PrimitiveType.LONG);
    }
    if (t.is(T.DOUBLE)) {
        return ast.newPrimitiveType(PrimitiveType.DOUBLE);
    }
    if (t.is(T.VOID)) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    if (t.isQualified()) {
        final T qualifierT = t.getQualifierT();
        assert qualifierT != null : "cannot be null for qualified";
        // could be ParamT etc., not decompileable with name as target;
        // restrict qualifications to really necessary enclosings:
        // t = Outer.Inner.InnerInner, t = Outer.Inner ==> Inner
        final T contextT = context.getT();
        assert contextT != null;
        if (contextT.getFullName().startsWith(qualifierT.getFullName())) {
            // TODO full name has too much info yet (like annotations)
            return ast.newSimpleType(newSimpleName(t.getSimpleIdentifier(), ast));
        }
        return ast.newQualifiedType(newType(qualifierT, context), newSimpleName(t.getSimpleIdentifier(), ast));
    }
    // else fall through...
    return ast.newSimpleType(newTypeName(t, context));
}

From source file:org.eclipse.andmore.android.generateviewbylayout.codegenerators.RatingBarCodeGenerator.java

License:Apache License

/**
 * Adds methods (event handler) for RatingBar
 * //from   www .j  av  a 2s  . c  om
 * <br>
 * GENERATED_CODE_FORMAT: <br>
 * $GUI_ID.setOnRatingBarChangeListener(new OnRatingBarChangeListener() { <br>
 * public void onRatingChanged(RatingBar ratingBar, float rating, boolean
 * fromUser) { <br>
 * } <br>
 * });
 * 
 * @param monitor
 */
private void addOnRatingBarChangeListener(IProgressMonitor monitor) throws JavaModelException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    subMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_AddingRatingBarHandler,
            codeGeneratorData.getGuiItems().size());
    for (LayoutNode node : codeGeneratorData.getGuiItems()) {
        if (node.shouldInsertCode()
                && node.getNodeType().equals(LayoutNode.LayoutNodeViewType.RatingBar.name())) {
            boolean containMethodDeclared = checkIfInvokeMethodIsDeclared(node,
                    JavaViewBasedOnLayoutModifierConstants.SET_ON_RATING_BAR_CHANGE_LISTENER);
            if (!containMethodDeclared) {
                List<SingleVariableDeclaration> parameters1 = new ArrayList<SingleVariableDeclaration>();
                SingleVariableDeclaration param1 = createVariableDeclarationFromStrings(
                        LayoutNode.LayoutNodeViewType.RatingBar.name(),
                        JavaViewBasedOnLayoutModifierConstants.RATING_BAR_VARIABLE);
                parameters1.add(param1);
                SingleVariableDeclaration param2 = createVariableDeclarationPrimitiveCode(PrimitiveType.FLOAT,
                        JavaViewBasedOnLayoutModifierConstants.RATING_VARIABLE);
                parameters1.add(param2);
                SingleVariableDeclaration param3 = createVariableDeclarationPrimitiveCode(PrimitiveType.BOOLEAN,
                        JavaViewBasedOnLayoutModifierConstants.FROM_USER_VARIABLE);
                parameters1.add(param3);
                MethodDeclaration methodDeclaration1 = addMethodDeclaration(ModifierKeyword.PUBLIC_KEYWORD,
                        JavaViewBasedOnLayoutModifierConstants.ON_RATING_CHANGED, PrimitiveType.VOID,
                        parameters1);
                Block block1 = onCreateDeclaration.getAST().newBlock();
                methodDeclaration1.setBody(block1);

                addMethodInvocationToListenerHandler(node.getNodeId(),
                        JavaViewBasedOnLayoutModifierConstants.SET_ON_RATING_BAR_CHANGE_LISTENER,
                        LayoutNode.LayoutNodeViewType.RatingBar.name(),
                        JavaViewBasedOnLayoutModifierConstants.ON_RATING_BAR_CHANGE_LISTENER,
                        methodDeclaration1);
            }
        }
        subMonitor.worked(1);
    }
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

protected PrimitiveType.Code getPrimitiveTypeCode(char[] name) {
    switch (name[0]) {
    case 'i':
        if (name.length == 3 && name[1] == 'n' && name[2] == 't') {
            return PrimitiveType.INT;
        }/*from  ww w  .  java  2 s. com*/
        break;
    case 'l':
        if (name.length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') {
            return PrimitiveType.LONG;
        }
        break;
    case 'd':
        if (name.length == 6 && name[1] == 'o' && name[2] == 'u' && name[3] == 'b' && name[4] == 'l'
                && name[5] == 'e') {
            return PrimitiveType.DOUBLE;
        }
        break;
    case 'f':
        if (name.length == 5 && name[1] == 'l' && name[2] == 'o' && name[3] == 'a' && name[4] == 't') {
            return PrimitiveType.FLOAT;
        }
        break;
    case 'b':
        if (name.length == 4 && name[1] == 'y' && name[2] == 't' && name[3] == 'e') {
            return PrimitiveType.BYTE;
        } else if (name.length == 7 && name[1] == 'o' && name[2] == 'o' && name[3] == 'l' && name[4] == 'e'
                && name[5] == 'a' && name[6] == 'n') {
            return PrimitiveType.BOOLEAN;
        }
        break;
    case 'c':
        if (name.length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r') {
            return PrimitiveType.CHAR;
        }
        break;
    case 's':
        if (name.length == 5 && name[1] == 'h' && name[2] == 'o' && name[3] == 'r' && name[4] == 't') {
            return PrimitiveType.SHORT;
        }
        break;
    case 'v':
        if (name.length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd') {
            return PrimitiveType.VOID;
        }
    }
    return null; // cannot be reached
}

From source file:org.evosuite.testcarver.codegen.JUnitCodeGenerator.java

License:Open Source License

private Type createAstArrayType(final String type, final AST ast) {
    // NOTE: see asm4 guide p. 11 for more insights about internal type representation

    final int arrayDim = type.lastIndexOf('[') + 1;

    if (type.contains("[L")) {
        // --- object array

        // TODO use regex for extraction

        String extractedType = type.substring(type.indexOf('L') + 1, type.length() - 1);
        extractedType = extractedType.replaceFirst("java\\.lang\\.", "");
        extractedType = extractedType.replace('$', '.');

        return ast.newArrayType(this.createAstType(extractedType, ast), arrayDim);
    } else {//  w  ww.  j a  v a2 s .c  om
        // --- primitive type array

        if (type.contains("[I")) // int[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.INT), arrayDim);
        } else if (type.contains("[B")) // byte[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.BYTE), arrayDim);
        } else if (type.contains("[C")) // char[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.CHAR), arrayDim);

        } else if (type.contains("[D")) // double[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.DOUBLE), arrayDim);
        } else if (type.contains("[Z")) // boolean[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.BOOLEAN), arrayDim);
        } else if (type.contains("[F")) // float[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.FLOAT), arrayDim);
        } else if (type.contains("[S")) // short[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.SHORT), arrayDim);
        } else if (type.contains("[J")) // long[]
        {
            return ast.newArrayType(ast.newPrimitiveType(PrimitiveType.LONG), arrayDim);
        } else {
            throw new RuntimeException("Can not create array type for " + type);
        }
    }
}

From source file:org.evosuite.testcarver.codegen.JUnitCodeGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//ww w .j  av a2  s  . c o m
public void createMethodCallStmt(CaptureLog log, int logRecNo) {
    PostProcessor.notifyRecentlyProcessedLogRecNo(logRecNo);

    // assumption: all necessary statements are created and there is one variable for reach referenced object
    final int oid = log.objectIds.get(logRecNo);
    Object[] methodArgs = log.params.get(logRecNo);
    final String methodName = log.methodNames.get(logRecNo);

    final String methodDesc = log.descList.get(logRecNo);
    org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc);

    Class<?>[] methodParamTypeClasses = new Class[methodParamTypes.length];
    for (int i = 0; i < methodParamTypes.length; i++) {
        methodParamTypeClasses[i] = getClassForName(methodParamTypes[i].getClassName());
    }

    final String typeName = log.oidClassNames.get(log.oidRecMapping.get(oid));
    Class<?> type = getClassForName(typeName);

    final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer...

    final Statement finalStmt;

    @SuppressWarnings("rawtypes")
    final List arguments;
    if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
        /*
         * Person var0 = null;
         * {
         *    var0 = new Person();
         * }
         * catch(Throwable t)
         * {
         *    org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>);
         * }
         */

        // e.g. Person var0 = null;
        final String varName = this.createNewVarName(oid, typeName);
        VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName(varName));
        VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
        stmt.setType(this.createAstType(typeName, ast));
        vd.setInitializer(ast.newNullLiteral());
        methodBlock.statements().add(stmt);

        //FIXME this does not make any sense
        try {
            this.getConstructorModifiers(type, methodParamTypeClasses);
        } catch (Exception e) {
            logger.error("" + e, e);
        }

        final int constructorTypeModifiers = this.getConstructorModifiers(type, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(constructorTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        if (isReflectionAccessNeeded) {
            this.isNewInstanceMethodNeeded = true;
            final MethodInvocation mi = this.createCallMethodOrNewInstanceCallStmt(true, ast, varName, typeName,
                    methodName, methodArgs, methodParamTypes);
            arguments = null;

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);

            final CastExpression cast = ast.newCastExpression();
            cast.setType(this.createAstType(typeName, ast));
            cast.setExpression(mi);
            assignment.setRightHandSide(cast);

            finalStmt = ast.newExpressionStatement(assignment);
        } else {
            // e.g. var0 = new Person();
            final ClassInstanceCreation ci = ast.newClassInstanceCreation();

            final int recNo = log.oidRecMapping.get(oid);
            final int dependencyOID = log.dependencies.getQuick(recNo);

            if (dependencyOID == CaptureLog.NO_DEPENDENCY) {
                ci.setType(this.createAstType(typeName, ast));
            } else {
                //               final String varTypeName = oidToVarMapping.get(dependencyOID) + "." + typeName.substring(typeName.indexOf('$') + 1);
                //               ci.setType(this.createAstType(varTypeName, ast));
                /*
                 * e.g.
                 * OuterClass.InnerClass innerObject = outerObject.new InnerClass();
                 */
                ci.setType(this.createAstType(typeName.substring(typeName.indexOf('$') + 1), ast));
                ci.setExpression(ast.newSimpleName(oidToVarMapping.get(dependencyOID)));

                final int index = Arrays.binarySearch(methodArgs, dependencyOID);

                if (index > -1) {
                    logger.debug(varName + " xxxx3 " + index);

                    final Object[] newArgs = new Object[methodArgs.length - 1];
                    System.arraycopy(methodArgs, 0, newArgs, 0, index);
                    System.arraycopy(methodArgs, index + 1, newArgs, index, methodArgs.length - index - 1);
                    methodArgs = newArgs;

                    final Class<?>[] newParamTypeClasses = new Class<?>[methodParamTypeClasses.length - 1];
                    System.arraycopy(methodParamTypeClasses, 0, newParamTypeClasses, 0, index);
                    System.arraycopy(methodParamTypeClasses, index + 1, newParamTypeClasses, index,
                            methodParamTypeClasses.length - index - 1);
                    methodParamTypeClasses = newParamTypeClasses;

                    final org.objectweb.asm.Type[] newParamTypes = new org.objectweb.asm.Type[methodParamTypes.length
                            - 1];
                    System.arraycopy(methodParamTypes, 0, newParamTypes, 0, index);
                    System.arraycopy(methodParamTypes, index + 1, newParamTypes, index,
                            methodParamTypes.length - index - 1);
                    methodParamTypes = newParamTypes;
                }
            }

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);
            assignment.setRightHandSide(ci);

            finalStmt = ast.newExpressionStatement(assignment);
            arguments = ci.arguments();
        }
    } else //------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
    {
        String returnVarName = null;

        final String desc = log.descList.get(logRecNo);
        final String returnType = org.objectweb.asm.Type.getReturnType(desc).getClassName();

        final Object returnValue = log.returnValues.get(logRecNo);
        if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
            Integer returnValueOID = (Integer) returnValue;

            // e.g. Person var0 = null;
            returnVarName = this.createNewVarName(returnValueOID, returnType);

            VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
            vd.setName(ast.newSimpleName(returnVarName));
            VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
            stmt.setType(this.createAstType(returnType, ast));
            vd.setInitializer(ast.newNullLiteral());
            methodBlock.statements().add(stmt);
        }

        final String varName = this.oidToVarMapping.get(oid);
        final int methodTypeModifiers = this.getMethodModifiers(type, methodName, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(methodTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        // e.g. Person var0 = var1.getPerson("Ben");

        final MethodInvocation mi;

        if (isReflectionAccessNeeded) {
            this.isCallMethodMethodNeeded = true;
            mi = this.createCallMethodOrNewInstanceCallStmt(false, ast, varName, typeName, methodName,
                    methodArgs, methodParamTypes);
            arguments = null;

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);

                final CastExpression cast = ast.newCastExpression();
                cast.setType(this.createAstType(returnType, ast));
                cast.setExpression(mi);
                assignment.setRightHandSide(cast);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        } else {
            mi = ast.newMethodInvocation();

            if (log.isStaticCallList.get(logRecNo)) {
                // can only happen, if this is a static method call (because constructor statement has been reported)
                final String tmpType = log.oidClassNames.get(log.oidRecMapping.get(oid));
                mi.setExpression(ast.newName(tmpType.split("\\.")));
            } else {
                try {
                    mi.setExpression(ast.newSimpleName(varName));
                } catch (final IllegalArgumentException ex) {

                    String msg = "";

                    msg += "--recno-- " + logRecNo + "\n";
                    msg += "--oid-- " + oid + "\n";
                    msg += "--method-- " + methodName + "\n";
                    msg += "--varName-- " + varName + "\n";
                    msg += "--oidToVarMap-- " + this.oidToVarMapping + "\n";
                    msg += (log) + "\n";

                    logger.error(msg);
                    throw new RuntimeException(msg);
                }
            }

            mi.setName(ast.newSimpleName(methodName));

            arguments = mi.arguments();

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);
                assignment.setRightHandSide(mi);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        }
    }

    if (postprocessing) {
        final TryStatement tryStmt = this.createTryStatementForPostProcessing(ast, finalStmt, logRecNo);
        methodBlock.statements().add(tryStmt);
    } else {
        if (this.failedRecords.contains(logRecNo)) {
            // we just need an empty catch block to preserve program flow
            final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, finalStmt);
            methodBlock.statements().add(tryStmt);
        } else {
            methodBlock.statements().add(finalStmt);
        }
    }

    if (arguments != null) {
        Class<?> methodParamType;
        Class<?> argType;

        Integer arg; // is either an oid or null
        for (int i = 0; i < methodArgs.length; i++) {
            arg = (Integer) methodArgs[i];
            if (arg == null) {
                arguments.add(ast.newNullLiteral());
            } else {
                methodParamType = CaptureUtil.getClassFromDesc(methodParamTypes[i].getDescriptor());
                argType = this.oidToTypeMapping.get(arg);

                // TODO: Warten was Florian und Gordon dazu sagen. Siehe Mail 04.08.2012
                if (argType == null) {
                    logger.error(
                            "Call within constructor needs instance of enclosing object as parameter -> ignored: "
                                    + arg);
                    methodBlock.statements().remove(methodBlock.statements().size() - 1);
                    return;
                }

                final CastExpression cast = ast.newCastExpression();

                if (methodParamType.isPrimitive()) {
                    // cast to ensure that right method is called
                    // --> see doSth(int) and doSth(Integer)

                    if (methodParamType.equals(boolean.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.BOOLEAN));
                    } else if (methodParamType.equals(byte.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.BYTE));
                    } else if (methodParamType.equals(char.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.CHAR));
                    } else if (methodParamType.equals(double.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.DOUBLE));
                    } else if (methodParamType.equals(float.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.FLOAT));
                    } else if (methodParamType.equals(int.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.INT));
                    } else if (methodParamType.equals(long.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.LONG));
                    } else if (methodParamType.equals(short.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.SHORT));
                    } else {
                        throw new RuntimeException("unknown primitive type: " + methodParamType);
                    }

                } else {
                    // we need an up-cast
                    if (methodParamType.getName().contains(".")) {
                        cast.setType(this.createAstType(methodParamType.getName(), ast));
                    } else {
                        cast.setType(createAstType(methodParamType.getName(), ast));
                    }
                }

                cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg)));
                arguments.add(cast);
            }
        }
    }
}