org.codehaus.groovy.GroovyBugError Java Examples

The following examples show how to use org.codehaus.groovy.GroovyBugError. 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: GroovyTypeCheckingExtensionSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<MethodNode> handleAmbiguousMethods(final List<MethodNode> nodes, final Expression origin) {
    List<Closure> onMethodSelection = eventHandlers.get("handleAmbiguousMethods");
    List<MethodNode> methodList = nodes;
    if (onMethodSelection != null) {
        Iterator<Closure> iterator = onMethodSelection.iterator();
        while (methodList.size()>1 && iterator.hasNext() ) {
            final Closure closure = iterator.next();
            Object result = safeCall(closure, methodList, origin);
            if (result != null) {
                if (result instanceof MethodNode) {
                    methodList = Collections.singletonList((MethodNode) result);
                } else if (result instanceof Collection) {
                    methodList = new LinkedList<MethodNode>((Collection<? extends MethodNode>) result);
                } else {
                    throw new GroovyBugError("Type checking extension returned unexpected method list: " + result);
                }
            }
        }
    }
    return methodList;
}
 
Example #2
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(AnnotationMemberDeclaration n, Object arg) {
    if (!currentClassDoc.isAnnotationType()) {
        throw new GroovyBugError("Annotation member definition found when not expected");
    }
    SimpleGroovyFieldDoc fieldDoc = new SimpleGroovyFieldDoc(n.getNameAsString(), currentClassDoc);
    fieldDoc.setType(makeType(n.getType()));
    setModifiers(n.getModifiers(), fieldDoc);
    fieldDoc.setPublic(true);
    processAnnotations(fieldDoc, n);
    currentClassDoc.add(fieldDoc);
    n.getJavadocComment().ifPresent(javadocComment ->
            fieldDoc.setRawCommentText(javadocComment.getContent()));
    n.getDefaultValue().ifPresent(defValue -> {
        fieldDoc.setRawCommentText(fieldDoc.getRawCommentText() + "\n* @default " + defValue.toString());
        fieldDoc.setConstantValueExpression(defValue.toString());
    });
    super.visit(n, arg);
}
 
Example #3
Source File: GroovyTypeCheckingExtensionSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<MethodNode> handleMissingMethod(final ClassNode receiver, final String name, final ArgumentListExpression argumentList, final ClassNode[] argumentTypes, final MethodCall call) {
    List<Closure> onMethodSelection = eventHandlers.get("handleMissingMethod");
    List<MethodNode> methodList = new LinkedList<MethodNode>();
    if (onMethodSelection != null) {
        for (Closure closure : onMethodSelection) {
            Object result = safeCall(closure, receiver, name, argumentList, argumentTypes, call);
            if (result != null) {
                if (result instanceof MethodNode) {
                    methodList.add((MethodNode) result);
                } else if (result instanceof Collection) {
                    methodList.addAll((Collection<? extends MethodNode>) result);
                } else {
                    throw new GroovyBugError("Type checking extension returned unexpected method list: " + result);
                }
            }
        }
    }
    return methodList;
}
 
Example #4
Source File: Selector.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Selector
 */
public static Selector getSelector(MutableCallSite callSite, Class<?> sender, String methodName, int callID, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
    CallType callType = CALL_TYPE_VALUES[callID];
    switch (callType) {
        case INIT:
            return new InitSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
        case METHOD:
            return new MethodSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
        case GET:
            return new PropertySelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
        case SET:
            throw new GroovyBugError("your call tried to do a property set, which is not supported.");
        case CAST:
            return new CastSelector(callSite, arguments);
        default:
            throw new GroovyBugError("unexpected call type");
    }
}
 
Example #5
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Uses supplied type to make a connection from usage to declaration.
 * <p>
 * The method operates in two modes:
 * <ul>
 * <li>For type !instanceof target a structural compare will be done
 *     (for example Type&lt;T&gt; and List&lt;E&gt; to get E -> T)
 * <li>If type equals target, a structural match is done as well
 *     (for example Collection&lt;T&gt; and Collection&lt;E&gt; to get E -> T)
 * <li>Otherwise we climb the hierarchy to find a case of type equals target
 *     to then execute the structural match, while applying possibly existing
 *     generics contexts on the way (for example for IntRange and Collection&lt;E&gt;
 *     to get E -> Integer, since IntRange is an AbstractList&lt;Integer&gt;)
 * </ul>
 * Should the target not have any generics this method does nothing.
 */
static void extractGenericsConnections(final Map<GenericsTypeName, GenericsType> connections, final ClassNode type, final ClassNode target) {
    if (target == null || type == target || !isUsingGenericsOrIsArrayUsingGenerics(target)) return;
    if (type == null || type == UNKNOWN_PARAMETER_TYPE) return;

    if (target.isGenericsPlaceHolder()) {
        connections.put(new GenericsTypeName(target.getGenericsTypes()[0].getName()), new GenericsType(type));

    } else if (type.isArray() && target.isArray()) {
        extractGenericsConnections(connections, type.getComponentType(), target.getComponentType());

    } else if (type.equals(target) || !implementsInterfaceOrIsSubclassOf(type, target)) {
        extractGenericsConnections(connections, type.getGenericsTypes(), target.getGenericsTypes());

    } else {
        // first find matching super class or interface
        ClassNode superClass = getSuperClass(type, target);
        if (superClass != null) {
            extractGenericsConnections(connections, getCorrectedClassNode(type, superClass, true), target);
        } else {
            // if we reach here, we have an unhandled case
            throw new GroovyBugError("The type " + type + " seems not to normally extend " + target + ". Sorry, I cannot handle this.");
        }
    }
}
 
Example #6
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 * <p>
 * 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(final Expression expr, final CompilerConfiguration config) {
    String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$');
    ClassNode node = new ClassNode(className, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
    ReturnStatement code = new ReturnStatement(expr);
    addGeneratedMethod(node, "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);
    List<GroovyClass> classes = cu.getClasses();
    Class<?> aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes());
    try {
        return aClass.getMethod("eval").invoke(null);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new GroovyBugError(e);
    }
}
 
Example #7
Source File: StaticTypesClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected ClassNode createClosureClass(final ClosureExpression expression, final int mods) {
    ClassNode closureClass = super.createClosureClass(expression, mods);
    List<MethodNode> methods = closureClass.getDeclaredMethods("call");
    List<MethodNode> doCall = closureClass.getMethods("doCall");
    if (doCall.size() != 1) {
        throw new GroovyBugError("Expected to find one (1) doCall method on generated closure, but found " + doCall.size());
    }
    MethodNode doCallMethod = doCall.get(0);
    if (methods.isEmpty() && doCallMethod.getParameters().length == 1) {
        createDirectCallMethod(closureClass, doCallMethod);
    }
    MethodTargetCompletionVisitor visitor = new MethodTargetCompletionVisitor(doCallMethod);
    Object dynamic = expression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION);
    if (dynamic != null) {
        doCallMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, dynamic);
    }
    for (MethodNode method : methods) {
        visitor.visitMethod(method);
    }
    closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE);
    return closureClass;
}
 
Example #8
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void makeSingleArgumentCall(final Expression receiver, final String message, final Expression arguments, final boolean safe) {
    TypeChooser typeChooser = controller.getTypeChooser();
    ClassNode classNode = controller.getClassNode();
    ClassNode rType = typeChooser.resolveType(receiver, classNode);
    ClassNode aType = typeChooser.resolveType(arguments, classNode);
    if (trySubscript(receiver, message, arguments, rType, aType, safe)) {
        return;
    }
    // now try with flow type instead of declaration type
    rType = receiver.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
    if (receiver instanceof VariableExpression && rType == null) {
        // TODO: can STCV be made smarter to avoid this check?
        VariableExpression ve = (VariableExpression) ((VariableExpression)receiver).getAccessedVariable();
        rType = ve.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
    }
    if (rType!=null && trySubscript(receiver, message, arguments, rType, aType, safe)) {
        return;
    }
    // todo: more cases
    throw new GroovyBugError(
            "At line " + receiver.getLineNumber() + " column " + receiver.getColumnNumber() + "\n" +
            "On receiver: " + receiver.getText() + " with message: " + message + " and arguments: " + arguments.getText() + "\n" +
            "This method should not have been called. Please try to create a simple example reproducing\n" +
            "this error and file a bug report at https://issues.apache.org/jira/browse/GROOVY");
}
 
Example #9
Source File: SourceUnit.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the source to a CST.  You can retrieve it with getCST().
 */
public void parse() throws CompilationFailedException {
    if (this.phase > Phases.PARSING) {
        throw new GroovyBugError("parsing is already complete");
    }

    if (this.phase == Phases.INITIALIZATION) {
        nextPhase();
    }

    //
    // Create a reader on the source and run the parser.

    try (Reader reader = source.getReader()) {
        // let's recreate the parser each time as it tends to keep around state
        parserPlugin = getConfiguration().getPluginFactory().createParserPlugin();

        cst = parserPlugin.parseCST(this, reader);
    } catch (IOException e) {
        getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), this));
    }
}
 
Example #10
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ClassNode configureType(Type type) {
    if (type instanceof WildcardType) {
        return configureWildcardType((WildcardType) type);
    } else if (type instanceof ParameterizedType) {
        return configureParameterizedType((ParameterizedType) type);
    } else if (type instanceof GenericArrayType) {
        return configureGenericArray((GenericArrayType) type);
    } else if (type instanceof TypeVariable) {
        return configureTypeVariableReference(((TypeVariable) type).getName());
    } else if (type instanceof Class) {
        return configureClass((Class<?>) type);
    } else if (type==null) {
        throw new GroovyBugError("Type is null. Most probably you let a transform reuse existing ClassNodes with generics information, that is now used in a wrong context.");
    } else {
        throw new GroovyBugError("unknown type: " + type + " := " + type.getClass());
    }
}
 
Example #11
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static groovy.transform.PackageScopeTarget extractTarget(PropertyExpression expr) {
    Expression oe = expr.getObjectExpression();
    if (oe instanceof ClassExpression) {
        ClassExpression ce = (ClassExpression) oe;
        if (ce.getType().getName().equals("groovy.transform.PackageScopeTarget")) {
            Expression prop = expr.getProperty();
            if (prop instanceof ConstantExpression) {
                String propName = (String) ((ConstantExpression) prop).getValue();
                try {
                    return PackageScopeTarget.valueOf(propName);
                } catch(IllegalArgumentException iae) {
                    /* ignore */
                }
            }
        }
    }
    throw new GroovyBugError("Internal error during " + MY_TYPE_NAME
            + " processing. Annotation parameters must be of type: " + TARGET_CLASS_NAME + ".");
}
 
Example #12
Source File: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
public boolean addGeneratedClosureConstructorCall(final ConstructorCallExpression call) {
    ClassNode classNode = controller.getClassNode();
    if (!classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    ClassNode callNode = classNode.getSuperClass();
    TupleExpression arguments = (TupleExpression) call.getArguments();
    if (arguments.getExpressions().size()!=2) throw new GroovyBugError("expected 2 arguments for closure constructor super call, but got"+arguments.getExpressions().size());
    arguments.getExpression(0).visit(acg);
    operandStack.box();
    arguments.getExpression(1).visit(acg);
    operandStack.box();
    //TODO: replace with normal String, p not needed
    Parameter p = new Parameter(ClassHelper.OBJECT_TYPE,"_p");
    String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, new Parameter[]{p,p});
    mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "<init>", descriptor, false);
    operandStack.remove(2);
    return true;
}
 
Example #13
Source File: GeneratorContext.java    From groovy with Apache License 2.0 6 votes vote down vote up
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;
    if (lastEscape == -1) throw new GroovyBugError("unexpected escape char control flow in "+name);
    b.append(name, lastEscape + 1, l);
    return b.toString();
}
 
Example #14
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public Object getInvokeSpecialHandle(final Method method, final Object receiver) {
    if (getLookupConstructor() == null) {
        throw new GroovyBugError("getInvokeSpecialHandle requires at least JDK 7 wot private access to Lookup");
    }
    if (!method.isAccessible()) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.trySetAccessible(method);
            return null;
        });
    }
    Class<?> declaringClass = method.getDeclaringClass();
    try {
        return getLookupConstructor().newInstance(declaringClass, -1).
                unreflectSpecial(method, declaringClass).
                bindTo(receiver);
    } catch (ReflectiveOperationException e) {
        throw new GroovyBugError(e);
    }
}
 
Example #15
Source File: StaticTypesLambdaWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void newGroovyLambdaWrapperAndLoad(final ClassNode lambdaClass, final LambdaExpression expression, final boolean accessingInstanceMembers) {
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();
    MethodVisitor mv = controller.getMethodVisitor();

    String lambdaClassInternalName = BytecodeHelper.getClassInternalName(lambdaClass);
    mv.visitTypeInsn(NEW, lambdaClassInternalName);
    mv.visitInsn(DUP);

    if (controller.isStaticMethod() || compileStack.isInSpecialConstructorCall() || !accessingInstanceMembers) {
        ClassNode classNode = controller.getClassNode();
        while (isGeneratedFunction(classNode)) {
            classNode = classNode.getOuterClass();
        }
        classX(classNode).visit(controller.getAcg());
    } else {
        loadThis();
    }

    operandStack.dup();

    loadSharedVariables(expression);

    Optional<ConstructorNode> generatedConstructor = lambdaClass.getDeclaredConstructors().stream()
            .filter(ctor -> Boolean.TRUE.equals(ctor.getNodeMetaData(IS_GENERATED_CONSTRUCTOR))).findFirst();
    if (!generatedConstructor.isPresent()) {
        throw new GroovyBugError("Failed to find the generated constructor");
    }

    Parameter[] lambdaClassConstructorParameters = generatedConstructor.get().getParameters();
    mv.visitMethodInsn(INVOKESPECIAL, lambdaClassInternalName, "<init>", BytecodeHelper.getMethodDescriptor(VOID_TYPE, lambdaClassConstructorParameters), lambdaClass.isInterface());

    operandStack.replace(CLOSURE_TYPE, lambdaClassConstructorParameters.length);
}
 
Example #16
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * 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 == 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 {
            BytecodeHelper.convertPrimitiveToBoolean(mv, last);
        }
    } else {
        throw new GroovyBugError(
                "operand stack contains " + size +
                        " elements, but we expected only " + mark
        );
    }
    stack.set(mark, ClassHelper.boolean_TYPE);
}
 
Example #17
Source File: WriterController.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ClassNode getReturnType() {
    if (methodNode != null) {
        return methodNode.getReturnType();
    } else if (constructorNode != null) {
        return constructorNode.getReturnType();
    } else {
        throw new GroovyBugError("I spotted a return that is neither in a method nor in a constructor... I can not handle that");
    }
}
 
Example #18
Source File: CompileStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * 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(final VariableScope scope, final Parameter[] parameters) {
    if (!clear) throw new GroovyBugError("CompileStack#init called without calling clear before");
    clear = false;
    pushVariableScope(scope);
    defineMethodVariables(parameters, scope.isInStaticContext());
    this.className = BytecodeHelper.getTypeDescription(controller.getClassNode());
}
 
Example #19
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode popWithMessage(int last) {
    try {
        return stack.remove(last);
    } catch (ArrayIndexOutOfBoundsException ai) {
        String method = controller.getMethodNode() == null ?
                controller.getConstructorNode().getTypeDescriptor() :
                controller.getMethodNode().getTypeDescriptor();
        throw new GroovyBugError("Error while popping argument from operand stack tracker in class " +
                controller.getClassName() + " method " + method + ".");
    }
}
 
Example #20
Source File: WriterController.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static int chooseBytecodeVersion(final boolean invokedynamic, final boolean previewFeatures, final String targetBytecode) {
    Integer bytecodeVersion = CompilerConfiguration.JDK_TO_BYTECODE_VERSION_MAP.get(targetBytecode);
    if (bytecodeVersion == null) {
        throw new GroovyBugError("Bytecode version [" + targetBytecode + "] is not supported by the compiler");
    }

    if (invokedynamic && bytecodeVersion <= Opcodes.V1_7) {
        return Opcodes.V1_7; // invokedynamic added here
    } else if (previewFeatures) {
        return bytecodeVersion | Opcodes.V_PREVIEW;
    } else {
        return bytecodeVersion;
    }
}
 
Example #21
Source File: BinaryBooleanExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean writeStdOperators(int type, boolean simulate) {
    type = type - PLUS;
    if (type < 0 || type > 5 || type == 3 /*DIV*/) return false;
    if (simulate) return false;
    throw new GroovyBugError("should not reach here");
}
 
Example #22
Source File: NodeMetaDataHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the node meta data but allows overwriting values.
 *
 * @param key   the meta data key
 * @param value the meta data value
 * @return the old node meta data value for this key
 * @throws GroovyBugError if key is null
 */
default Object putNodeMetaData(Object key, Object value) {
    if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + ".");

    Map metaDataMap = this.getMetaDataMap();
    if (metaDataMap == null) {
        metaDataMap = new ListHashMap();
        this.setMetaDataMap(metaDataMap);
    }
    return metaDataMap.put(key, value);
}
 
Example #23
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void extractSuperClassGenerics(ClassNode type, ClassNode target, Map<String, ClassNode> spec) {
    // TODO: this method is very similar to StaticTypesCheckingSupport#extractGenericsConnections,
    // but operates on ClassNodes instead of GenericsType
    if (target == null || type == target) return;
    if (type.isArray() && target.isArray()) {
        extractSuperClassGenerics(type.getComponentType(), target.getComponentType(), spec);
    } else if (type.isArray() && JAVA_LANG_OBJECT.equals(target.getName())) {
        // Object is superclass of arrays but no generics involved
    } else if (target.isGenericsPlaceHolder() || type.equals(target) || !implementsInterfaceOrIsSubclassOf(type, target)) {
        // structural match route
        if (target.isGenericsPlaceHolder()) {
            spec.put(target.getGenericsTypes()[0].getName(), type);
        } else {
            extractSuperClassGenerics(type.getGenericsTypes(), target.getGenericsTypes(), spec);
        }
    } else {
        // have first to find matching super class or interface
        ClassNode superClass = getSuperClass(type, target);

        if (superClass != null) {
            ClassNode corrected = getCorrectedClassNode(type, superClass, false);
            extractSuperClassGenerics(corrected, target, spec);
        } else {
            // if we reach here, we have an unhandled case
            throw new GroovyBugError("The type " + type + " seems not to normally extend " + target + ". Sorry, I cannot handle this.");
        }
    }
}
 
Example #24
Source File: AsmReferenceResolver.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Class resolveJvmClass(String name) {
    try {
        return unit.getClassLoader().loadClass(name, false, true);
    } catch (ClassNotFoundException e) {
        throw new GroovyBugError("JVM class can't be loaded for " + name, e);
    }
}
 
Example #25
Source File: ClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the concrete class this classnode relates to. However, this method
 * is inherently unsafe as it may return null depending on the compile phase you are
 * using. AST transformations should never use this method directly, but rather obtain
 * a new class node using {@link #getPlainNodeReference()}.
 * @return the class this classnode relates to. May return null.
 */
public Class getTypeClass() {
    if (clazz != null) return clazz;
    if (redirect != null) return redirect.getTypeClass();

    ClassNode component = redirect().componentType;
    if (component != null && component.isResolved()) {
        return Array.newInstance(component.getTypeClass(), 0).getClass();
    }
    throw new GroovyBugError("ClassNode#getTypeClass for " + getName() + " called before the type class is set");
}
 
Example #26
Source File: ClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * @return the {@code ClassNode} of the super class of this type
 */
public ClassNode getSuperClass() {
    if (!lazyInitDone && !isResolved()) {
        throw new GroovyBugError("ClassNode#getSuperClass for " + getName() + " called before class resolving");
    }
    ClassNode sn = redirect().getUnresolvedSuperClass();
    if (sn != null) sn = sn.redirect();
    return sn;
}
 
Example #27
Source File: GroovyScript.java    From chaosblade-exec-jvm with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                return script.run();
            }
        });
    } catch (AssertionError assertionError) {
        if (assertionError instanceof GroovyBugError) {
            final String message = "encountered bug in Groovy while executing script [" + compiledScript.getId()
                + "]";
            throw new ScriptException(message, assertionError, Collections.<String>emptyList(), compiledScript
                .toString(), compiledScript.getLanguage());
        }
        final StackTraceElement[] elements = assertionError.getStackTrace();
        if (elements.length > 0 && "org.codehaus.groovy.runtime.InvokerHelper".equals(elements[0].getClassName())) {
            throw new ScriptException("error evaluating " + compiledScript.getId(), assertionError,
                Collections.<String>emptyList(), "", compiledScript.getLanguage());
        }
        throw assertionError;
    } catch (Exception e) {
        throw new ScriptException("error evaluating " + compiledScript.getId(), e, Collections.<String>emptyList(),
            "", compiledScript.getLanguage());
    }
}
 
Example #28
Source File: TryCatchStatement.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void addResource(ExpressionStatement resourceStatement) {
    Expression resourceExpression = resourceStatement.getExpression();
    if (!(resourceExpression instanceof DeclarationExpression || resourceExpression instanceof VariableExpression)) {
        throw new GroovyBugError("resourceStatement should be a variable declaration statement or a variable");
    }

    resourceExpression.putNodeMetaData(IS_RESOURCE, Boolean.TRUE);

    resourceStatements.add(resourceStatement);
}
 
Example #29
Source File: Token.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the specified element, or null.
 */
public CSTNode get(int index) {
    if (index > 0) {
        throw new GroovyBugError("attempt to access Token element other than root");
    }

    return this;
}
 
Example #30
Source File: Reduction.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Removes a node from the <code>Reduction</code>.  You cannot remove
 * the root node (index 0).
 */
public CSTNode remove(int index) {
    if (index < 1) {
        throw new GroovyBugError("attempt to remove() root node of Reduction");
    }

    return (CSTNode) elements.remove(index);
}