org.codehaus.groovy.ast.expr.ClassExpression Java Examples

The following examples show how to use org.codehaus.groovy.ast.expr.ClassExpression. 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: InvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Converts sourceType to a non primitive by using Groovy casting.
 * sourceType might be a primitive
 * This might be done using SBA#castToType
 */
public void castToNonPrimitiveIfNecessary(final ClassNode sourceType, final ClassNode targetType) {
    OperandStack os = controller.getOperandStack();
    ClassNode boxedType = os.box();
    if (WideningCategories.implementsInterfaceOrSubclassOf(boxedType, targetType)) return;
    MethodVisitor mv = controller.getMethodVisitor();
    if (ClassHelper.CLASS_Type.equals(targetType)) {
        castToClassMethod.call(mv);
    } else if (ClassHelper.STRING_TYPE.equals(targetType)) {
        castToStringMethod.call(mv);
    } else if (targetType.isDerivedFrom(ClassHelper.Enum_Type)) {
        (new ClassExpression(targetType)).visit(controller.getAcg());
        os.remove(1);
        castToEnumMethod.call(mv);
        BytecodeHelper.doCast(mv, targetType);
    } else {
        (new ClassExpression(targetType)).visit(controller.getAcg());
        os.remove(1);
        castToTypeMethod.call(mv);
    }
}
 
Example #2
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<String> getKnownImmutableClasses(AbstractASTTransformation xform, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(ImmutablePropertyUtils.IMMUTABLE_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    final List<String> immutableClasses = new ArrayList<String>();

    if (anno == null) return immutableClasses;
    final Expression expression = anno.getMember(MEMBER_KNOWN_IMMUTABLE_CLASSES);
    if (expression == null) return immutableClasses;

    if (!(expression instanceof ListExpression)) {
        xform.addError("Use the Groovy list notation [el1, el2] to specify known immutable classes via \"" + MEMBER_KNOWN_IMMUTABLE_CLASSES + "\"", anno);
        return immutableClasses;
    }

    final ListExpression listExpression = (ListExpression) expression;
    for (Expression listItemExpression : listExpression.getExpressions()) {
        if (listItemExpression instanceof ClassExpression) {
            immutableClasses.add(listItemExpression.getType().getName());
        }
    }

    return immutableClasses;
}
 
Example #3
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 #4
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformDeclarationExpression(final DeclarationExpression de) {
    visitAnnotations(de);
    Expression oldLeft = de.getLeftExpression();
    checkingVariableTypeInDeclaration = true;
    Expression left = transform(oldLeft);
    checkingVariableTypeInDeclaration = false;
    if (left instanceof ClassExpression) {
        ClassExpression ce = (ClassExpression) left;
        addError("you tried to assign a value to the class " + ce.getType().getName(), oldLeft);
        return de;
    }
    Expression right = transform(de.getRightExpression());
    if (right == de.getRightExpression()) {
        fixDeclaringClass(de);
        return de;
    }
    DeclarationExpression newDeclExpr = new DeclarationExpression(left, de.getOperation(), right);
    newDeclExpr.setDeclaringClass(de.getDeclaringClass());
    newDeclExpr.addAnnotations(de.getAnnotations());
    newDeclExpr.copyNodeMetaData(de);
    fixDeclaringClass(newDeclExpr);
    return newDeclExpr;
}
 
Example #5
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean findClassWithMatchingBasename(String nameWithoutPackage) {
    // For performance reasons test against classNamePattern first
    if (classNamePattern != null && classNamePattern.matcher(nameWithoutPackage).matches()) {
        return true;
    }

    if (classesToNewify != null) {
        @SuppressWarnings("unchecked")
        List<ClassExpression> classes = (List) classesToNewify.getExpressions();
        for (ClassExpression ce : classes) {
            if (ce.getType().getNameWithoutPackage().equals(nameWithoutPackage)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #6
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private MethodNode addSyntheticMethodForDGSM(MethodNode mn) {
    Parameter[] parameters = removeFirstParameter(mn.getParameters());
    ArgumentListExpression args = args(parameters);
    args.getExpressions().add(0, ConstantExpression.NULL);

    MethodNode syntheticMethodNode = controller.getClassNode().addSyntheticMethod(
            "dgsm$$" + mn.getParameters()[0].getType().getName().replace(".", "$") + "$$" + mn.getName(),
            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
            mn.getReturnType(),
            parameters,
            ClassNode.EMPTY_ARRAY,
            block(
                    returnS(
                            callX(new ClassExpression(mn.getDeclaringClass()), mn.getName(), args)
                    )
            )
    );

    syntheticMethodNode.addAnnotation(new AnnotationNode(GENERATED_TYPE));
    syntheticMethodNode.addAnnotation(new AnnotationNode(COMPILE_STATIC_TYPE));

    return syntheticMethodNode;
}
 
Example #7
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean validateEnumConstant(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        String name = pe.getPropertyAsString();
        if (pe.getObjectExpression() instanceof ClassExpression && name != null) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            if (type.isEnum()) {
                boolean ok = false;
                try {
                    FieldNode enumField = type.getDeclaredField(name);
                    ok = enumField != null && enumField.getType().equals(type);
                } catch(Exception ex) {
                    // ignore
                }
                if(!ok) {
                    addError("No enum const " + type.getName() + "." + name, pe);
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #8
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression annotationValueToExpression (Object value) {
    if (value == null || value instanceof String || value instanceof Number || value instanceof Character || value instanceof Boolean)
        return new ConstantExpression(value);

    if (value instanceof Class)
        return new ClassExpression(ClassHelper.makeWithoutCaching((Class<?>)value));

    if (value.getClass().isArray()) {
        ListExpression elementExprs = new ListExpression();
        int len = Array.getLength(value);
        for (int i = 0; i != len; ++i)
            elementExprs.addExpression(annotationValueToExpression(Array.get(value, i)));
        return elementExprs;
    }

    return null;
}
 
Example #9
Source File: InstanceOfVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    if (expression.getOperation().isA(Types.INSTANCEOF_OPERATOR) &&
            expression.getRightExpression() instanceof ClassExpression) {
        ClassNode referenceType = expression.getRightExpression().getType();

        if (ClassHelper.isPrimitiveType(referenceType)) {
            addTypeError(expression.getRightExpression(), "primitive type " + referenceType.getName());
        } else {
            while (referenceType.isArray()) {
                referenceType = referenceType.getComponentType();
            }

            if (referenceType.isGenericsPlaceHolder()) {
                addTypeError(expression.getRightExpression(), "type parameter " + referenceType.getUnresolvedName() +
                    ". Use its erasure " + referenceType.getNameWithoutPackage() + " instead since further generic type information will be erased at runtime");
            } else if (referenceType.getGenericsTypes() != null) {
                // TODO: Cannot perform instanceof check against parameterized type Class<Type>. Use the form Class<?> instead since further eneric type information will be erased at runtime
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example #10
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public List<ClassNode> getMemberClassList(AnnotationNode anno, String name) {
    List<ClassNode> list = new ArrayList<>();
    Expression expr = anno.getMember(name);
    if (expr == null) {
        return null;
    }
    if (expr instanceof ListExpression) {
        final ListExpression listExpression = (ListExpression) expr;
        if (isUndefinedMarkerList(listExpression)) {
            return null;
        }
        list = getTypeList(listExpression);
    } else if (expr instanceof ClassExpression) {
        ClassNode cn = expr.getType();
        if (isUndefined(cn)) return null;
        if (cn != null) list.add(cn);
    }
    return list;
}
 
Example #11
Source File: PicocliScriptASTTransformation.java    From picocli with Apache License 2.0 6 votes vote down vote up
private void changeBaseScriptTypeFromPackageOrImport(final SourceUnit source, final AnnotatedNode parent, final AnnotationNode node) {
    Expression value = node.getMember("value");
    ClassNode scriptType;
    if (value == null) {
        scriptType = BASE_SCRIPT_TYPE;
    } else {
        if (!(value instanceof ClassExpression)) {
            addError("Annotation " + MY_TYPE_NAME + " member 'value' should be a class literal.", value);
            return;
        }
        scriptType = value.getType();
    }
    List<ClassNode> classes = source.getAST().getClasses();
    for (ClassNode classNode : classes) {
        if (classNode.isScriptBody()) {
            changeBaseScriptType(source, parent, classNode, scriptType, node);
        }
    }
}
 
Example #12
Source File: InvokeDynamicWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean makeCachedCall(Expression origin, ClassExpression sender,
        Expression receiver, Expression message, Expression arguments,
        MethodCallerMultiAdapter adapter, boolean safe, boolean spreadSafe,
        boolean implicitThis, boolean containsSpreadExpression
) {
    // fixed number of arguments && name is a real String and no GString
    if ((adapter == null || adapter == invokeMethod || adapter == invokeMethodOnCurrent || adapter == invokeStaticMethod) && !spreadSafe) {
        String methodName = getMethodName(message);
        if (methodName != null) {
            makeIndyCall(adapter, receiver, implicitThis, safe, methodName, arguments);
            return true;
        }
    }
    return false;
}
 
Example #13
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean getField(final PropertyExpression expression, final Expression receiver, ClassNode receiverType, final String name) {
    boolean safe = expression.isSafe();
    boolean implicitThis = expression.isImplicitThis();

    if (makeGetField(receiver, receiverType, name, safe, implicitThis)) return true;
    if (receiver instanceof ClassExpression) {
        if (makeGetField(receiver, receiver.getType(), name, safe, implicitThis)) return true;
        if (makeGetPrivateFieldWithBridgeMethod(receiver, receiver.getType(), name, safe, implicitThis)) return true;
    }
    if (makeGetPrivateFieldWithBridgeMethod(receiver, receiverType, name, safe, implicitThis)) return true;

    boolean isClassReceiver = false;
    if (isClassClassNodeWrappingConcreteType(receiverType)) {
        isClassReceiver = true;
        receiverType = receiverType.getGenericsTypes()[0].getType();
    }
    if (isClassReceiver && makeGetField(receiver, CLASS_Type, name, safe, false)) return true;
    if (receiverType.isEnum()) {
        controller.getMethodVisitor().visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(receiverType), name, BytecodeHelper.getTypeDescription(receiverType));
        controller.getOperandStack().push(receiverType);
        return true;
    }
    return false;
}
 
Example #14
Source File: TypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Given a method call, first checks that it's a static method call, and if it is, returns the
 * class node for the receiver. For example, with the following code:
 * <code></code>Person.findAll { ... }</code>, it would return the class node for <i>Person</i>.
 * If it's not a static method call, returns null.
 * @param call a method call
 * @return null if it's not a static method call, or the class node for the receiver instead.
 */
public ClassNode extractStaticReceiver(MethodCall call) {
    if (call instanceof StaticMethodCallExpression) {
        return ((StaticMethodCallExpression) call).getOwnerType();
    } else if (call instanceof MethodCallExpression) {
        Expression objectExpr = ((MethodCallExpression) call).getObjectExpression();
        if (objectExpr instanceof ClassExpression && ClassHelper.CLASS_Type.equals(objectExpr.getType())) {
            GenericsType[] genericsTypes = objectExpr.getType().getGenericsTypes();
            if (genericsTypes!=null && genericsTypes.length==1) {
                return genericsTypes[0].getType();
            }
        }
        if (objectExpr instanceof ClassExpression) {
            return objectExpr.getType();
        }
    }
    return null;
}
 
Example #15
Source File: Traits.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Collects all the self types that a type should extend or implement, given
 * the traits is implements.
 * @param receiver a class node that may implement a trait
 * @param selfTypes a collection where the list of self types will be written
 * @param checkInterfaces should the interfaces that the node implements be collected too
 * @param checkSuper should we collect from the superclass too
 * @return the selfTypes collection itself
 * @since 2.4.0
 */
public static LinkedHashSet<ClassNode> collectSelfTypes(
        ClassNode receiver,
        LinkedHashSet<ClassNode> selfTypes,
        boolean checkInterfaces,
        boolean checkSuper) {
    if (Traits.isTrait(receiver)) {
        List<AnnotationNode> annotations = receiver.getAnnotations(SELFTYPE_CLASSNODE);
        for (AnnotationNode annotation : annotations) {
            Expression value = annotation.getMember("value");
            if (value instanceof ClassExpression) {
                selfTypes.add(value.getType());
            } else if (value instanceof ListExpression) {
                List<Expression> expressions = ((ListExpression) value).getExpressions();
                for (Expression expression : expressions) {
                    if (expression instanceof ClassExpression) {
                        selfTypes.add(expression.getType());
                    }
                }
            }
        }
    }
    if (checkInterfaces) {
        ClassNode[] interfaces = receiver.getInterfaces();
        for (ClassNode anInterface : interfaces) {
            collectSelfTypes(anInterface, selfTypes, true, checkSuper);
        }
    }

    if (checkSuper) {
        ClassNode superClass = receiver.getSuperClass();
        if (superClass != null) {
            collectSelfTypes(superClass, selfTypes, checkInterfaces, true);
        }
    }
    return selfTypes;
}
 
Example #16
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isGroovyObject(final Expression objectExpression) {
    if (isThisExpression(objectExpression)) return true;
    if (objectExpression instanceof ClassExpression) return false;

    ClassNode objectExpressionType = controller.getTypeChooser().resolveType(objectExpression, controller.getClassNode());
    if (objectExpressionType.equals(ClassHelper.OBJECT_TYPE)) objectExpressionType = objectExpression.getType();
    return objectExpressionType.isDerivedFromGroovyObject();
}
 
Example #17
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void makeCall(Expression origin, ClassExpression sender, Expression receiver, Expression message, Expression arguments, MethodCallerMultiAdapter adapter, boolean safe, boolean spreadSafe, boolean implicitThis) {
    // direct method call paths
    boolean containsSpreadExpression = AsmClassGenerator.containsSpreadExpression(arguments);

    if (makeDirectCall(origin, receiver, message, arguments, adapter, implicitThis, containsSpreadExpression)) return;

    // normal path
    if (makeCachedCall(origin, sender, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis, containsSpreadExpression)) return;

    // path through ScriptBytecodeAdapter
    makeUncachedCall(origin, sender, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis, containsSpreadExpression);
}
 
Example #18
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected boolean makeCachedCall(Expression origin, ClassExpression sender, Expression receiver, Expression message, Expression arguments, MethodCallerMultiAdapter adapter, boolean safe, boolean spreadSafe, boolean implicitThis, boolean containsSpreadExpression) {
    // prepare call site
    if ((adapter == invokeMethod || adapter == invokeMethodOnCurrent || adapter == invokeStaticMethod) && !spreadSafe) {
        String methodName = getMethodName(message);
        if (methodName != null) {
            controller.getCallSiteWriter().makeCallSite(receiver, methodName, arguments, safe, implicitThis, adapter == invokeMethodOnCurrent, adapter == invokeStaticMethod);
            return true;
        }
    }
    return false;
}
 
Example #19
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void loadWrapper(final Expression argument) {
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode goalClass = argument.getType();
    visitClassExpression(new ClassExpression(goalClass));
    if (goalClass.isDerivedFromGroovyObject()) {
        createGroovyObjectWrapperMethod.call(mv);
    } else {
        createPojoWrapperMethod.call(mv);
    }
    controller.getOperandStack().remove(1);
}
 
Example #20
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitClassExpression(final ClassExpression expression) {
    ClassNode type = expression.getType();
    MethodVisitor mv = controller.getMethodVisitor();
    if (BytecodeHelper.isClassLiteralPossible(type) || BytecodeHelper.isSameCompilationUnit(controller.getClassNode(), type)) {
        if (controller.getClassNode().isInterface()) {
            InterfaceHelperClassNode interfaceClassLoadingClass = controller.getInterfaceClassLoadingClass();
            if (BytecodeHelper.isClassLiteralPossible(interfaceClassLoadingClass)) {
                BytecodeHelper.visitClassLiteral(mv, interfaceClassLoadingClass);
                controller.getOperandStack().push(ClassHelper.CLASS_Type);
                return;
            }
        } else {
            BytecodeHelper.visitClassLiteral(mv, type);
            controller.getOperandStack().push(ClassHelper.CLASS_Type);
            return;
        }
    }
    String staticFieldName = getStaticFieldName(type);
    referencedClasses.put(staticFieldName, type);

    String internalClassName = controller.getInternalClassName();
    if (controller.getClassNode().isInterface()) {
        internalClassName = BytecodeHelper.getClassInternalName(controller.getInterfaceClassLoadingClass());
        mv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
    } else {
        mv.visitMethodInsn(INVOKESTATIC, internalClassName, "$get$" + staticFieldName, "()Ljava/lang/Class;", false);
    }
    controller.getOperandStack().push(ClassHelper.CLASS_Type);
}
 
Example #21
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * if Class.forName(x) is recognized, make a direct method call
 */
protected boolean makeClassForNameCall(final Expression origin, final Expression receiver, final Expression message, final Expression arguments) {
    if (!(receiver instanceof ClassExpression)) return false;
    ClassExpression ce = (ClassExpression) receiver;
    if (!ClassHelper.CLASS_Type.equals(ce.getType())) return false;
    String msg = getMethodName(message);
    if (!"forName".equals(msg)) return false;
    ArgumentListExpression ae = makeArgumentList(arguments);
    if (ae.getExpressions().size() != 1) return false;
    return writeDirectMethodCall(CLASS_FOR_NAME_STRING, false, receiver, ae);
}
 
Example #22
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static int determineCommonArrayType(final List<Expression> values) {
    Expression expr = values.get(0);
    int arrayElementType = -1;
    if (expr instanceof AnnotationConstantExpression) {
        arrayElementType = 1;
    } else if (expr instanceof ConstantExpression) {
        arrayElementType = 2;
    } else if (expr instanceof ClassExpression) {
        arrayElementType = 3;
    } else if (expr instanceof PropertyExpression) {
        arrayElementType = 4;
    }
    return arrayElementType;
}
 
Example #23
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPrivateMethodCallOnThisInClosure(final MethodCallExpression call,
                                                             final Expression arguments, final String methodName) {
    ArgumentListExpression newArgs = createArgumentList(arguments);
    MethodCallExpression transformed = new MethodCallExpression(
            new ClassExpression(traitHelperClass),
            methodName,
            newArgs
    );
    transformed.setSourcePosition(call);
    transformed.setSafe(call.isSafe());
    transformed.setSpreadSafe(call.isSpreadSafe());
    transformed.setImplicitThis(true);
    return transformed;
}
 
Example #24
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isTraitSuperPropertyExpression(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pexp = (PropertyExpression) exp;
        Expression objectExpression = pexp.getObjectExpression();
        if (objectExpression instanceof ClassExpression) {
            ClassNode type = objectExpression.getType();
            if (Traits.isTrait(type) && "super".equals(pexp.getPropertyAsString())) {
                return true;
            }
        }
    }
    return false;
}
 
Example #25
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformMethodCallExpression(final MethodCallExpression exp) {
    if (isTraitSuperPropertyExpression(exp.getObjectExpression())) {
        Expression objectExpression = exp.getObjectExpression();
        ClassNode traitReceiver = ((PropertyExpression) objectExpression).getObjectExpression().getType();

        if (traitReceiver != null) {
            // (SomeTrait.super).foo() --> SomeTrait$Helper.foo(this)
            ClassExpression receiver = new ClassExpression(
                    getHelper(traitReceiver)
            );
            ArgumentListExpression newArgs = new ArgumentListExpression();
            Expression arguments = exp.getArguments();
            newArgs.addExpression(new VariableExpression("this"));
            if (arguments instanceof TupleExpression) {
                List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
                for (Expression expression : expressions) {
                    newArgs.addExpression(transform(expression));
                }
            } else {
                newArgs.addExpression(transform(arguments));
            }
            MethodCallExpression result = new MethodCallExpression(
                    receiver,
                    transform(exp.getMethod()),
                    newArgs
            );
            result.setImplicitThis(false);
            result.setSpreadSafe(exp.isSpreadSafe());
            result.setSafe(exp.isSafe());
            result.setSourcePosition(exp);
            return result;
        }
    }
    return super.transform(exp);
}
 
Example #26
Source File: CategoryASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getTargetClass(SourceUnit source, AnnotationNode annotation) {
    Expression value = annotation.getMember("value");
    if (!(value instanceof ClassExpression)) {
        //noinspection ThrowableInstanceNeverThrown
        source.getErrorCollector().addErrorAndContinue("@groovy.lang.Category must define 'value' which is the class to apply this category to", annotation, source);
        return null;
    } else {
        ClassExpression ce = (ClassExpression) value;
        return ce.getType();
    }
}
 
Example #27
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean isUndefinedMarkerList(ListExpression listExpression) {
    if (listExpression.getExpressions().size() != 1) return false;
    Expression itemExpr = listExpression.getExpression(0);
    if (itemExpr == null) return false;
    if (itemExpr instanceof ConstantExpression) {
        Object value = ((ConstantExpression) itemExpr).getValue();
        if (value instanceof String && isUndefined((String)value)) return true;
    } else if (itemExpr instanceof ClassExpression && isUndefined(itemExpr.getType())) {
        return true;
    }
    return false;
}
 
Example #28
Source File: StaticMethodCallExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
Expression transformStaticMethodCallExpression(final StaticMethodCallExpression orig) {
    MethodNode target = (MethodNode) orig.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
    if (target != null) {
        MethodCallExpression call = new MethodCallExpression(
                new ClassExpression(orig.getOwnerType()),
                orig.getMethod(),
                orig.getArguments()
        );
        call.setMethodTarget(target);
        call.setSourcePosition(orig);
        call.copyNodeMetaData(orig);
        return transformer.transform(call);
    }
    return transformer.superTransform(orig);
}
 
Example #29
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitClassExpression(ClassExpression node) {
	pushASTNode(node);
	try {
		super.visitClassExpression(node);
	} finally {
		popASTNode();
	}
}
 
Example #30
Source File: BaseScriptASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void changeBaseScriptTypeFromPackageOrImport(final SourceUnit source, final AnnotatedNode parent, final AnnotationNode node) {
    Expression value = node.getMember("value");
    if (!(value instanceof ClassExpression)) {
        addError("Annotation " + MY_TYPE_NAME + " member 'value' should be a class literal.", value);
        return;
    }
    List<ClassNode> classes = source.getAST().getClasses();
    for (ClassNode classNode : classes) {
        if (classNode.isScriptBody()) {
            changeBaseScriptType(parent, classNode, value.getType());
        }
    }
}