Search in sources :

Example 66 with GroovyBugError

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

the class OptimizingStatementWriter method writeDeclarationExtraction.

private boolean writeDeclarationExtraction(Statement statement) {
    Expression ex = null;
    if (statement instanceof ReturnStatement) {
        ReturnStatement rs = (ReturnStatement) statement;
        ex = rs.getExpression();
    } else if (statement instanceof ExpressionStatement) {
        ExpressionStatement es = (ExpressionStatement) statement;
        ex = es.getExpression();
    } else {
        throw new GroovyBugError("unknown statement type :" + statement.getClass());
    }
    if (!(ex instanceof DeclarationExpression))
        return true;
    DeclarationExpression declaration = (DeclarationExpression) ex;
    ex = declaration.getLeftExpression();
    if (ex instanceof TupleExpression)
        return false;
    // stash declared variable in case we do subsequent visits after we
    // change to assignment only
    StatementMeta meta = statement.getNodeMetaData(StatementMeta.class);
    if (meta != null) {
        meta.declaredVariableExpression = declaration.getVariableExpression();
    }
    // change statement to do assignment only
    BinaryExpression assignment = new BinaryExpression(declaration.getLeftExpression(), declaration.getOperation(), declaration.getRightExpression());
    assignment.setSourcePosition(declaration);
    assignment.copyNodeMetaData(declaration);
    // replace statement code
    if (statement instanceof ReturnStatement) {
        ReturnStatement rs = (ReturnStatement) statement;
        rs.setExpression(assignment);
    } else if (statement instanceof ExpressionStatement) {
        ExpressionStatement es = (ExpressionStatement) statement;
        es.setExpression(assignment);
    } else {
        throw new GroovyBugError("unknown statement type :" + statement.getClass());
    }
    return true;
}
Also used : GroovyBugError(org.codehaus.groovy.GroovyBugError)

Example 67 with GroovyBugError

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

the class OperandStack method castToBool.

/**
     * ensure last marked parameter on the stack is a primitive boolean
     * if mark==stack size, we assume an empty expression or statement.
     * was used and we will use the value given in emptyDefault as boolean 
     * if mark==stack.size()-1 the top element will be cast to boolean using
     * Groovy truth.
     * In other cases we throw a GroovyBugError
     */
public void castToBool(int mark, boolean emptyDefault) {
    int size = stack.size();
    MethodVisitor mv = controller.getMethodVisitor();
    if (mark == size) {
        // no element, so use emptyDefault
        if (emptyDefault) {
            mv.visitIntInsn(BIPUSH, 1);
        } else {
            mv.visitIntInsn(BIPUSH, 0);
        }
        stack.add(null);
    } else if (mark == stack.size() - 1) {
        ClassNode last = stack.get(size - 1);
        // nothing to do in that case
        if (last == ClassHelper.boolean_TYPE)
            return;
        // not a primitive type, so call booleanUnbox
        if (!ClassHelper.isPrimitiveType(last)) {
            controller.getInvocationWriter().castNonPrimitiveToBool(last);
        } else {
            primitive2b(mv, last);
        }
    } else {
        throw new GroovyBugError("operand stack contains " + stack.size() + " elements, but we expected only " + mark);
    }
    stack.set(mark, ClassHelper.boolean_TYPE);
}
Also used : GroovyBugError(org.codehaus.groovy.GroovyBugError) MethodVisitor(org.objectweb.asm.MethodVisitor)

Example 68 with GroovyBugError

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

the class ReadWriteLockASTTransformation method visit.

public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    final boolean isWriteLock;
    if (READ_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = false;
    } else if (WRITE_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = true;
    } else {
        throw new GroovyBugError("Internal error: expecting [" + READ_LOCK_TYPE.getName() + ", " + WRITE_LOCK_TYPE.getName() + "]" + " but got: " + node.getClassNode().getName());
    }
    String myTypeName = "@" + node.getClassNode().getNameWithoutPackage();
    String value = getMemberStringValue(node, "value");
    if (parent instanceof MethodNode) {
        MethodNode mNode = (MethodNode) parent;
        ClassNode cNode = mNode.getDeclaringClass();
        String lockExpr = determineLock(value, cNode, mNode.isStatic(), myTypeName);
        if (lockExpr == null)
            return;
        // get lock type
        final Expression lockType;
        if (isWriteLock) {
            lockType = callX(varX(lockExpr, LOCK_TYPE), "writeLock");
        } else {
            lockType = callX(varX(lockExpr, LOCK_TYPE), "readLock");
        }
        Expression acquireLock = callX(lockType, "lock");
        Expression releaseLock = callX(lockType, "unlock");
        Statement originalCode = mNode.getCode();
        mNode.setCode(block(stmt(acquireLock), new TryCatchStatement(originalCode, stmt(releaseLock))));
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) MethodNode(org.codehaus.groovy.ast.MethodNode) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) Expression(org.codehaus.groovy.ast.expr.Expression) Statement(org.codehaus.groovy.ast.stmt.Statement) TryCatchStatement(org.codehaus.groovy.ast.stmt.TryCatchStatement) AnnotatedNode(org.codehaus.groovy.ast.AnnotatedNode) GroovyBugError(org.codehaus.groovy.GroovyBugError) TryCatchStatement(org.codehaus.groovy.ast.stmt.TryCatchStatement)

Example 69 with GroovyBugError

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

the class StaticTypeCheckingSupport method applyGenericsConnections.

static void applyGenericsConnections(Map<String, GenericsType> connections, Map<String, GenericsType> resolvedPlaceholders) {
    if (connections == null)
        return;
    int count = 0;
    while (count < 10000) {
        count++;
        boolean checkForMorePlaceHolders = false;
        for (Map.Entry<String, GenericsType> entry : resolvedPlaceholders.entrySet()) {
            String name = entry.getKey();
            GenericsType replacement = connections.get(name);
            if (replacement == null) {
                GenericsType value = entry.getValue();
                GenericsType newValue = applyGenericsContext(connections, value);
                entry.setValue(newValue);
                checkForMorePlaceHolders = checkForMorePlaceHolders || !equalIncludingGenerics(value, newValue);
                continue;
            }
            GenericsType original = entry.getValue();
            if (!original.isWildcard() && !original.isPlaceholder()) {
                continue;
            }
            boolean placeholderReplacement = replacement.isPlaceholder();
            if (placeholderReplacement) {
                GenericsType connectedType = resolvedPlaceholders.get(replacement.getName());
                if (replacement == connectedType)
                    continue;
            }
            // GROOVY-6787: Don't override the original if the replacement placeholder doesn't respect the bounds,
            // otherwise the original bounds are lost which can result in accepting an incompatible type as an
            // argument, for example.
            ClassNode replacementType = extractType(replacement);
            if (original.isCompatibleWith(replacementType)) {
                entry.setValue(replacement);
                if (placeholderReplacement) {
                    checkForMorePlaceHolders = checkForMorePlaceHolders || !equalIncludingGenerics(original, replacement);
                }
            }
        }
        if (!checkForMorePlaceHolders)
            break;
    }
    if (count >= 10000)
        throw new GroovyBugError("unable to handle generics in " + resolvedPlaceholders + " with connections " + connections);
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) GenericsType(org.codehaus.groovy.ast.GenericsType) GroovyBugError(org.codehaus.groovy.GroovyBugError) Map(java.util.Map) HashMap(java.util.HashMap)

Example 70 with GroovyBugError

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

the class GroovyTypeCheckingExtensionSupport method setup.

@Override
public void setup() {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass("org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL");
    ImportCustomizer ic = new ImportCustomizer();
    ic.addStarImports("org.codehaus.groovy.ast.expr");
    ic.addStaticStars("org.codehaus.groovy.ast.ClassHelper");
    ic.addStaticStars("org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport");
    config.addCompilationCustomizers(ic);
    final GroovyClassLoader transformLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : typeCheckingVisitor.getSourceUnit().getClassLoader();
    // since Groovy 2.2, it is possible to use FQCN for type checking extension scripts
    TypeCheckingDSL script = null;
    try {
        Class<?> clazz = transformLoader.loadClass(scriptPath, false, true);
        if (TypeCheckingDSL.class.isAssignableFrom(clazz)) {
            script = (TypeCheckingDSL) clazz.newInstance();
        } else if (TypeCheckingExtension.class.isAssignableFrom(clazz)) {
            // since 2.4, we can also register precompiled type checking extensions which are not scripts
            try {
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(StaticTypeCheckingVisitor.class);
                TypeCheckingExtension extension = (TypeCheckingExtension) declaredConstructor.newInstance(typeCheckingVisitor);
                typeCheckingVisitor.addTypeCheckingExtension(extension);
                extension.setup();
                return;
            } catch (InstantiationException e) {
                addLoadingError(config);
            } catch (IllegalAccessException e) {
                addLoadingError(config);
            } catch (NoSuchMethodException e) {
                context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' could not be loaded because it doesn't have a constructor accepting StaticTypeCheckingVisitor.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
            } catch (InvocationTargetException e) {
                addLoadingError(config);
            }
        }
    } catch (ClassNotFoundException e) {
    // silent
    } catch (InstantiationException e) {
        addLoadingError(config);
    } catch (IllegalAccessException e) {
        addLoadingError(config);
    }
    if (script == null) {
        ClassLoader cl = typeCheckingVisitor.getSourceUnit().getClassLoader();
        // cast to prevent incorrect @since 1.7 warning
        InputStream is = ((ClassLoader) transformLoader).getResourceAsStream(scriptPath);
        if (is == null) {
            // fallback to the source unit classloader
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // fallback to the compiler classloader
            cl = GroovyTypeCheckingExtensionSupport.class.getClassLoader();
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // if the input stream is still null, we've not found the extension
            context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' was not found on the classpath.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
        }
        try {
            GroovyShell shell = new GroovyShell(transformLoader, new Binding(), config);
            script = (TypeCheckingDSL) shell.parse(new InputStreamReader(is, typeCheckingVisitor.getSourceUnit().getConfiguration().getSourceEncoding()));
        } catch (CompilationFailedException e) {
            throw new GroovyBugError("An unexpected error was thrown during custom type checking", e);
        } catch (UnsupportedEncodingException e) {
            throw new GroovyBugError("Unsupported encoding found in compiler configuration", e);
        }
    }
    if (script != null) {
        script.extension = this;
        script.run();
        List<Closure> list = eventHandlers.get("setup");
        if (list != null) {
            for (Closure closure : list) {
                safeCall(closure);
            }
        }
    }
}
Also used : Closure(groovy.lang.Closure) GroovyBugError(org.codehaus.groovy.GroovyBugError) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClassLoader(groovy.lang.GroovyClassLoader) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) Binding(groovy.lang.Binding) InputStreamReader(java.io.InputStreamReader) Constructor(java.lang.reflect.Constructor) InputStream(java.io.InputStream) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyShell(groovy.lang.GroovyShell)

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