org.codehaus.groovy.ast.ClassNode Java Examples

The following examples show how to use org.codehaus.groovy.ast.ClassNode. 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: ImmutableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static boolean isSpecialNamedArgCase(List<PropertyNode> list, boolean checkSize) {
    if (checkSize && list.size() != 1) return false;
    if (list.size() == 0) return false;
    ClassNode firstParamType = list.get(0).getField().getType();
    if (firstParamType.equals(ClassHelper.MAP_TYPE)) {
        return true;
    }
    ClassNode candidate = HMAP_TYPE;
    while (candidate != null) {
        if (candidate.equals(firstParamType)) {
            return true;
        }
        candidate = candidate.getSuperClass();
    }
    return false;
}
 
Example #2
Source File: BuilderASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected boolean unsupportedAttribute(BuilderASTTransformation transform, AnnotationNode anno, String memberName, String extraMessage) {
    Object memberValue = transform.getMemberValue(anno, memberName);
    if (memberValue instanceof String && isUndefined((String) memberValue)) return false;
    if (memberValue == null) {
        memberValue = transform.getMemberClassValue(anno, memberName);
        if (memberValue != null && isUndefined((ClassNode) memberValue)) {
            memberValue = null;
        }
    }
    if (memberValue != null) {
        String message = extraMessage.length() == 0 ? "" : " " + extraMessage;
        transform.addError("Error during " + MY_TYPE_NAME + " processing: Annotation attribute '" + memberName + "' not supported by " + getClass().getName() + message, anno);
        return true;
    }
    return false;
}
 
Example #3
Source File: OperandStack.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean convertFromDouble(ClassNode target) {
    MethodVisitor mv = controller.getMethodVisitor();
    if (target==ClassHelper.int_TYPE){
        mv.visitInsn(D2I);
        return true;
    } else if ( target==ClassHelper.char_TYPE ||
                target==ClassHelper.byte_TYPE ||
                target==ClassHelper.short_TYPE)
    {
        mv.visitInsn(D2I);
        return convertFromInt(target);
    } else if (target==ClassHelper.long_TYPE){
        mv.visitInsn(D2L);
        return true;
    } else if (target==ClassHelper.float_TYPE){
        mv.visitInsn(D2F);
        return true;
    } 
    return false;
}
 
Example #4
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void writeGenericsBounds(PrintWriter out, GenericsType genericsType) {
    if (genericsType.isPlaceholder()) {
        out.print(genericsType.getName());
    } else {
        printTypeName(genericsType.getType(), out);
        ClassNode[] upperBounds = genericsType.getUpperBounds();
        ClassNode lowerBound = genericsType.getLowerBound();
        if (upperBounds != null) {
            out.print(" extends ");
            for (int i = 0; i < upperBounds.length; i++) {
                printType(upperBounds[i], out);
                if (i + 1 < upperBounds.length) {
                    out.print(" & ");
                }
            }
        } else if (lowerBound != null) {
            out.print(" super ");
            printType(lowerBound, out);
        }
    }
}
 
Example #5
Source File: GremlinGroovyScriptEngine.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void registerBindingTypes(final ScriptContext context) {
    if (typeCheckingEnabled) {
        final Map<String, ClassNode> variableTypes = new HashMap<>();
        clearVarTypes();

        // use null for the classtype if the binding value itself is null - not fully sure if that is
        // a sound way to deal with that.  didn't see a class type for null - maybe it should just be
        // unknown and be "Object".  at least null is properly being accounted for now.
        context.getBindings(ScriptContext.GLOBAL_SCOPE).forEach((k, v) ->
                variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));
        context.getBindings(ScriptContext.ENGINE_SCOPE).forEach((k, v) ->
                variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));

        COMPILE_OPTIONS.get().put(COMPILE_OPTIONS_VAR_TYPES, variableTypes);
    }
}
 
Example #6
Source File: OperandStack.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean convertFromLong(ClassNode target) {
    MethodVisitor mv = controller.getMethodVisitor();
    if (target==ClassHelper.int_TYPE){
        mv.visitInsn(L2I);
        return true;
    } else if ( target==ClassHelper.char_TYPE ||
                target==ClassHelper.byte_TYPE ||
                target==ClassHelper.short_TYPE)
    {
        mv.visitInsn(L2I);
        return convertFromInt(target);
    } else if (target==ClassHelper.double_TYPE){
        mv.visitInsn(L2D);
        return true;
    } else if (target==ClassHelper.float_TYPE){
        mv.visitInsn(L2F);
        return true;
    } 
    return false;
}
 
Example #7
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement createConstructorStatementCollection(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    ClassNode fieldType = fieldExpr.getType();
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = ifElseS(
            isInstanceOfX(param, CLONEABLE_TYPE),
            assignS(fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(param, fieldType), fieldType)),
            assignS(fieldExpr, cloneCollectionExpr(param, fieldType)));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example #8
Source File: StaticTypesUnaryExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void writeNotExpression(final NotExpression expression) {
    TypeChooser typeChooser = controller.getTypeChooser();
    Expression subExpression = expression.getExpression();
    ClassNode classNode = controller.getClassNode();
    if (typeChooser.resolveType(subExpression, classNode) == boolean_TYPE) {
        subExpression.visit(controller.getAcg());
        controller.getOperandStack().doGroovyCast(boolean_TYPE);
        BytecodeExpression bytecodeExpression = bytecodeX(mv -> {
            Label ne = new Label();
            mv.visitJumpInsn(IFNE, ne);
            mv.visitInsn(ICONST_1);
            Label out = new Label();
            mv.visitJumpInsn(GOTO, out);
            mv.visitLabel(ne);
            mv.visitInsn(ICONST_0);
            mv.visitLabel(out);
        });
        bytecodeExpression.visit(controller.getAcg());
        controller.getOperandStack().remove(1);
        return;
    }
    super.writeNotExpression(expression);
}
 
Example #9
Source File: StaticTypesLambdaWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Parameter[] createParametersWithExactType(final LambdaExpression expression) {
    Parameter[] parameters = expression.getParameters();
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    }

    for (Parameter parameter : parameters) {
        ClassNode inferredType = parameter.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
        if (inferredType == null) {
            continue;
        }

        ClassNode type = convertParameterType(parameter.getType(), inferredType);

        parameter.setType(type);
        parameter.setOriginType(type);
    }

    return parameters;
}
 
Example #10
Source File: PropertyTest.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void testInheritedProperties() throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC + ACC_SUPER, ClassHelper.make(DummyBean.class));
    classNode.addProperty(new PropertyNode("bar", ACC_PUBLIC, ClassHelper.STRING_TYPE, classNode, null, null, null));

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    Object bean = fooClass.getDeclaredConstructor().newInstance();
    assertTrue("Managed to create bean", bean != null);

    assertField(fooClass, "bar", 0, ClassHelper.STRING_TYPE);

    assertGetProperty(bean, "name", "James");
    assertSetProperty(bean, "name", "Bob");

    assertGetProperty(bean, "bar", null);
    assertSetProperty(bean, "bar", "newValue");
}
 
Example #11
Source File: CategoryASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean ensureNoInstanceFieldOrProperty(final SourceUnit source, final ClassNode parent) {
    boolean valid = true;
    for (FieldNode fieldNode : parent.getFields()) {
        if (!fieldNode.isStatic() && fieldNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(fieldNode,  source);
            valid = false;
        }
    }
    for (PropertyNode propertyNode : parent.getProperties()) {
        if (!propertyNode.isStatic() && propertyNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(propertyNode, source);
            valid = false;
        }
    }
    return valid;
}
 
Example #12
Source File: LegacyHashMapPropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateProperties(AbstractASTTransformation xform, BlockStatement body, ClassNode cNode, List<PropertyNode> props) {
    if (!(props.size() == 1 && props.get(0).getType().equals(HMAP_TYPE))) {
        xform.addError("Error during " + xform.getAnnotationName() + " processing. Property handler " + getClass().getName() + " only accepts a single HashMap property", props.size() == 1 ? props.get(0) : cNode);
        return false;
    }
    return true;
}
 
Example #13
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<String> getInstanceNonPropertyFieldNames(final ClassNode cNode) {
    List<FieldNode> fList = getInstanceNonPropertyFields(cNode);
    List<String> result = new ArrayList<>(fList.size());
    for (FieldNode fNode : fList) {
        result.add(fNode.getName());
    }
    return result;
}
 
Example #14
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected boolean resolveFromCompileUnit(final ClassNode type) {
    // look into the compile unit if there is a class with that name
    CompileUnit compileUnit = currentClass.getCompileUnit();
    if (compileUnit == null) return false;
    ClassNode cuClass = compileUnit.getClass(type.getName());
    if (cuClass != null) {
        if (type != cuClass) type.setRedirect(cuClass);
        return true;
    }
    return false;
}
 
Example #15
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void collectTraits(final Class clazz, final Set<ClassNode> traits) {
    Annotation annotation = clazz.getAnnotation(Trait.class);
    if (annotation != null) {
        ClassNode trait = ClassHelper.make(clazz);
        traits.add(trait.getPlainNodeReference());
        LinkedHashSet<ClassNode> selfTypes = new LinkedHashSet<ClassNode>();
        Traits.collectSelfTypes(trait, selfTypes, true, true);
        for (ClassNode selfType : selfTypes) {
            if (Traits.isTrait(selfType)) {
                traits.add(selfType.getPlainNodeReference());
            }
        }
    }
}
 
Example #16
Source File: LegacyHashMapPropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Statement createPropInit(AbstractASTTransformation xform, AnnotationNode anno, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    FieldNode fNode = pNode.getField();
    if (fNode.isFinal() && fNode.isStatic()) return null;
    if (fNode.isFinal() && fNode.getInitialExpression() != null) {
        return checkFinalArgNotOverridden(cNode, fNode);
    }
    return createLegacyConstructorStatementMapSpecial(fNode);
}
 
Example #17
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public List<AnnotationNode> getAnnotations() {
    List<AnnotationNode> nodes = new LinkedList<AnnotationNode>();
    for (ClassNode delegate : delegates) {
        List<AnnotationNode> annotations = delegate.getAnnotations();
        if (annotations != null) nodes.addAll(annotations);
    }
    return nodes;
}
 
Example #18
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Map<String, ClassNode> addMethodGenerics(MethodNode current, Map<String, ClassNode> oldSpec) {
    Map<String, ClassNode> newSpec = new HashMap<>(oldSpec);
    GenericsType[] gts = current.getGenericsTypes();
    if (gts != null) {
        for (GenericsType gt : gts) {
            String name = gt.getName();
            ClassNode type = gt.getType();
            if (gt.isPlaceholder()) {
                ClassNode redirect;
                if (gt.getUpperBounds() != null) {
                    redirect = gt.getUpperBounds()[0];
                } else if (gt.getLowerBound() != null) {
                    redirect = gt.getLowerBound();
                } else {
                    redirect = ClassHelper.OBJECT_TYPE;
                }
                if (redirect.isGenericsPlaceHolder()) {
                    // "T extends U" or "T super U"
                    type = redirect;
                } else {
                    // "T" or "T extends Thing" or "T super Thing"
                    type = ClassHelper.makeWithoutCaching(name);
                    type.setGenericsPlaceHolder(true);
                    type.setRedirect(redirect);
                }
            }
            newSpec.put(name, type);
        }
    }
    return newSpec;
}
 
Example #19
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected boolean resolveToOuter(final ClassNode type) {
    String name = type.getName();

    // We do not need to check instances of LowerCaseClass
    // to be a Class, because unless there was an import for
    // for this we do not lookup these cases. This was a decision
    // made on the mailing list. To ensure we will not visit this
    // method again we set a NO_CLASS for this name
    if (type instanceof LowerCaseClass) {
        classNodeResolver.cacheClass(name, ClassNodeResolver.NO_CLASS);
        return false;
    }

    if (currentClass.getModule().hasPackageName() && name.indexOf('.') == -1) return false;

    LookupResult lr = classNodeResolver.resolveName(name, compilationUnit);
    if (lr != null) {
        if (lr.isSourceUnit()) {
            SourceUnit su = lr.getSourceUnit();
            currentClass.getCompileUnit().addClassNodeToCompile(type, su);
        } else {
            type.setRedirect(lr.getClassNode());
        }
        return true;
    }

    return false;
}
 
Example #20
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a primitive type to boolean.
 *
 * @param mv method visitor
 * @param type primitive type to convert
 */
public static void convertPrimitiveToBoolean(MethodVisitor mv, ClassNode type) {
    if (type == boolean_TYPE) {
        return;
    }
    // Special handling is done for floating point types in order to
    // handle checking for 0 or NaN values.
    if (type == double_TYPE) {
        convertDoubleToBoolean(mv);
        return;
    } else if (type == float_TYPE) {
        convertFloatToBoolean(mv);
        return;
    }
    Label trueLabel = new Label();
    Label falseLabel = new Label();
    // Convert long to int for IFEQ comparison using LCMP
    if (type== long_TYPE) {
        mv.visitInsn(LCONST_0);
        mv.visitInsn(LCMP);
    }
    // This handles byte, short, char and int
    mv.visitJumpInsn(IFEQ, falseLabel);
    mv.visitInsn(ICONST_1);
    mv.visitJumpInsn(GOTO, trueLabel);
    mv.visitLabel(falseLabel);
    mv.visitInsn(ICONST_0);
    mv.visitLabel(trueLabel);
}
 
Example #21
Source File: GenericsVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static String getPrintName(ClassNode cn) {
    StringBuilder ret = new StringBuilder(cn.getName());
    GenericsType[] gts = cn.getGenericsTypes();
    if (gts != null) {
        ret.append("<");
        for (int i = 0; i < gts.length; i++) {
            if (i != 0) ret.append(",");
            ret.append(getPrintName(gts[i]));
        }
        ret.append(">");
    }
    return ret.toString();
}
 
Example #22
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MethodNode getCompatibleMethod(final ClassNode current, final String getAt, final ClassNode aType) {
    // TODO this really should find "best" match or find all matches and complain about ambiguity if more than one
    // TODO handle getAt with more than one parameter
    // TODO handle default getAt methods on Java 8 interfaces
    for (MethodNode methodNode : current.getDeclaredMethods("getAt")) {
        if (methodNode.getParameters().length == 1) {
            ClassNode paramType = methodNode.getParameters()[0].getType();
            if (aType.isDerivedFrom(paramType) || aType.declaresInterface(paramType)) {
                return methodNode;
            }
        }
    }
    return null;
}
 
Example #23
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addMethodOccurrences(MethodNode visitedMethod, ClassNode findingNode) {
    // Check return type
    addOccurrences(visitedMethod.getReturnType(), findingNode);

    // Check method parameters
    for (Parameter parameter : visitedMethod.getParameters()) {
        addOccurrences(parameter.getType(), findingNode);
    }

    // Check annotations
    for (AnnotationNode annotation : visitedMethod.getAnnotations(findingNode)) {
        addAnnotationOccurrences(annotation, findingNode);
    }
}
 
Example #24
Source File: AbstractFunctionalInterfaceWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
default ClassNode getFunctionalInterfaceType(Expression expression) {
    ClassNode type = expression.getNodeMetaData(PARAMETER_TYPE);

    if (null == type) {
        type = expression.getNodeMetaData(INFERRED_FUNCTIONAL_INTERFACE_TYPE);
    }
    return type;
}
 
Example #25
Source File: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Annotation getTransformClassAnnotation(final ClassNode annotationType) {
    if (!annotationType.isResolved()) return null;

    for (Annotation a : annotationType.getTypeClass().getAnnotations()) {
        // clients are free to choose any GroovyClassLoader for resolving a
        // ClassNode such as annotationType; we have to compare by name and
        // cannot cast the return value to our GroovyASTTransformationClass
        if (a.annotationType().getName().equals(GroovyASTTransformationClass.class.getName())) {
            return a;
        }
    }

    return null;
}
 
Example #26
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * swap two top level operands
 */
public void swap() {
    MethodVisitor mv = controller.getMethodVisitor();
    int size = stack.size();
    ClassNode b = stack.get(size-1);
    ClassNode a = stack.get(size-2);
    //        dup_x1:     --- 
    //        dup_x2:     aab  -> baab
    //        dup2_x1:    abb  -> bbabb
    //        dup2_x2:    aabb -> bbaabb
    //        b = top element, a = element under b
    //        top element at right
    if (isTwoSlotType(a)) { // aa
        if (isTwoSlotType(b)) { // aabb
            // aabb -> bbaa
            mv.visitInsn(DUP2_X2);   // bbaabb
            mv.visitInsn(POP2);      // bbaa
        } else {
            // aab -> baa
            mv.visitInsn(DUP_X2);   // baab
            mv.visitInsn(POP);      // baa
        }
    } else { // a
        if (isTwoSlotType(b)) { //abb
            // abb -> bba
            mv.visitInsn(DUP2_X1);   // bbabb
            mv.visitInsn(POP2);      // bba
        } else {
            // ab -> ba
            mv.visitInsn(SWAP);
        }
    }
    stack.set(size-1,a);
    stack.set(size-2,b);
}
 
Example #27
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ClassNode box() {
    MethodVisitor mv = controller.getMethodVisitor();
    int size = stack.size();
    ClassNode type = stack.get(size-1);
    if (ClassHelper.isPrimitiveType(type) && ClassHelper.VOID_TYPE!=type) {
        ClassNode wrapper = ClassHelper.getWrapper(type);
        BytecodeHelper.doCastToWrappedType(mv, type, wrapper);
        type = wrapper;
    } // else nothing to box
    stack.set(size-1, type);
    return type;
}
 
Example #28
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
    ClassNode type = node.getDeclaringClass();
    ClassNode superType = type.getUnresolvedSuperClass();

    Parameter[] bestMatch = null;
    for (ConstructorNode c : superType.getDeclaredConstructors()) {
        // Only look at things we can actually call
        if (!c.isPublic() && !c.isProtected()) continue;
        Parameter[] parameters = c.getParameters();
        // workaround for GROOVY-5859: remove generic type info
        Parameter[] copy = new Parameter[parameters.length];
        for (int i = 0; i < copy.length; i++) {
            Parameter orig = parameters[i];
            copy[i] = new Parameter(orig.getOriginType().getPlainNodeReference(), orig.getName());
        }
        if (noExceptionToAvoid(node,c)) return copy;
        if (bestMatch==null) bestMatch = copy;
    }
    if (bestMatch!=null) return bestMatch;

    // fall back for parameterless constructor
    if (superType.isPrimaryClassNode()) {
        return Parameter.EMPTY_ARRAY;
    }

    return null;
}
 
Example #29
Source File: DetectorTransform.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example #30
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addWeakerAccessError(ClassNode cn, MethodNode method, Parameter[] parameters, MethodNode superMethod) {
    StringBuilder msg = new StringBuilder();
    msg.append(method.getName());
    appendParamsDescription(parameters, msg);
    msg.append(" in ");
    msg.append(cn.getName());
    msg.append(" cannot override ");
    msg.append(superMethod.getName());
    msg.append(" in ");
    msg.append(superMethod.getDeclaringClass().getName());
    msg.append("; attempting to assign weaker access privileges; was ");
    msg.append(superMethod.isPublic() ? "public" : (superMethod.isProtected() ? "protected" : "package-private"));
    addError(msg.toString(), method);
}