Search in sources :

Example 11 with GroovyBugError

use of org.codehaus.groovy.GroovyBugError in project groovy by apache.

the class StaticTypeCheckingVisitor method extractPlaceHolders.

private static Map<String, GenericsType> extractPlaceHolders(MethodNode method, ClassNode receiver, ClassNode declaringClass) {
    if (declaringClass.equals(OBJECT_TYPE)) {
        Map<String, GenericsType> resolvedPlaceholders = new HashMap<String, GenericsType>();
        if (method != null)
            addMethodLevelDeclaredGenerics(method, resolvedPlaceholders);
        return resolvedPlaceholders;
    }
    Map<String, GenericsType> resolvedPlaceholders = null;
    if (isPrimitiveType(receiver) && !isPrimitiveType(declaringClass)) {
        receiver = getWrapper(receiver);
    }
    final List<ClassNode> queue;
    if (receiver instanceof UnionTypeClassNode) {
        queue = Arrays.asList(((UnionTypeClassNode) receiver).getDelegates());
    } else {
        queue = Collections.singletonList(receiver);
    }
    for (ClassNode item : queue) {
        ClassNode current = item;
        while (current != null) {
            boolean continueLoop = true;
            //extract the place holders
            Map<String, GenericsType> currentPlaceHolders = new HashMap<String, GenericsType>();
            if (isGenericsPlaceHolderOrArrayOf(declaringClass) || declaringClass.equals(current)) {
                extractGenericsConnections(currentPlaceHolders, current, declaringClass);
                if (method != null)
                    addMethodLevelDeclaredGenerics(method, currentPlaceHolders);
                continueLoop = false;
            } else {
                GenericsUtils.extractPlaceholders(current, currentPlaceHolders);
            }
            if (resolvedPlaceholders != null) {
                // merge maps
                Set<Map.Entry<String, GenericsType>> entries = currentPlaceHolders.entrySet();
                for (Map.Entry<String, GenericsType> entry : entries) {
                    GenericsType gt = entry.getValue();
                    if (!gt.isPlaceholder())
                        continue;
                    GenericsType referenced = resolvedPlaceholders.get(gt.getName());
                    if (referenced == null)
                        continue;
                    entry.setValue(referenced);
                }
            }
            resolvedPlaceholders = currentPlaceHolders;
            // we are done if we are now in the declaring class
            if (!continueLoop)
                break;
            current = getNextSuperClass(current, declaringClass);
            if (current == null && CLASS_Type.equals(declaringClass)) {
                // this can happen if the receiver is Class<Foo>, then
                // the actual receiver is Foo and declaringClass is Class
                current = declaringClass;
            }
        }
    }
    if (resolvedPlaceholders == null) {
        String descriptor = "<>";
        if (method != null)
            descriptor = method.getTypeDescriptor();
        throw new GroovyBugError("Declaring class for method call to '" + descriptor + "' declared in " + declaringClass.getName() + " was not matched with found receiver " + receiver.getName() + "." + " This should not have happened!");
    }
    return resolvedPlaceholders;
}
Also used : LowestUpperBoundClassNode(org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) LinkedHashMap(java.util.LinkedHashMap) ListHashMap(org.codehaus.groovy.util.ListHashMap) HashMap(java.util.HashMap) GroovyBugError(org.codehaus.groovy.GroovyBugError) GenericsType(org.codehaus.groovy.ast.GenericsType) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ListHashMap(org.codehaus.groovy.util.ListHashMap) HashMap(java.util.HashMap)

Example 12 with GroovyBugError

use of org.codehaus.groovy.GroovyBugError in project groovy by apache.

the class StaticTypeCheckingSupport method evaluateExpression.

/**
     * A helper method that can be used to evaluate expressions as found in annotation
     * parameters. For example, it will evaluate a constant, be it referenced directly as
     * an integer or as a reference to a field.
     *
     * If this method throws an exception, then the expression cannot be evaluated on its own.
     *
     * @param expr the expression to be evaluated
     * @param config the compiler configuration
     * @return the result of the expression
     */
public static Object evaluateExpression(Expression expr, CompilerConfiguration config) {
    String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$');
    ClassNode node = new ClassNode(className, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
    ReturnStatement code = new ReturnStatement(expr);
    node.addMethod(new MethodNode("eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code));
    CompilerConfiguration copyConf = new CompilerConfiguration(config);
    CompilationUnit cu = new CompilationUnit(copyConf);
    cu.addClassNode(node);
    cu.compile(Phases.CLASS_GENERATION);
    @SuppressWarnings("unchecked") List<GroovyClass> classes = (List<GroovyClass>) cu.getClasses();
    Class aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes());
    try {
        return aClass.getMethod("eval").invoke(null);
    } catch (IllegalAccessException e) {
        throw new GroovyBugError(e);
    } catch (InvocationTargetException e) {
        throw new GroovyBugError(e);
    } catch (NoSuchMethodException e) {
        throw new GroovyBugError(e);
    }
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) ClassNode(org.codehaus.groovy.ast.ClassNode) GroovyClass(org.codehaus.groovy.tools.GroovyClass) GroovyBugError(org.codehaus.groovy.GroovyBugError) InvocationTargetException(java.lang.reflect.InvocationTargetException) MethodNode(org.codehaus.groovy.ast.MethodNode) ReturnStatement(org.codehaus.groovy.ast.stmt.ReturnStatement) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) GroovyClass(org.codehaus.groovy.tools.GroovyClass)

Example 13 with GroovyBugError

use of org.codehaus.groovy.GroovyBugError in project groovy by apache.

the class BinaryExpressionHelper method eval.

public void eval(BinaryExpression expression) {
    switch(expression.getOperation().getType()) {
        case // = assignment
        EQUAL:
            evaluateEqual(expression, false);
            break;
        case // ==
        COMPARE_EQUAL:
            evaluateCompareExpression(compareEqualMethod, expression);
            break;
        case COMPARE_NOT_EQUAL:
            evaluateCompareExpression(compareNotEqualMethod, expression);
            break;
        case COMPARE_TO:
            evaluateCompareTo(expression);
            break;
        case COMPARE_GREATER_THAN:
            evaluateCompareExpression(compareGreaterThanMethod, expression);
            break;
        case COMPARE_GREATER_THAN_EQUAL:
            evaluateCompareExpression(compareGreaterThanEqualMethod, expression);
            break;
        case COMPARE_LESS_THAN:
            evaluateCompareExpression(compareLessThanMethod, expression);
            break;
        case COMPARE_LESS_THAN_EQUAL:
            evaluateCompareExpression(compareLessThanEqualMethod, expression);
            break;
        case LOGICAL_AND:
            evaluateLogicalAndExpression(expression);
            break;
        case LOGICAL_OR:
            evaluateLogicalOrExpression(expression);
            break;
        case BITWISE_AND:
            evaluateBinaryExpression("and", expression);
            break;
        case BITWISE_AND_EQUAL:
            evaluateBinaryExpressionWithAssignment("and", expression);
            break;
        case BITWISE_OR:
            evaluateBinaryExpression("or", expression);
            break;
        case BITWISE_OR_EQUAL:
            evaluateBinaryExpressionWithAssignment("or", expression);
            break;
        case BITWISE_XOR:
            evaluateBinaryExpression("xor", expression);
            break;
        case BITWISE_XOR_EQUAL:
            evaluateBinaryExpressionWithAssignment("xor", expression);
            break;
        case PLUS:
            evaluateBinaryExpression("plus", expression);
            break;
        case PLUS_EQUAL:
            evaluateBinaryExpressionWithAssignment("plus", expression);
            break;
        case MINUS:
            evaluateBinaryExpression("minus", expression);
            break;
        case MINUS_EQUAL:
            evaluateBinaryExpressionWithAssignment("minus", expression);
            break;
        case MULTIPLY:
            evaluateBinaryExpression("multiply", expression);
            break;
        case MULTIPLY_EQUAL:
            evaluateBinaryExpressionWithAssignment("multiply", expression);
            break;
        case DIVIDE:
            evaluateBinaryExpression("div", expression);
            break;
        case DIVIDE_EQUAL:
            //SPG don't use divide since BigInteger implements directly
            //and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
            evaluateBinaryExpressionWithAssignment("div", expression);
            break;
        case INTDIV:
            evaluateBinaryExpression("intdiv", expression);
            break;
        case INTDIV_EQUAL:
            evaluateBinaryExpressionWithAssignment("intdiv", expression);
            break;
        case MOD:
            evaluateBinaryExpression("mod", expression);
            break;
        case MOD_EQUAL:
            evaluateBinaryExpressionWithAssignment("mod", expression);
            break;
        case POWER:
            evaluateBinaryExpression("power", expression);
            break;
        case POWER_EQUAL:
            evaluateBinaryExpressionWithAssignment("power", expression);
            break;
        case LEFT_SHIFT:
            evaluateBinaryExpression("leftShift", expression);
            break;
        case LEFT_SHIFT_EQUAL:
            evaluateBinaryExpressionWithAssignment("leftShift", expression);
            break;
        case RIGHT_SHIFT:
            evaluateBinaryExpression("rightShift", expression);
            break;
        case RIGHT_SHIFT_EQUAL:
            evaluateBinaryExpressionWithAssignment("rightShift", expression);
            break;
        case RIGHT_SHIFT_UNSIGNED:
            evaluateBinaryExpression("rightShiftUnsigned", expression);
            break;
        case RIGHT_SHIFT_UNSIGNED_EQUAL:
            evaluateBinaryExpressionWithAssignment("rightShiftUnsigned", expression);
            break;
        case KEYWORD_INSTANCEOF:
            evaluateInstanceof(expression);
            break;
        case FIND_REGEX:
            evaluateCompareExpression(findRegexMethod, expression);
            break;
        case MATCH_REGEX:
            evaluateCompareExpression(matchRegexMethod, expression);
            break;
        case LEFT_SQUARE_BRACKET:
            if (controller.getCompileStack().isLHS()) {
                evaluateEqual(expression, false);
            } else {
                evaluateBinaryExpression("getAt", expression);
            }
            break;
        case KEYWORD_IN:
            evaluateCompareExpression(isCaseMethod, expression);
            break;
        case COMPARE_IDENTICAL:
        case COMPARE_NOT_IDENTICAL:
            Token op = expression.getOperation();
            Throwable cause = new SyntaxException("Operator " + op + " not supported", op.getStartLine(), op.getStartColumn(), op.getStartLine(), op.getStartColumn() + 3);
            throw new GroovyRuntimeException(cause);
        default:
            throw new GroovyBugError("Operation: " + expression.getOperation() + " not supported");
    }
}
Also used : SyntaxException(org.codehaus.groovy.syntax.SyntaxException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GroovyBugError(org.codehaus.groovy.GroovyBugError) Token(org.codehaus.groovy.syntax.Token)

Example 14 with GroovyBugError

use of org.codehaus.groovy.GroovyBugError in project groovy by apache.

the class CompileStack method init.

/**
     * initializes this class for a MethodNode. This method will
     * automatically define variables for the method parameters
     * and will create references if needed.  The created variables
     * can be accessed by calling getVariable().
     *
     */
public void init(VariableScope el, Parameter[] parameters) {
    if (!clear)
        throw new GroovyBugError("CompileStack#init called without calling clear before");
    clear = false;
    pushVariableScope(el);
    defineMethodVariables(parameters, el.isInStaticContext());
    this.className = BytecodeHelper.getTypeDescription(controller.getClassNode());
}
Also used : GroovyBugError(org.codehaus.groovy.GroovyBugError)

Example 15 with GroovyBugError

use of org.codehaus.groovy.GroovyBugError in project groovy by apache.

the class Verifier method addDefaultParameters.

protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) {
    Parameter[] parameters = method.getParameters();
    int counter = 0;
    List paramValues = new ArrayList();
    int size = parameters.length;
    for (int i = size - 1; i >= 0; i--) {
        Parameter parameter = parameters[i];
        if (parameter != null && parameter.hasInitialExpression()) {
            paramValues.add(i);
            paramValues.add(new CastExpression(parameter.getType(), parameter.getInitialExpression()));
            counter++;
        }
    }
    for (int j = 1; j <= counter; j++) {
        Parameter[] newParams = new Parameter[parameters.length - j];
        ArgumentListExpression arguments = new ArgumentListExpression();
        int index = 0;
        int k = 1;
        for (Parameter parameter : parameters) {
            if (parameter == null) {
                throw new GroovyBugError("Parameter should not be null for method " + methodNode.getName());
            } else {
                if (k > counter - j && parameter.hasInitialExpression()) {
                    arguments.addExpression(new CastExpression(parameter.getType(), parameter.getInitialExpression()));
                    k++;
                } else if (parameter.hasInitialExpression()) {
                    newParams[index++] = parameter;
                    arguments.addExpression(new CastExpression(parameter.getType(), new VariableExpression(parameter.getName())));
                    k++;
                } else {
                    newParams[index++] = parameter;
                    arguments.addExpression(new CastExpression(parameter.getType(), new VariableExpression(parameter.getName())));
                }
            }
        }
        action.call(arguments, newParams, method);
    }
    for (Parameter parameter : parameters) {
        // remove default expression and store it as node metadata
        parameter.putNodeMetaData(Verifier.INITIAL_EXPRESSION, parameter.getInitialExpression());
        parameter.setInitialExpression(null);
    }
}
Also used : ArrayList(java.util.ArrayList) GroovyBugError(org.codehaus.groovy.GroovyBugError) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) List(java.util.List) ArrayList(java.util.ArrayList) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) CastExpression(org.codehaus.groovy.ast.expr.CastExpression)

Aggregations

GroovyBugError (org.codehaus.groovy.GroovyBugError)71 ClassNode (org.codehaus.groovy.ast.ClassNode)31 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)11 InnerClassNode (org.codehaus.groovy.ast.InnerClassNode)11 MethodNode (org.codehaus.groovy.ast.MethodNode)11 GenericsType (org.codehaus.groovy.ast.GenericsType)9 AnnotatedNode (org.codehaus.groovy.ast.AnnotatedNode)8 FieldNode (org.codehaus.groovy.ast.FieldNode)8 SyntaxException (org.codehaus.groovy.syntax.SyntaxException)8 MethodVisitor (org.objectweb.asm.MethodVisitor)8 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)7 Closure (groovy.lang.Closure)6 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 LinkedList (java.util.LinkedList)5 Expression (org.codehaus.groovy.ast.expr.Expression)5 GroovyClassLoader (groovy.lang.GroovyClassLoader)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Collection (java.util.Collection)4