Search in sources :

Example 61 with GroovyBugError

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

the class AsmClassGenerator method visitAnnotationDefaultExpression.

void visitAnnotationDefaultExpression(AnnotationVisitor av, ClassNode type, Expression exp) {
    if (exp instanceof ClosureExpression) {
        ClassNode closureClass = controller.getClosureWriter().getOrAddClosureClass((ClosureExpression) exp, ACC_PUBLIC);
        Type t = Type.getType(BytecodeHelper.getTypeDescription(closureClass));
        av.visit(null, t);
    } else if (type.isArray()) {
        AnnotationVisitor avl = av.visitArray(null);
        ClassNode componentType = type.getComponentType();
        if (exp instanceof ListExpression) {
            ListExpression list = (ListExpression) exp;
            for (Expression lExp : list.getExpressions()) {
                visitAnnotationDefaultExpression(avl, componentType, lExp);
            }
        } else {
            visitAnnotationDefaultExpression(avl, componentType, exp);
        }
    } else if (ClassHelper.isPrimitiveType(type) || type.equals(ClassHelper.STRING_TYPE)) {
        ConstantExpression constExp = (ConstantExpression) exp;
        av.visit(null, constExp.getValue());
    } else if (ClassHelper.CLASS_Type.equals(type)) {
        ClassNode clazz = exp.getType();
        Type t = Type.getType(BytecodeHelper.getTypeDescription(clazz));
        av.visit(null, t);
    } else if (type.isDerivedFrom(ClassHelper.Enum_Type)) {
        PropertyExpression pExp = (PropertyExpression) exp;
        ClassExpression cExp = (ClassExpression) pExp.getObjectExpression();
        String desc = BytecodeHelper.getTypeDescription(cExp.getType());
        String name = pExp.getPropertyAsString();
        av.visitEnum(null, desc, name);
    } else if (type.implementsInterface(ClassHelper.Annotation_TYPE)) {
        AnnotationConstantExpression avExp = (AnnotationConstantExpression) exp;
        AnnotationNode value = (AnnotationNode) avExp.getValue();
        AnnotationVisitor avc = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(avExp.getType()));
        visitAnnotationAttributes(value, avc);
    } else {
        throw new GroovyBugError("unexpected annotation type " + type.getName());
    }
    av.visitEnd();
}
Also used : InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) InterfaceHelperClassNode(org.codehaus.groovy.ast.InterfaceHelperClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) GroovyBugError(org.codehaus.groovy.GroovyBugError) Type(org.objectweb.asm.Type) GenericsType(org.codehaus.groovy.ast.GenericsType) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) AnnotationVisitor(org.objectweb.asm.AnnotationVisitor)

Example 62 with GroovyBugError

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

the class GeneratorContext method encodeAsValidClassName.

public static String encodeAsValidClassName(String name) {
    final int l = name.length();
    StringBuilder b = null;
    int lastEscape = -1;
    for (int i = 0; i < l; ++i) {
        final int encodeIndex = name.charAt(i) - MIN_ENCODING;
        if (encodeIndex >= 0 && encodeIndex < CHARACTERS_TO_ENCODE.length) {
            if (CHARACTERS_TO_ENCODE[encodeIndex]) {
                if (b == null) {
                    b = new StringBuilder(name.length() + 3);
                    b.append(name, 0, i);
                } else {
                    b.append(name, lastEscape + 1, i);
                }
                b.append('_');
                lastEscape = i;
            }
        }
    }
    if (b == null)
        return name.toString();
    if (lastEscape == -1)
        throw new GroovyBugError("unexpected escape char control flow in " + name);
    b.append(name, lastEscape + 1, l);
    return b.toString();
}
Also used : GroovyBugError(org.codehaus.groovy.GroovyBugError)

Example 63 with GroovyBugError

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

the class GenericsUtils method applyGenericsContextToPlaceHolders.

/**
     * transforms generics types from an old context to a new context using the given spec. This method assumes
     * all generics types will be placeholders. WARNING: The resulting generics types may or may not be placeholders
     * after the transformation.
     * @param genericsSpec the generics context information spec
     * @param oldPlaceHolders the old placeholders
     * @return the new generics types
     */
public static GenericsType[] applyGenericsContextToPlaceHolders(Map<String, ClassNode> genericsSpec, GenericsType[] oldPlaceHolders) {
    if (oldPlaceHolders == null || oldPlaceHolders.length == 0)
        return oldPlaceHolders;
    if (genericsSpec.isEmpty())
        return oldPlaceHolders;
    GenericsType[] newTypes = new GenericsType[oldPlaceHolders.length];
    for (int i = 0; i < oldPlaceHolders.length; i++) {
        GenericsType old = oldPlaceHolders[i];
        if (!old.isPlaceholder())
            throw new GroovyBugError("Given generics type " + old + " must be a placeholder!");
        ClassNode fromSpec = genericsSpec.get(old.getName());
        if (fromSpec != null) {
            if (fromSpec.isGenericsPlaceHolder()) {
                ClassNode[] upper = new ClassNode[] { fromSpec.redirect() };
                newTypes[i] = new GenericsType(fromSpec, upper, null);
            } else {
                newTypes[i] = new GenericsType(fromSpec);
            }
        } else {
            ClassNode[] upper = old.getUpperBounds();
            ClassNode[] newUpper = upper;
            if (upper != null && upper.length > 0) {
                ClassNode[] upperCorrected = new ClassNode[upper.length];
                for (int j = 0; j < upper.length; j++) {
                    upperCorrected[i] = correctToGenericsSpecRecurse(genericsSpec, upper[j]);
                }
                upper = upperCorrected;
            }
            ClassNode lower = old.getLowerBound();
            ClassNode newLower = correctToGenericsSpecRecurse(genericsSpec, lower);
            if (lower == newLower && upper == newUpper) {
                newTypes[i] = oldPlaceHolders[i];
            } else {
                ClassNode newPlaceHolder = ClassHelper.make(old.getName());
                GenericsType gt = new GenericsType(newPlaceHolder, newUpper, newLower);
                gt.setPlaceholder(true);
                newTypes[i] = gt;
            }
        }
    }
    return newTypes;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) GenericsType(org.codehaus.groovy.ast.GenericsType) GroovyBugError(org.codehaus.groovy.GroovyBugError)

Example 64 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 65 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