Java Code Examples for org.codehaus.groovy.ast.ClassHelper#isPrimitiveType()

The following examples show how to use org.codehaus.groovy.ast.ClassHelper#isPrimitiveType() . 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: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Statement createConstructorStatementDefault(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final ClassNode fType = fNode.getType();
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = assignS(fieldExpr, castX(fType, param));
    if (shouldNullCheck) {
        assignStmt = ifElseS(equalsNullX(param), NullCheckASTTransformation.makeThrowStmt(fNode.getName()), assignStmt);
    }
    Expression initExpr = fNode.getInitialValueExpression();
    Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        if (ClassHelper.isPrimitiveType(fType)) {
            assignInit = EmptyStatement.INSTANCE;
        } else {
            assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
        }
    } else {
        assignInit = assignS(fieldExpr, initExpr);
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example 2
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void writePostOrPrefixMethod(final int op, final String method, final Expression expression, final Expression orig) {
    MethodNode mn = orig.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (mn != null) {
        controller.getOperandStack().pop();
        MethodCallExpression call = callX(expression, method);
        call.setMethodTarget(mn);
        call.visit(controller.getAcg());
        return;
    }

    ClassNode top = controller.getOperandStack().getTopOperand();
    if (ClassHelper.isPrimitiveType(top) && (ClassHelper.isNumberType(top) || char_TYPE.equals(top))) {
        MethodVisitor mv = controller.getMethodVisitor();
        visitInsnByType(top, mv, ICONST_1, LCONST_1, FCONST_1, DCONST_1);
        if ("next".equals(method)) {
            visitInsnByType(top, mv, IADD, LADD, FADD, DADD);
        } else {
            visitInsnByType(top, mv, ISUB, LSUB, FSUB, DSUB);
        }
        return;
    }

    super.writePostOrPrefixMethod(op, method, expression, orig);
}
 
Example 3
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void loadThis(final VariableExpression thisOrSuper) {
    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    if (controller.isInGeneratedFunction() && !controller.getCompileStack().isImplicitThis()) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Closure", "getThisObject", "()Ljava/lang/Object;", false);
        ClassNode expectedType = controller.getTypeChooser().resolveType(thisOrSuper, controller.getOutermostClass());
        if (!ClassHelper.OBJECT_TYPE.equals(expectedType) && !ClassHelper.isPrimitiveType(expectedType)) {
            BytecodeHelper.doCast(mv, expectedType);
            controller.getOperandStack().push(expectedType);
        } else {
            controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
        }
    } else {
        controller.getOperandStack().push(controller.getClassNode());
    }
}
 
Example 4
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void printDefaultValue(PrintWriter out, ClassNode type) {
    if (type.redirect() != ClassHelper.OBJECT_TYPE && type.redirect() != ClassHelper.boolean_TYPE) {
        out.print("(");
        printType(out, type);
        out.print(")");
    }

    if (ClassHelper.isPrimitiveType(type)) {
        if (type == ClassHelper.boolean_TYPE) {
            out.print("false");
        } else {
            out.print("0");
        }
    } else {
        out.print("null");
    }
}
 
Example 5
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(final GroovyCodeVisitor visitor) {
    receiver.visit(visitor);
    if (visitor instanceof AsmClassGenerator) {
        ClassNode topOperand = controller.getOperandStack().getTopOperand();
        ClassNode type = getType();
        if (ClassHelper.GSTRING_TYPE.equals(topOperand) && ClassHelper.STRING_TYPE.equals(type)) {
            // perform regular type conversion
            controller.getOperandStack().doGroovyCast(type);
            return;
        }
        if (ClassHelper.isPrimitiveType(topOperand) && !ClassHelper.isPrimitiveType(type)) {
            controller.getOperandStack().box();
        } else if (!ClassHelper.isPrimitiveType(topOperand) && ClassHelper.isPrimitiveType(type)) {
            controller.getOperandStack().doGroovyCast(type);
        }
        if (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(topOperand, type)) return;
        controller.getMethodVisitor().visitTypeInsn(CHECKCAST, type.isArray()
                ? BytecodeHelper.getTypeDescription(type)
                : BytecodeHelper.getClassInternalName(type.getName()));
        controller.getOperandStack().replace(type);
    }
}
 
Example 6
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static void visitField(ErrorCollecting xform, AnnotationNode node, FieldNode fieldNode) {
    final Expression soft = node.getMember("soft");
    final Expression init = getInitExpr(xform, fieldNode);

    String backingFieldName = "$" + fieldNode.getName();
    fieldNode.rename(backingFieldName);
    fieldNode.setModifiers(ACC_PRIVATE | ACC_SYNTHETIC | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED))));
    PropertyNode pNode = fieldNode.getDeclaringClass().getProperty(backingFieldName);
    if (pNode != null) {
        fieldNode.getDeclaringClass().getProperties().remove(pNode);
    }

    if (soft instanceof ConstantExpression && ((ConstantExpression) soft).getValue().equals(true)) {
        createSoft(fieldNode, init);
    } else {
        create(fieldNode, init);
        // @Lazy not meaningful with primitive so convert to wrapper if needed
        if (ClassHelper.isPrimitiveType(fieldNode.getType())) {
            fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType()));
        }
    }
}
 
Example 7
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustMethod(MethodNode mn, boolean includeGenerated) {
    BlockStatement newCode = getCodeAsBlock(mn);
    if (mn.getParameters().length == 0) return;
    boolean generated = isGenerated(mn);
    int startingIndex = 0;
    if (!includeGenerated && generated) return;
    if (isMarkedAsProcessed(mn)) return;
    if (mn instanceof ConstructorNode) {
        // some transform has been here already and we assume it knows what it is doing
        if (mn.getFirstStatement() instanceof BytecodeSequence) return;
        // ignore any constructors calling this(...) or super(...)
        ConstructorCallExpression cce = ConstructorNodeUtils.getFirstIfSpecialConstructorCall(mn.getCode());
        if (cce != null) {
            if (generated) {
                return;
            } else {
                startingIndex = 1; // skip over this/super() call
            }
        }
    }
    for (Parameter p : mn.getParameters()) {
        if (ClassHelper.isPrimitiveType(p.getType())) continue;
        newCode.getStatements().add(startingIndex, ifS(isNullX(varX(p)), makeThrowStmt(p.getName())));
    }
    mn.setCode(newCode);
}
 
Example 8
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean isKnownImmutableType(ClassNode fieldType, List<String> knownImmutableClasses) {
    if (builtinOrDeemedType(fieldType, knownImmutableClasses))
        return true;
    if (!fieldType.isResolved())
        return false;
    if ("java.util.Optional".equals(fieldType.getName()) && fieldType.getGenericsTypes() != null && fieldType.getGenericsTypes().length == 1) {
        GenericsType optionalType = fieldType.getGenericsTypes()[0];
        if (optionalType.isResolved() && !optionalType.isPlaceholder() && !optionalType.isWildcard()) {
            ClassNode valueType = optionalType.getType();
            if (builtinOrDeemedType(valueType, knownImmutableClasses)) return true;
            if (valueType.isEnum()) return true;
        }
    }
    return fieldType.isEnum() ||
            ClassHelper.isPrimitiveType(fieldType) ||
            hasImmutableAnnotation(fieldType);
}
 
Example 9
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void printDefaultValue(PrintWriter out, ClassNode type) {
    if (type.redirect() != ClassHelper.OBJECT_TYPE) {
        out.print("(");
        printType(type, out);
        out.print(")");
    }

    if (ClassHelper.isPrimitiveType(type)) {
        if (type == ClassHelper.boolean_TYPE) {
            out.print("false");
        } else {
            out.print("0");
        }
    } else {
        out.print("null");
    }
}
 
Example 10
Source File: TupleConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression providedOrDefaultInitialValue(FieldNode fNode) {
    Expression initialExp = fNode.getInitialExpression() != null ? fNode.getInitialExpression() : nullX();
    final ClassNode paramType = fNode.getType();
    if (ClassHelper.isPrimitiveType(paramType) && isNull(initialExp)) {
        initialExp = primitivesInitialValues.get(paramType.getTypeClass());
    }
    return initialExp;
}
 
Example 11
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean matchWithOrWithourBoxing(final ClassNode argType, final Class aClass) {
    final boolean match;
    ClassNode type = ClassHelper.make(aClass);
    if (ClassHelper.isPrimitiveType(type) && !ClassHelper.isPrimitiveType(argType)) {
        type = ClassHelper.getWrapper(type);
    } else if (ClassHelper.isPrimitiveType(argType) && !ClassHelper.isPrimitiveType(type)) {
        type = ClassHelper.getUnwrapper(type);
    }
    match = argType.equals(type);
    return match;
}
 
Example 12
Source File: CompareToNullExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(final GroovyCodeVisitor visitor) {
    if (visitor instanceof AsmClassGenerator) {
        AsmClassGenerator acg = (AsmClassGenerator) visitor;
        WriterController controller = acg.getController();
        MethodVisitor mv = controller.getMethodVisitor();
        objectExpression.visit(acg);
        ClassNode top = controller.getOperandStack().getTopOperand();
        if (ClassHelper.isPrimitiveType(top)) {
            controller.getOperandStack().pop();
            mv.visitInsn(equalsNull ? ICONST_0 : ICONST_1);
            controller.getOperandStack().push(ClassHelper.boolean_TYPE);
            return;
        }
        Label zero = new Label();
        mv.visitJumpInsn(equalsNull ? IFNONNULL : IFNULL, zero);
        mv.visitInsn(ICONST_1);
        Label end = new Label();
        mv.visitJumpInsn(GOTO, end);
        mv.visitLabel(zero);
        mv.visitInsn(ICONST_0);
        mv.visitLabel(end);
        controller.getOperandStack().replace(ClassHelper.boolean_TYPE);
    } else {
        super.visit(visitor);
    }
}
 
Example 13
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void doCast(MethodVisitor mv, ClassNode type) {
    if (type == ClassHelper.OBJECT_TYPE) return;
    if (ClassHelper.isPrimitiveType(type) && type != VOID_TYPE) {
        unbox(mv, type);
    } else {
        mv.visitTypeInsn(
                CHECKCAST,
                type.isArray() ?
                        BytecodeHelper.getTypeDescription(type) :
                        BytecodeHelper.getClassInternalName(type.getName()));
    }
}
 
Example 14
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void writeGenericsBoundType(StringBuilder ret, ClassNode printType, boolean writeInterfaceMarker) {
    if (writeInterfaceMarker && printType.isInterface()) ret.append(":");
    if (printType.isGenericsPlaceHolder() && printType.getGenericsTypes()!=null) {
        ret.append("T");
        ret.append(printType.getGenericsTypes()[0].getName());
        ret.append(";");
    }
    else {
        ret.append(getTypeDescription(printType, false));
        addSubTypes(ret, printType.getGenericsTypes(), "<", ">");
        if (!ClassHelper.isPrimitiveType(printType)) ret.append(";");
    }
}
 
Example 15
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the bytecode to autobox the current value on the stack.
 */
@Deprecated
public static boolean box(MethodVisitor mv, ClassNode type) {
    if (ClassHelper.isPrimitiveType(type) && !ClassHelper.VOID_TYPE.equals(type)) {
        box(mv, BytecodeHelper.getTypeDescription(type));
        return true;
    }
    return false;
}
 
Example 16
Source File: OperandStack.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void doConvertAndCast(ClassNode targetType, boolean coerce) {
    int size = stack.size();
    throwExceptionForNoStackElement(size, targetType, coerce);

    ClassNode top = stack.get(size-1);
    targetType = targetType.redirect();
    if (targetType == top) return;

    if (coerce) {
        controller.getInvocationWriter().coerce(top,targetType);
        return;
    }

    boolean primTarget = ClassHelper.isPrimitiveType(targetType);
    boolean primTop = ClassHelper.isPrimitiveType(top);

    if (primTop && primTarget) {
        // here we box and unbox to get the goal type
        if (convertPrimitive(top, targetType)) {
            replace(targetType);
            return;
        }
        box();
    } else if (primTarget) {
        // top is not primitive so unbox
        // leave that BH#doCast later
    } else {
        // top might be primitive, target is not
        // so let invocation writer box if needed and do groovy cast otherwise
        controller.getInvocationWriter().castToNonPrimitiveIfNecessary(top, targetType);
    }

    MethodVisitor mv = controller.getMethodVisitor();
    if (primTarget && !ClassHelper.boolean_TYPE.equals(targetType) && !primTop && ClassHelper.getWrapper(targetType).equals(top)) {
        BytecodeHelper.doCastToPrimitive(mv, top, targetType);
    } else {
        top = stack.get(size-1);
        if (!WideningCategories.implementsInterfaceOrSubclassOf(top, targetType)) {
            BytecodeHelper.doCast(mv,targetType);
        }
    }
    replace(targetType);
}
 
Example 17
Source File: StaticTypesStatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void loadFromArray(MethodVisitor mv, BytecodeVariable variable, int array, int iteratorIdx) {
    OperandStack os = controller.getOperandStack();
    mv.visitVarInsn(ALOAD, array);
    mv.visitVarInsn(ILOAD, iteratorIdx);

    ClassNode varType = variable.getType();
    boolean primitiveType = ClassHelper.isPrimitiveType(varType);
    boolean isByte = ClassHelper.byte_TYPE.equals(varType);
    boolean isShort = ClassHelper.short_TYPE.equals(varType);
    boolean isInt = ClassHelper.int_TYPE.equals(varType);
    boolean isLong = ClassHelper.long_TYPE.equals(varType);
    boolean isFloat = ClassHelper.float_TYPE.equals(varType);
    boolean isDouble = ClassHelper.double_TYPE.equals(varType);
    boolean isChar = ClassHelper.char_TYPE.equals(varType);
    boolean isBoolean = ClassHelper.boolean_TYPE.equals(varType);

    if (primitiveType) {
        if (isByte) {
            mv.visitInsn(BALOAD);
        }
        if (isShort) {
            mv.visitInsn(SALOAD);
        }
        if (isInt || isChar || isBoolean) {
            mv.visitInsn(isChar ? CALOAD : isBoolean ? BALOAD : IALOAD);
        }
        if (isLong) {
            mv.visitInsn(LALOAD);
        }
        if (isFloat) {
            mv.visitInsn(FALOAD);
        }
        if (isDouble) {
            mv.visitInsn(DALOAD);
        }
    } else {
        mv.visitInsn(AALOAD);
    }
    os.push(varType);
    os.storeVar(variable);
}
 
Example 18
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void visitExpression(String attrName, Expression attrExp, ClassNode attrType) {
    if (attrType.isArray()) {
        // check needed as @Test(attr = {"elem"}) passes through the parser
        if (attrExp instanceof ListExpression) {
            ListExpression le = (ListExpression) attrExp;
            visitListExpression(attrName, le, attrType.getComponentType());
        } else if (attrExp instanceof ClosureExpression) {
            addError("Annotation list attributes must use Groovy notation [el1, el2]", attrExp);
        } else {
            // treat like a singleton list as per Java
            ListExpression listExp = new ListExpression();
            listExp.addExpression(attrExp);
            if (annotation != null) {
                annotation.setMember(attrName, listExp);
            }
            visitExpression(attrName, listExp, attrType);
        }
    } else if (ClassHelper.isPrimitiveType(attrType)) {
        visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.getWrapper(attrType));
    } else if (ClassHelper.STRING_TYPE.equals(attrType)) {
        visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.STRING_TYPE);
    } else if (ClassHelper.CLASS_Type.equals(attrType)) {
        if (!(attrExp instanceof ClassExpression || attrExp instanceof ClosureExpression)) {
            addError("Only classes and closures can be used for attribute '" + attrName + "'", attrExp);
        }
    } else if (attrType.isDerivedFrom(ClassHelper.Enum_Type)) {
        if (attrExp instanceof PropertyExpression) {
            visitEnumExpression(attrName, (PropertyExpression) attrExp, attrType);
        } else {
            addError("Expected enum value for attribute " + attrName, attrExp);
        }
    } else if (isValidAnnotationClass(attrType)) {
        if (attrExp instanceof AnnotationConstantExpression) {
            visitAnnotationExpression(attrName, (AnnotationConstantExpression) attrExp, attrType);
        } else {
            addError("Expected annotation of type '" + attrType.getName() + "' for attribute " + attrName, attrExp);
        }
    } else {
        addError("Unexpected type " + attrType.getName(), attrExp);
    }
}
 
Example 19
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitStdMethod(final MethodNode node, final boolean isConstructor, final Parameter[] parameters, final Statement code) {
    controller.getCompileStack().init(node.getVariableScope(), parameters);
    controller.getCallSiteWriter().makeSiteEntry();

    MethodVisitor mv = controller.getMethodVisitor();
    if (isConstructor && (code == null || !((ConstructorNode) node).firstStatementIsSpecialConstructorCall())) {
        boolean hasCallToSuper = false;
        if (code != null && isInnerClass()) {
            // GROOVY-4471: if the class is an inner class node, there are chances that
            // the call to super is already added so we must ensure not to add it twice
            if (code instanceof BlockStatement) {
                hasCallToSuper = ((BlockStatement) code).getStatements().stream()
                    .map(statement -> statement instanceof ExpressionStatement ? ((ExpressionStatement) statement).getExpression() : null)
                    .anyMatch(expression -> expression instanceof ConstructorCallExpression && ((ConstructorCallExpression) expression).isSuperCall());
            }
        }
        if (!hasCallToSuper) {
            // invokes the super class constructor
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, controller.getInternalBaseClassName(), "<init>", "()V", false);
        }
    }

    // handle body
    super.visitConstructorOrMethod(node, isConstructor);

    controller.getCompileStack().clear();
    if (node.isVoidMethod()) {
        mv.visitInsn(RETURN);
    } else {
        ClassNode type = node.getReturnType();
        if (ClassHelper.isPrimitiveType(type)) {
            mv.visitLdcInsn(0);
            controller.getOperandStack().push(ClassHelper.int_TYPE);
            controller.getOperandStack().doGroovyCast(type);
            BytecodeHelper.doReturn(mv, type);
            controller.getOperandStack().remove(1);
        } else {
            mv.visitInsn(ACONST_NULL);
            BytecodeHelper.doReturn(mv, type);
        }
    }
}
 
Example 20
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitArrayExpression(final ArrayExpression expression) {
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode elementType = expression.getElementType();
    String arrayTypeName = BytecodeHelper.getClassInternalName(elementType);
    List<Expression> sizeExpression = expression.getSizeExpression();

    int size = 0;
    int dimensions = 0;
    if (sizeExpression != null) {
        for (Expression element : sizeExpression) {
            if (element == ConstantExpression.EMPTY_EXPRESSION) break;
            dimensions += 1;
            // let's convert to an int
            element.visit(this);
            controller.getOperandStack().doGroovyCast(ClassHelper.int_TYPE);
        }
        controller.getOperandStack().remove(dimensions);
    } else {
        size = expression.getExpressions().size();
        BytecodeHelper.pushConstant(mv, size);
    }

    int storeIns = AASTORE;
    if (sizeExpression != null) {
        arrayTypeName = BytecodeHelper.getTypeDescription(expression.getType());
        mv.visitMultiANewArrayInsn(arrayTypeName, dimensions);
    } else if (ClassHelper.isPrimitiveType(elementType)) {
        int primType = 0;
        if (elementType == ClassHelper.boolean_TYPE) {
            primType = T_BOOLEAN;
            storeIns = BASTORE;
        } else if (elementType == ClassHelper.char_TYPE) {
            primType = T_CHAR;
            storeIns = CASTORE;
        } else if (elementType == ClassHelper.float_TYPE) {
            primType = T_FLOAT;
            storeIns = FASTORE;
        } else if (elementType == ClassHelper.double_TYPE) {
            primType = T_DOUBLE;
            storeIns = DASTORE;
        } else if (elementType == ClassHelper.byte_TYPE) {
            primType = T_BYTE;
            storeIns = BASTORE;
        } else if (elementType == ClassHelper.short_TYPE) {
            primType = T_SHORT;
            storeIns = SASTORE;
        } else if (elementType == ClassHelper.int_TYPE) {
            primType = T_INT;
            storeIns = IASTORE;
        } else if (elementType == ClassHelper.long_TYPE) {
            primType = T_LONG;
            storeIns = LASTORE;
        }
        mv.visitIntInsn(NEWARRAY, primType);
    } else {
        mv.visitTypeInsn(ANEWARRAY, arrayTypeName);
    }

    for (int i = 0; i < size; i += 1) {
        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i);
        Expression elementExpression = expression.getExpression(i);
        if (elementExpression == null) {
            ConstantExpression.NULL.visit(this);
        } else {
            elementExpression.visit(this);
            controller.getOperandStack().doGroovyCast(elementType);
        }
        mv.visitInsn(storeIns);
        controller.getOperandStack().remove(1);
    }

    controller.getOperandStack().push(expression.getType());
}