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 Project: groovy   Author: apache   File: OperandStack.java    License: 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 #2
Source Project: groovy   Author: apache   File: OperandStack.java    License: 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 #3
Source Project: tinkerpop   Author: apache   File: GremlinGroovyScriptEngine.java    License: 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 #4
Source Project: groovy   Author: apache   File: ImmutableASTTransformation.java    License: 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 #5
Source Project: groovy   Author: apache   File: PropertyTest.java    License: 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 #6
Source Project: groovy   Author: apache   File: CategoryASTTransformation.java    License: 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 #7
Source Project: groovy   Author: apache   File: StaticTypesUnaryExpressionHelper.java    License: 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 #8
Source Project: netbeans   Author: apache   File: GroovyVirtualSourceProvider.java    License: 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 #9
Source Project: groovy   Author: apache   File: ImmutablePropertyHandler.java    License: 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 #10
Source Project: groovy   Author: apache   File: StaticTypesLambdaWriter.java    License: 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 #11
Source Project: groovy   Author: apache   File: BuilderASTTransformation.java    License: 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 #12
Source Project: groovy   Author: apache   File: ClassCompletionVerifier.java    License: 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);
}
 
Example #13
Source Project: groovy   Author: apache   File: NewifyASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public void addAdditionalType(final ClassNode additionalType) {
    if (types == null) {
        types = new LinkedList<>();
        types.add(type);
    }
    types.add(additionalType);
}
 
Example #14
Source Project: groovy   Author: apache   File: TupleConstructorASTTransformation.java    License: Apache License 2.0 5 votes vote down vote up
private static Expression providedOrDefaultInitialValue(FieldNode fNode) {
    Expression initialExp = fNode.getInitialExpression() != null ? fNode.getInitialExpression() : nullX();
    final ClassNode paramType = fNode.getType();
    if (ClassHelper.isPrimitiveType(paramType) && isNull(initialExp)) {
        initialExp = primitivesInitialValues.get(paramType.getTypeClass());
    }
    return initialExp;
}
 
Example #15
Source Project: groovy   Author: apache   File: AsmReferenceResolver.java    License: Apache License 2.0 5 votes vote down vote up
private ClassNode resolveNonArrayType(Type type) {
    String className = type.getClassName();
    if (type.getSort() != Type.OBJECT) {
        return ClassHelper.make(className);
    }

    return resolveClass(className);
}
 
Example #16
Source Project: groovy   Author: apache   File: GenericsUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static List<ClassNode> getAllUnresolvedSuperClasses(ClassNode actualReceiver) {
    List<ClassNode> superClassNodeList = new LinkedList<>();

    for (ClassNode cn = actualReceiver.getUnresolvedSuperClass(); null != cn && ClassHelper.OBJECT_TYPE != cn; cn = cn.getUnresolvedSuperClass()) {
        superClassNodeList.add(cn);
    }

    return superClassNodeList;
}
 
Example #17
Source Project: groovy   Author: apache   File: UnionTypeClassNode.java    License: Apache License 2.0 5 votes vote down vote up
private static String asArrayDescriptor(ClassNode... nodes) {
    StringBuilder sb = new StringBuilder();
    for (ClassNode node : nodes) {
        if (sb.length() > 0) sb.append("+");
        sb.append(node.getText());
    }
    return sb.toString();
}
 
Example #18
Source Project: groovy-language-server   Author: prominic   File: ASTNodeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public List<ClassNode> getClassNodes() {
	List<ClassNode> result = new ArrayList<>();
	for (List<ClassNode> nodes : classNodesByURI.values()) {
		result.addAll(nodes);
	}
	return result;
}
 
Example #19
Source Project: groovy   Author: apache   File: StaticTypeCheckingSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Given a receiver and a method node, parameterize the method arguments using
 * available generic type information.
 *
 * @param receiver the class
 * @param m        the method
 * @return the parameterized arguments
 */
public static Parameter[] parameterizeArguments(final ClassNode receiver, final MethodNode m) {
    Map<GenericsTypeName, GenericsType> genericFromReceiver = GenericsUtils.extractPlaceholders(receiver);
    Map<GenericsTypeName, GenericsType> contextPlaceholders = extractGenericsParameterMapOfThis(m);
    Parameter[] methodParameters = m.getParameters();
    Parameter[] params = new Parameter[methodParameters.length];
    for (int i = 0, n = methodParameters.length; i < n; i += 1) {
        Parameter methodParameter = methodParameters[i];
        ClassNode paramType = methodParameter.getType();
        params[i] = buildParameter(genericFromReceiver, contextPlaceholders, methodParameter, paramType);
    }
    return params;
}
 
Example #20
Source Project: groovy   Author: apache   File: StaticInvocationWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void visitArgument(final Expression argumentExpr, final ClassNode parameterType) {
    argumentExpr.putNodeMetaData(StaticTypesMarker.PARAMETER_TYPE, parameterType);
    argumentExpr.visit(controller.getAcg());
    if (!isNullConstant(argumentExpr)) {
        controller.getOperandStack().doGroovyCast(parameterType);
    }
}
 
Example #21
Source Project: groovy   Author: apache   File: GenericsUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void extractSuperClassGenerics(GenericsType[] usage, GenericsType[] declaration, Map<String, ClassNode> spec) {
    // if declaration does not provide generics, there is no connection to make
    if (usage == null || declaration == null || declaration.length == 0) return;
    if (usage.length != declaration.length) return;

    // both have generics
    for (int i = 0; i < usage.length; i++) {
        GenericsType ui = usage[i];
        GenericsType di = declaration[i];
        if (di.isPlaceholder()) {
            spec.put(di.getName(), ui.getType());
        } else if (di.isWildcard()) {
            if (ui.isWildcard()) {
                extractSuperClassGenerics(ui.getLowerBound(), di.getLowerBound(), spec);
                extractSuperClassGenerics(ui.getUpperBounds(), di.getUpperBounds(), spec);
            } else {
                ClassNode cu = ui.getType();
                extractSuperClassGenerics(cu, di.getLowerBound(), spec);
                ClassNode[] upperBounds = di.getUpperBounds();
                if (upperBounds != null) {
                    for (ClassNode cn : upperBounds) {
                        extractSuperClassGenerics(cu, cn, spec);
                    }
                }
            }
        } else {
            extractSuperClassGenerics(ui.getType(), di.getType(), spec);
        }
    }
}
 
Example #22
Source Project: groovy-language-server   Author: prominic   File: GroovyASTUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<FieldNode> getFieldsForLeftSideOfPropertyExpression(Expression node, ASTNodeVisitor astVisitor) {
    ClassNode classNode = getTypeOfNode(node, astVisitor);
    if (classNode != null) {
        boolean statics = node instanceof ClassExpression;
        return classNode.getFields().stream().filter(fieldNode -> {
            return statics ? fieldNode.isStatic() : !fieldNode.isStatic();
        }).collect(Collectors.toList());
    }
    return Collections.emptyList();
}
 
Example #23
Source Project: netbeans   Author: apache   File: FindTypeUsagesVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitClass(ClassNode clazz) {
    if (isEquals(clazz.getSuperClass())) {
        // Oh my goodness I have absolutely no idea why the hack getSuperClass() doesn't return valid initiated superclass
        // and the method with a weird name getUnresolvedSuperClass(false) is actually returning resolved super class (with
        // line/column numbers set)
        usages.add(new ASTUtils.FakeASTNode(clazz.getUnresolvedSuperClass(false), clazz.getSuperClass().getNameWithoutPackage()));
    }
    for (ClassNode interfaceNode : clazz.getInterfaces()) {
        addIfEquals(interfaceNode);
    }
    super.visitClass(clazz);
}
 
Example #24
Source Project: groovy   Author: apache   File: OptimizingStatementWriter.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodNode selectConstructor(final ClassNode node, final Parameter[] parameters) {
    List<ConstructorNode> ctors = node.getDeclaredConstructors();
    MethodNode result = null;
    for (ConstructorNode ctor : ctors) {
        if (parametersEqual(ctor.getParameters(), parameters)) {
            result = ctor;
            break;
        }
    }
    return (result != null && result.isPublic() ? result : null);
}
 
Example #25
Source Project: groovy   Author: apache   File: ImmutablePropertyHandler.java    License: 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 createConstructorStatement(xform, cNode, pNode, namedArgsMap);
}
 
Example #26
Source Project: groovy   Author: apache   File: GeneralUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<PropertyNode> getInstanceProperties(final ClassNode cNode) {
    List<PropertyNode> result = new ArrayList<>();
    for (PropertyNode pNode : cNode.getProperties()) {
        if (!pNode.isStatic()) {
            result.add(pNode);
        }
    }
    return result;
}
 
Example #27
Source Project: groovy   Author: apache   File: GeneralUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<FieldNode> getInstancePropertyFields(final ClassNode cNode) {
    List<FieldNode> result = new ArrayList<>();
    for (PropertyNode pNode : cNode.getProperties()) {
        if (!pNode.isStatic()) {
            result.add(pNode.getField());
        }
    }
    return result;
}
 
Example #28
Source Project: groovy   Author: apache   File: FromString.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<ClassNode[]> getClosureSignatures(final MethodNode node, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final String[] options, final ASTNode usage) {
    List<ClassNode[]> list = new ArrayList<ClassNode[]>(options.length);
    for (String option : options) {
        list.add(parseOption(option, sourceUnit, compilationUnit, node, usage));
    }
    return list;
}
 
Example #29
Source Project: netbeans   Author: apache   File: TypeFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Goes through the whole project file base and return a set of {@link ClassNode}s
 * that has the same name as the given argument.
 *
 * NOTE: Please be aware that this method is currently highly ineffective since it
 * doesn't use index into account and parse the whole source base. It should be improve
 * once we will create a general API for both AST and Indexed elements.
 *
 * @param fileInProject one file from the project
 * @param className class name we are looking for
 * @return set of {@link ClassNode}s with the same name as the given argument
 */
public static Set<ClassNode> findTypes(FileObject fileInProject, String className) {
    final Set<ClassNode> types = new HashSet<ClassNode>();
    for (FileObject fo : GroovyProjectUtil.getGroovyFilesInProject(fileInProject)) {
        try {
            FindPossibleTypesTask task = new FindPossibleTypesTask(className);
            ParserManager.parse(Collections.singleton(Source.create(fo)), task);
            types.addAll(task.getResult());

        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return types;
}
 
Example #30
Source Project: groovy   Author: apache   File: MopWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MOP method name from a method.
 *
 * @param method  the method to be called by the mop method
 * @param useThis if true, then it is a call on "this", "super" else
 * @return the mop method name
 */
public static String getMopMethodName(MethodNode method, boolean useThis) {
    ClassNode declaringNode = method.getDeclaringClass();
    int distance = 0;
    for (; declaringNode != null; declaringNode = declaringNode.getSuperClass()) {
        distance += 1;
    }
    return (useThis ? "this" : "super") + "$" + distance + "$" + method.getName();
}