Java Code Examples for org.codehaus.groovy.ast.ClassNode#getName()

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getName() . 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: PropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static PropertyHandler createPropertyHandler(AbstractASTTransformation xform, GroovyClassLoader loader, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(PROPERTY_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    if (anno == null) return new groovy.transform.options.DefaultPropertyHandler();

    ClassNode handlerClass = xform.getMemberClassValue(anno, "propertyHandler", ClassHelper.make(groovy.transform.options.DefaultPropertyHandler.class));

    if (handlerClass == null) {
        xform.addError("Couldn't determine propertyHandler class", anno);
        return null;
    }

    String className = handlerClass.getName();
    try {
        Object instance = loader.loadClass(className).getDeclaredConstructor().newInstance();
        if (!PropertyHandler.class.isAssignableFrom(instance.getClass())) {
            xform.addError("The propertyHandler class '" + handlerClass.getName() + "' on " + xform.getAnnotationName() + " is not a propertyHandler", anno);
            return null;
        }

        return (PropertyHandler) instance;
    } catch (Exception e) {
        xform.addError("Can't load propertyHandler '" + className + "' " + e, anno);
        return null;
    }
}
 
Example 2
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ConstantExpression getConstantExpression(Expression exp, ClassNode attrType) {
    Expression result = exp;
    if (!(result instanceof ConstantExpression)) {
        result = transformInlineConstants(result, attrType);
    }
    if (result instanceof ConstantExpression) {
        return (ConstantExpression) result;
    }
    String base = "Expected '" + exp.getText() + "' to be an inline constant of type " + attrType.getName();
    if (exp instanceof PropertyExpression) {
        addError(base + " not a property expression", exp);
    } else if (exp instanceof VariableExpression && ((VariableExpression)exp).getAccessedVariable() instanceof FieldNode) {
        addError(base + " not a field expression", exp);
    } else {
        addError(base, exp);
    }
    ConstantExpression ret = new ConstantExpression(null);
    ret.setSourcePosition(exp);
    return ret;
}
 
Example 3
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static FieldNode getMetaClassField(ClassNode node) {
    FieldNode ret = node.getDeclaredField("metaClass");
    if (ret != null) {
        ClassNode mcFieldType = ret.getType();
        if (!mcFieldType.equals(ClassHelper.METACLASS_TYPE)) {
            throw new RuntimeParserException("The class " + node.getName() +
                    " cannot declare field 'metaClass' of type " + mcFieldType.getName() + " as it needs to be of " +
                    "the type " + ClassHelper.METACLASS_TYPE.getName() + " for internal groovy purposes", ret);
        }
        return ret;
    }
    ClassNode current = node;
    while (current != ClassHelper.OBJECT_TYPE) {
        current = current.getSuperClass();
        if (current == null) break;
        ret = current.getDeclaredField("metaClass");
        if (ret == null) continue;
        if (isPrivate(ret.getModifiers())) continue;
        return ret;
    }
    return null;
}
 
Example 4
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Formats a type name into a human readable version. For arrays, appends "[]" to the formatted
 * type name of the component. For unit class nodes, uses the class node name.
 *
 * @param cNode the type to format
 * @return a human readable version of the type name (java.lang.String[] for example)
 */
public static String formatTypeName(ClassNode cNode) {
    if (cNode.isArray()) {
        ClassNode it = cNode;
        int dim = 0;
        while (it.isArray()) {
            dim++;
            it = it.getComponentType();
        }
        StringBuilder sb = new StringBuilder(it.getName().length() + 2 * dim);
        sb.append(it.getName());
        for (int i = 0; i < dim; i++) {
            sb.append("[]");
        }
        return sb.toString();
    }
    return cNode.getName();
}
 
Example 5
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void newifyClass(ClassNode cNode, boolean autoFlag, ListExpression list, final Pattern cnPattern) {
    String cName = cNode.getName();
    if (cNode.isInterface()) {
        addError("Error processing interface '" + cName + "'. @"
                + MY_NAME + " not allowed for interfaces.", cNode);
    }

    final ListExpression oldClassesToNewify = classesToNewify;
    final boolean oldAuto = auto;
    final Pattern oldCnPattern = classNamePattern;

    classesToNewify = list;
    auto = autoFlag;
    classNamePattern = cnPattern;

    super.visitClass(cNode);

    classesToNewify = oldClassesToNewify;
    auto = oldAuto;
    classNamePattern = oldCnPattern;
}
 
Example 6
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ConstructedOuterNestedClassNode tryToConstructOuterNestedClassNode(final ClassNode type, final ClassNode outerClassNode, final BiConsumer<ConstructedOuterNestedClassNode, ClassNode> setRedirectListener) {
    String outerClassName = outerClassNode.getName();

    for (String typeName = type.getName(), ident = typeName; ident.indexOf('.') != -1; ) {
        ident = ident.substring(0, ident.lastIndexOf('.'));
        if (outerClassName.endsWith(ident)) {
            String outerNestedClassName = outerClassName + typeName.substring(ident.length()).replace('.', '$');
            ConstructedOuterNestedClassNode constructedOuterNestedClassNode = new ConstructedOuterNestedClassNode(outerClassNode, outerNestedClassName);
            constructedOuterNestedClassNode.addSetRedirectListener(setRedirectListener);
            return constructedOuterNestedClassNode;
        }
    }

    return null;
}
 
Example 7
Source File: LogASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public String getCategoryName(ClassNode classNode, String categoryName) {
    if (categoryName.equals(DEFAULT_CATEGORY_NAME)) {
        return classNode.getName();
    }
    return categoryName;
}
 
Example 8
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ConstructedOuterNestedClassNode tryToConstructOuterNestedClassNodeForBaseType(final CompileUnit compileUnit, final String typeName, final ClassNode cn, final BiConsumer<ConstructedOuterNestedClassNode, ClassNode> setRedirectListener) {
    if (!compileUnit.getClassesToCompile().containsValue(cn)) return null;

    String outerNestedClassName = cn.getName() + "$" + typeName;
    ConstructedOuterNestedClassNode constructedOuterNestedClassNode = new ConstructedOuterNestedClassNode(cn, outerNestedClassName);
    constructedOuterNestedClassNode.addSetRedirectListener(setRedirectListener);
    return constructedOuterNestedClassNode;
}
 
Example 9
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static FieldNode checkFieldDoesNotExist(ClassNode node, String fieldName) {
    FieldNode ret = node.getDeclaredField(fieldName);
    if (ret != null) {
        if (isPublic(ret.getModifiers()) &&
                ret.getType().redirect() == ClassHelper.boolean_TYPE) {
            return ret;
        }
        throw new RuntimeParserException("The class " + node.getName() +
                " cannot declare field '" + fieldName + "' as this" +
                " field is needed for internal groovy purposes", ret);
    }
    return null;
}
 
Example 10
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 11
Source File: JRGroovyCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.codehaus.groovy.control.CompilationUnit.ClassgenCallback#call(
 *      groovyjarjarasm.asm.ClassVisitor, 
 *      org.codehaus.groovy.ast.ClassNode)
 */
@Override
public void call(ClassVisitor writer, ClassNode node) throws CompilationFailedException 
{
	classCount++;
	String name = node.getName();
	if (!classes.containsKey(name))
	{
		byte[] bytes = ((ClassWriter) writer).toByteArray();
		classes.put(name, bytes);
	}
}
 
Example 12
Source File: DependencyTracker.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addToCache(ClassNode node){
    if (node == null) return;
    String name = node.getName();
    if (!precompiledDependencies.containsKey(name)  &&
        !node.isPrimaryClassNode())
    {
        return;
    }
    current.add(node.getName());
    addToCache(node.getSuperClass());
    addToCache(node.getInterfaces());
}
 
Example 13
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private String genClosureClassName() {
    ClassNode classNode = controller.getClassNode();
    ClassNode outerClass = controller.getOutermostClass();
    MethodNode methodNode = controller.getMethodNode();

    return classNode.getName() + "$"
            + controller.getContext().getNextClosureInnerName(outerClass, classNode, methodNode);
}
 
Example 14
Source File: StaticTypesLambdaWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private String nextLambdaClassName() {
    ClassNode enclosingClass = controller.getClassNode();
    ClassNode outermostClass = controller.getOutermostClass();
    return enclosingClass.getName() + "$" + controller.getContext().getNextLambdaInnerName(outermostClass, enclosingClass, controller.getMethodNode());
}
 
Example 15
Source File: Traits.java    From groovy with Apache License 2.0 4 votes vote down vote up
static String helperClassName(final ClassNode traitNode) {
    return traitNode.getName() + TRAIT_HELPER;
}
 
Example 16
Source File: MissingClassException.java    From groovy with Apache License 2.0 4 votes vote down vote up
public MissingClassException(ClassNode type, String message){
    super("No such class: " + type.getName() + " " + message);
    this.type = type.getName();
}
 
Example 17
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private boolean tryPropertyOfSuperClass(final PropertyExpression pexp, final String propertyName) {
    ClassNode classNode = controller.getClassNode();

    if (!controller.getCompileStack().isLHS()) {
        String methodName = "get" + capitalize(propertyName); // TODO: "is"
        callX(pexp.getObjectExpression(), methodName).visit(this);
        return true;
    }

    FieldNode fieldNode = classNode.getSuperClass().getField(propertyName);

    if (fieldNode == null) {
        throw new RuntimeParserException("Failed to find field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }
    if (fieldNode.isFinal()) {
        throw new RuntimeParserException("Cannot modify final field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }

    MethodNode setter = classNode.getSuperClass().getSetterMethod(getSetterName(propertyName));
    MethodNode getter = classNode.getSuperClass().getGetterMethod("get" + capitalize(propertyName));

    if (fieldNode.isPrivate() && (setter == null || getter == null || !setter.getDeclaringClass().equals(getter.getDeclaringClass()))) {
        throw new RuntimeParserException("Cannot access private field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }

    OperandStack operandStack = controller.getOperandStack();
    operandStack.doAsType(fieldNode.getType());

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    operandStack.push(classNode);

    operandStack.swap();

    String owner = BytecodeHelper.getClassInternalName(classNode.getSuperClass().getName());
    String desc = BytecodeHelper.getTypeDescription(fieldNode.getType());
    if (fieldNode.isPublic() || fieldNode.isProtected()) {
        mv.visitFieldInsn(PUTFIELD, owner, propertyName, desc);
    } else {
        mv.visitMethodInsn(INVOKESPECIAL, owner, setter.getName(), BytecodeHelper.getMethodDescriptor(setter), false);
    }
    return true;
}
 
Example 18
Source File: Traits.java    From groovy with Apache License 2.0 4 votes vote down vote up
static String fieldHelperClassName(final ClassNode traitNode) {
    return traitNode.getName() + FIELD_HELPER;
}
 
Example 19
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static String getDescription(final ClassNode node) {
    return (node.isInterface() ? "interface" : "class") + " '" + node.getName() + "'";
}
 
Example 20
Source File: ToStringASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static Expression calculateToStringStatements(ClassNode cNode, boolean includeSuper, boolean includeFields, boolean includeSuperFields, List<String> excludes, final List<String> includes, boolean includeNames, boolean ignoreNulls, boolean includePackage, boolean includeSuperProperties, boolean allProperties, BlockStatement body, boolean allNames) {
    // def _result = new StringBuilder()
    final Expression result = localVarX("_result");
    body.addStatement(declS(result, ctorX(STRINGBUILDER_TYPE)));
    List<ToStringElement> elements = new ArrayList<ToStringElement>();

    // def $toStringFirst = true
    final VariableExpression first = localVarX("$toStringFirst");
    body.addStatement(declS(first, constX(Boolean.TRUE)));

    // <class_name>(
    String className = (includePackage) ? cNode.getName() : cNode.getNameWithoutPackage();
    body.addStatement(appendS(result, constX(className + "(")));

    Set<String> names = new HashSet<String>();
    List<PropertyNode> superList;
    if (includeSuperProperties || includeSuperFields) {
        superList = getAllProperties(names, cNode, cNode.getSuperClass(), includeSuperProperties, includeSuperFields, allProperties, false, true, true, true, allNames, false);
    } else {
        superList = new ArrayList<PropertyNode>();
    }
    List<PropertyNode> list = getAllProperties(names, cNode, cNode,true, includeFields, allProperties, false, false, true, false, allNames, false);
    list.addAll(superList);

    for (PropertyNode pNode : list) {
        String name = pNode.getName();
        if (shouldSkipUndefinedAware(name, excludes, includes, allNames)) continue;
        FieldNode fNode = pNode.getField();
        if (!cNode.hasProperty(name) && fNode.getDeclaringClass() != null) {
            // it's really just a field
            elements.add(new ToStringElement(varX(fNode), name, canBeSelf(cNode, fNode.getType())));
        } else {
            Expression getter = getterThisX(cNode, pNode);
            elements.add(new ToStringElement(getter, name, canBeSelf(cNode, pNode.getType())));
        }
    }

    // append super if needed
    if (includeSuper) {
        // not through MOP to avoid infinite recursion
        elements.add(new ToStringElement(callSuperX("toString"), "super", false));
    }

    if (includes != null) {
        Comparator<ToStringElement> includeComparator = Comparator.comparingInt(tse -> includes.indexOf(tse.name));
        elements.sort(includeComparator);
    }

    for (ToStringElement el : elements) {
        appendValue(body, result, first, el.value, el.name, includeNames, ignoreNulls, el.canBeSelf);
    }

    // wrap up
    body.addStatement(appendS(result, constX(")")));
    MethodCallExpression toString = callX(result, "toString");
    toString.setImplicitThis(false);
    return toString;
}