Java Code Examples for org.codehaus.groovy.ast.Parameter#EMPTY_ARRAY

The following examples show how to use org.codehaus.groovy.ast.Parameter#EMPTY_ARRAY . 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: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
    ClassNode type = node.getDeclaringClass();
    ClassNode superType = type.getSuperClass();

    boolean hadPrivateConstructor = false;
    for (ConstructorNode c : superType.getDeclaredConstructors()) {
        // Only look at things we can actually call
        if (c.isPublic() || c.isProtected()) {
            return c.getParameters();
        }
    }

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

    return null;
}
 
Example 2
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that arguments and parameter types match.
 *
 * @return -1 if arguments do not match, 0 if arguments are of the exact type and > 0 when one or more argument is
 * not of the exact type but still match
 */
public static int allParametersAndArgumentsMatch(Parameter[] parameters, final ClassNode[] argumentTypes) {
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    }
    int dist = 0;
    if (argumentTypes.length < parameters.length) {
        return -1;
    }
    // we already know there are at least params.length elements in both arrays
    for (int i = 0, n = parameters.length; i < n; i += 1) {
        ClassNode paramType = parameters[i].getType();
        ClassNode argType = argumentTypes[i];
        if (!isAssignableTo(argType, paramType)) {
            return -1;
        } else if (!paramType.equals(argType)) {
            dist += getDistance(argType, paramType);
        }
    }
    return dist;
}
 
Example 3
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
public MethodNode newMethod(final String name,
                            final Callable<ClassNode> returnType) {
    MethodNode node = new MethodNode(name,
            Opcodes.ACC_PUBLIC,
            ClassHelper.OBJECT_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            EmptyStatement.INSTANCE) {
        @Override
        public ClassNode getReturnType() {
            try {
                return returnType.call();
            } catch (Exception e) {
                return super.getReturnType();
            }
        }
    };
    generatedMethods.add(node);
    return node;
}
 
Example 4
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Used to instruct the type checker that the call is a dynamic method call.
 * Calling this method automatically sets the handled flag to true.
 * @param call the method call which is a dynamic method call
 * @param returnType the expected return type of the dynamic call
 * @return a virtual method node with the same name as the expected call
 */
public MethodNode makeDynamic(MethodCall call, ClassNode returnType) {
    TypeCheckingContext.EnclosingClosure enclosingClosure = context.getEnclosingClosure();
    MethodNode enclosingMethod = context.getEnclosingMethod();
    ((ASTNode)call).putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
    if (enclosingClosure!=null) {
        enclosingClosure.getClosureExpression().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
    } else {
        enclosingMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
    }
    setHandled(true);
    if (debug) {
        LOG.info("Turning "+call.getText()+" into a dynamic method call returning "+returnType.toString(false));
    }
    return new MethodNode(call.getMethodAsString(), 0, returnType, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE);
}
 
Example 5
Source File: GenericsUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static ClassNode resolveClassNode(final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage, final ClassNode parsedNode) {
    ClassNode dummyClass = new ClassNode("dummy", 0, ClassHelper.OBJECT_TYPE);
    dummyClass.setModule(new ModuleNode(sourceUnit));
    dummyClass.setGenericsTypes(mn.getDeclaringClass().getGenericsTypes());
    MethodNode dummyMN = new MethodNode(
            "dummy",
            0,
            parsedNode,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            EmptyStatement.INSTANCE
    );
    dummyMN.setGenericsTypes(mn.getGenericsTypes());
    dummyClass.addMethod(dummyMN);
    ResolveVisitor visitor = new ResolveVisitor(compilationUnit) {
        @Override
        public void addError(final String msg, final ASTNode expr) {
            sourceUnit.addError(new IncorrectTypeHintException(mn, msg, usage.getLineNumber(), usage.getColumnNumber()));
        }
    };
    visitor.startResolving(dummyClass, sourceUnit);
    return dummyMN.getReturnType();
}
 
Example 6
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Parameter[] createParametersWithExactType(MethodNode abstractMethodNode, ClassNode[] inferredParameterTypes) {
    Parameter[] originalParameters = abstractMethodNode.getParameters();

    // We MUST clone the parameters to avoid impacting the original parameter type of SAM
    Parameter[] parameters = GeneralUtils.cloneParams(originalParameters);
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    }

    for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        ClassNode parameterType = parameter.getType();
        ClassNode inferredType = inferredParameterTypes[i];

        if (null == inferredType) {
            continue;
        }

        ClassNode type = convertParameterType(parameterType, inferredType);

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

    return parameters;
}
 
Example 7
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 8
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 5 votes vote down vote up
public MethodNode newMethod(final String name, final ClassNode returnType) {
    MethodNode node = new MethodNode(name,
            Opcodes.ACC_PUBLIC,
            returnType,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            EmptyStatement.INSTANCE);
    generatedMethods.add(node);
    return node;
}
 
Example 9
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitGetter(PropertyNode node, Statement getterBlock, int getterModifiers, String getterName) {
    MethodNode getter =
            new MethodNode(getterName, getterModifiers, node.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock);
    getter.setSynthetic(true);
    addPropertyMethod(getter);
    visitMethod(getter);
}
 
Example 10
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 11
Source File: Java8.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Parameter[] processParameters(CompileUnit compileUnit, Method m) {
    java.lang.reflect.Parameter[] parameters = m.getParameters();
    Type[] types = m.getGenericParameterTypes();
    Parameter[] params = Parameter.EMPTY_ARRAY;
    if (types.length > 0) {
        params = new Parameter[types.length];
        for (int i = 0; i < params.length; i++) {
            java.lang.reflect.Parameter p = parameters[i];
            String name = p.isNamePresent() ? p.getName() : "param" + i;
            params[i] = makeParameter(compileUnit, types[i], m.getParameterTypes()[i], m.getParameterAnnotations()[i], name);
        }
    }
    return params;
}
 
Example 12
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression transformMethodCall(final MethodCallExpression exp) {
    String name = exp.getMethodAsString();
    if (exp.isImplicitThis() && "include".equals(name)) {
        return tryTransformInclude(exp);
    } else if (exp.isImplicitThis() && name.startsWith(":")) {
        List<Expression> args;
        if (exp.getArguments() instanceof ArgumentListExpression) {
            args = ((ArgumentListExpression) exp.getArguments()).getExpressions();
        } else {
            args = Collections.singletonList(exp.getArguments());
        }
        Expression newArguments = transform(new ArgumentListExpression(new ConstantExpression(name.substring(1)), new ArrayExpression(ClassHelper.OBJECT_TYPE, args)));
        MethodCallExpression call = new MethodCallExpression(
                new VariableExpression("this"),
                "methodMissing",
                newArguments
        );
        call.setImplicitThis(true);
        call.setSafe(exp.isSafe());
        call.setSpreadSafe(exp.isSpreadSafe());
        call.setSourcePosition(exp);
        return call;
    } else if (name!=null && name.startsWith("$")) {
        MethodCallExpression reformatted = new MethodCallExpression(
                exp.getObjectExpression(),
                name.substring(1),
                exp.getArguments()
        );
        reformatted.setImplicitThis(exp.isImplicitThis());
        reformatted.setSafe(exp.isSafe());
        reformatted.setSpreadSafe(exp.isSpreadSafe());
        reformatted.setSourcePosition(exp);
        // wrap in a stringOf { ... } closure call
        ClosureExpression clos = new ClosureExpression(Parameter.EMPTY_ARRAY, new ExpressionStatement(reformatted));
        clos.setVariableScope(new VariableScope());
        MethodCallExpression stringOf = new MethodCallExpression(new VariableExpression("this"),
                "stringOf",
                clos);
        stringOf.setImplicitThis(true);
        stringOf.setSourcePosition(reformatted);
        return stringOf;
    }
    return super.transform(exp);
}
 
Example 13
Source File: MapConstructorASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createNoArgConstructor(ClassNode cNode, int modifiers) {
    Statement body = stmt(ctorX(ClassNode.THIS, args(new MapExpression())));
    ConstructorNode consNode = new ConstructorNode(modifiers, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body);
    markAsGenerated(cNode, consNode);
    cNode.addConstructor(consNode);
}
 
Example 14
Source File: ClosureUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * @return the parameters for the ClosureExpression
 */
public static Parameter[] getParametersSafe(ClosureExpression ce) {
    return ce.getParameters() != null ? ce.getParameters() : Parameter.EMPTY_ARRAY;
}
 
Example 15
Source File: ClosureWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected ClassNode createClosureClass(final ClosureExpression expression, final int modifiers) {
    ClassNode classNode = controller.getClassNode();
    ClassNode outerClass = controller.getOutermostClass();
    String name = genClosureClassName();
    boolean staticMethodOrInStaticClass = controller.isStaticMethod() || classNode.isStaticClass();

    Parameter[] parameters = expression.getParameters();
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    } else if (parameters.length == 0) {
        // let's create a default 'it' parameter
        Parameter it = new Parameter(ClassHelper.OBJECT_TYPE, "it", ConstantExpression.NULL);
        parameters = new Parameter[]{it};
        Variable ref = expression.getVariableScope().getDeclaredVariable("it");
        if (ref!=null) it.setClosureSharedVariable(ref.isClosureSharedVariable());
    }

    Parameter[] localVariableParams = getClosureSharedVariables(expression);
    removeInitialValues(localVariableParams);

    InnerClassNode answer = new InnerClassNode(classNode, name, modifiers, ClassHelper.CLOSURE_TYPE.getPlainNodeReference());
    answer.setEnclosingMethod(controller.getMethodNode());
    answer.setSynthetic(true);
    answer.setUsingGenerics(outerClass.isUsingGenerics());
    answer.setSourcePosition(expression);

    if (staticMethodOrInStaticClass) {
        answer.setStaticClass(true);
    }
    if (controller.isInScriptBody()) {
        answer.setScriptBody(true);
    }
    MethodNode method =
            answer.addMethod("doCall", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, expression.getCode());
    method.setSourcePosition(expression);

    VariableScope varScope = expression.getVariableScope();
    if (varScope == null) {
        throw new RuntimeException(
                "Must have a VariableScope by now! for expression: " + expression + " class: " + name);
    } else {
        method.setVariableScope(varScope.copy());
    }
    if (parameters.length > 1
            || (parameters.length == 1
            && parameters[0].getType() != null
            && parameters[0].getType() != ClassHelper.OBJECT_TYPE
            && !ClassHelper.OBJECT_TYPE.equals(parameters[0].getType().getComponentType())))
    {

        // let's add a typesafe call method
        MethodNode call = answer.addMethod(
                "call",
                ACC_PUBLIC,
                ClassHelper.OBJECT_TYPE,
                parameters,
                ClassNode.EMPTY_ARRAY,
                new ReturnStatement(
                        new MethodCallExpression(
                                VariableExpression.THIS_EXPRESSION,
                                "doCall",
                                new ArgumentListExpression(parameters))));
        call.setSourcePosition(expression);
    }

    // let's make the constructor
    BlockStatement block = createBlockStatementForConstructor(expression, outerClass, classNode);

    // let's assign all the parameter fields from the outer context
    addFieldsAndGettersForLocalVariables(answer, localVariableParams);

    addConstructor(expression, localVariableParams, answer, block);

    correctAccessedVariable(answer,expression);

    return answer;
}