Java Code Examples for org.codehaus.groovy.ast.Parameter#hasInitialExpression()

The following examples show how to use org.codehaus.groovy.ast.Parameter#hasInitialExpression() . 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: StaticVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
    MethodNode oldMethodNode = methodNode;
    methodNode = node;
    super.visitConstructorOrMethod(node, isConstructor);
    if (isConstructor) {
        for (Parameter param : node.getParameters()) {
            if (param.hasInitialExpression()) {
                // initial expression will be argument to special constructor call
                boolean oldIsSpecialConstructorCall = inSpecialConstructorCall;
                inSpecialConstructorCall = true;
                param.getInitialExpression().visit(this);
                inSpecialConstructorCall = oldIsSpecialConstructorCall;
            }
        }
    }
    methodNode = oldMethodNode;
}
 
Example 2
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformClosureExpression(final ClosureExpression ce) {
    boolean oldInClosure = inClosure;
    inClosure = true;
    for (Parameter para : getParametersSafe(ce)) {
        ClassNode t = para.getType();
        resolveOrFail(t, ce);
        visitAnnotations(para);
        if (para.hasInitialExpression()) {
            para.setInitialExpression(transform(para.getInitialExpression()));
        }
        visitAnnotations(para);
    }

    Statement code = ce.getCode();
    if (code != null) code.visit(this);
    inClosure = oldInClosure;
    return ce;
}
 
Example 3
Source File: NamedVariantASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean processExplicitNamedParam(final MethodNode mNode, final Parameter mapParam, final BlockStatement inner, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) {
    AnnotationNode namedParam = fromParam.getAnnotations(NAMED_PARAM_TYPE).get(0);
    boolean required = memberHasValue(namedParam, "required", true);
    if (getMemberStringValue(namedParam, "value") == null) {
        namedParam.addMember("value", constX(fromParam.getName()));
    }
    String name = getMemberStringValue(namedParam, "value");
    if (getMemberValue(namedParam, "type") == null) {
        namedParam.addMember("type", classX(fromParam.getType()));
    }
    if (hasDuplicates(mNode, propNames, name)) return false;
    // TODO: Check specified type is assignable from declared param type?
    //ClassNode type = getMemberClassValue(namedParam, "type");
    if (required) {
        if (fromParam.hasInitialExpression()) {
            addError("Error during " + NAMED_VARIANT + " processing. A required parameter can't have an initial value.", mNode);
            return false;
        }
        inner.addStatement(new AssertStatement(boolX(callX(varX(mapParam), "containsKey", args(constX(name)))),
                plusX(constX("Missing required named argument '" + name + "'. Keys found: "), callX(varX(mapParam), "keySet"))));
    }
    args.addExpression(propX(varX(mapParam), name));
    mapParam.addAnnotation(namedParam);
    fromParam.getAnnotations().remove(namedParam);
    return true;
}
 
Example 4
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitClosureExpression(final ClosureExpression expression) {
    pushState();
    expression.setVariableScope(currentScope);
    inClosure = !isAnonymous(currentScope.getParent().getClassScope());

    if (expression.isParameterSpecified()) {
        for (Parameter parameter : expression.getParameters()) {
            parameter.setInStaticContext(currentScope.isInStaticContext());
            if (parameter.hasInitialExpression()) {
                parameter.getInitialExpression().visit(this);
            }
            declare(parameter, expression);
        }
    } else if (expression.getParameters() != null) {
        Parameter var = new Parameter(ClassHelper.OBJECT_TYPE, "it");
        var.setInStaticContext(currentScope.isInStaticContext());
        currentScope.putDeclaredVariable(var);
    }

    super.visitClosureExpression(expression);
    markClosureSharedVariables();

    popState();
}
 
Example 5
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Expression transformClosureExpression(ClosureExpression ce) {
    boolean oldInClosure = inClosure;
    inClosure = true;
    for (Parameter p : getParametersSafe(ce)) {
        if (p.hasInitialExpression()) {
            p.setInitialExpression(transform(p.getInitialExpression()));
        }
    }
    Statement code = ce.getCode();
    if (code != null) code.visit(this);
    inClosure = oldInClosure;
    return ce;
}
 
Example 6
Source File: InheritConstructorsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private List<Expression> buildParams(Parameter[] origParams, Parameter[] params, Map<String, ClassNode> genericsSpec, boolean copyParameterAnnotations) {
    List<Expression> theArgs = new ArrayList<>();
    for (int i = 0, n = origParams.length; i < n; i += 1) {
        Parameter p = origParams[i];
        ClassNode newType = correctToGenericsSpecRecurse(genericsSpec, p.getType());
        params[i] = p.hasInitialExpression() ? param(newType, p.getName(), p.getInitialExpression()) : param(newType, p.getName());
        if (copyParameterAnnotations) {
            params[i].addAnnotations(copyAnnotatedNodeAnnotations(origParams[i], ANNOTATION));
        }
        // cast argument to parameter type in case the value is null
        theArgs.add(castX(p.getType(), varX(p.getName(), newType)));
    }
    return theArgs;
}
 
Example 7
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that arguments and parameter types match, expecting that the number of parameters is strictly greater
 * than the number of arguments, allowing possible inclusion of default parameters.
 *
 * @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
 */
static int allParametersAndArgumentsMatchWithDefaultParams(final Parameter[] parameters, final ClassNode[] argumentTypes) {
    int dist = 0;
    ClassNode ptype = null;
    // we already know the lengths are equal
    for (int i = 0, j = 0, n = parameters.length; i < n; i += 1) {
        Parameter param = parameters[i];
        ClassNode paramType = param.getType();
        ClassNode arg = (j >= argumentTypes.length ? null : argumentTypes[j]);
        if (arg == null || !isAssignableTo(arg, paramType)) {
            if (!param.hasInitialExpression() && (ptype == null || !ptype.equals(paramType))) {
                return -1; // no default value
            }
            // a default value exists, we can skip this param
            ptype = null;
        } else {
            j += 1;
            if (!paramType.equals(arg)) {
                dist += getDistance(arg, paramType);
            }
            if (param.hasInitialExpression()) {
                ptype = arg;
            } else {
                ptype = null;
            }
        }
    }
    return dist;
}
 
Example 8
Source File: ClosureExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
Expression transformClosureExpression(final ClosureExpression expr) {
    for (Parameter parameter : getParametersSafe(expr)) {
        if (parameter.hasInitialExpression()) {
            parameter.setInitialExpression(transformer.transform(parameter.getInitialExpression()));
        }
    }
    Statement code = expr.getCode();
    transformer.visitClassCodeContainer(code);
    return transformer.superTransform(expr);
}
 
Example 9
Source File: NamedVariantASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean processImplicitNamedParam(final MethodNode mNode, final Parameter mapParam, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) {
    boolean required = fromParam.hasInitialExpression();
    String name = fromParam.getName();
    if (hasDuplicates(mNode, propNames, name)) return false;
    AnnotationNode namedParam = new AnnotationNode(NAMED_PARAM_TYPE);
    namedParam.addMember("value", constX(name));
    namedParam.addMember("type", classX(fromParam.getType()));
    namedParam.addMember("required", constX(required, true));
    mapParam.addAnnotation(namedParam);
    args.addExpression(propX(varX(mapParam), name));
    return true;
}
 
Example 10
Source File: InnerClassVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
    currentMethod = node;
    visitAnnotations(node);
    visitClassCodeContainer(node.getCode());
    // GROOVY-5681: initial expressions should be visited too!
    for (Parameter param : node.getParameters()) {
        if (param.hasInitialExpression()) {
            param.getInitialExpression().visit(this);
        }
        visitAnnotations(param);
    }
    currentMethod = null;
}
 
Example 11
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the given method has a possibly matching static method with the given name and arguments.
 * Handles default arguments and optionally spread expressions.
 *
 * @param cNode     the ClassNode of interest
 * @param name      the name of the method of interest
 * @param arguments the arguments to match against
 * @param trySpread whether to try to account for SpreadExpressions within the arguments
 * @return true if a matching method was found
 */
public static boolean hasPossibleStaticMethod(ClassNode cNode, String name, Expression arguments, boolean trySpread) {
    int count = 0;
    boolean foundSpread = false;

    if (arguments instanceof TupleExpression) {
        TupleExpression tuple = (TupleExpression) arguments;
        for (Expression arg : tuple.getExpressions()) {
            if (arg instanceof SpreadExpression) {
                foundSpread = true;
            } else {
                count++;
            }
        }
    } else if (arguments instanceof MapExpression) {
        count = 1;
    }

    for (MethodNode method : cNode.getMethods(name)) {
        if (method.isStatic()) {
            Parameter[] parameters = method.getParameters();
            // do fuzzy match for spread case: count will be number of non-spread args
            if (trySpread && foundSpread && parameters.length >= count) return true;

            if (parameters.length == count) return true;

            // handle varargs case
            if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) {
                if (count >= parameters.length - 1) return true;
                // fuzzy match any spread to a varargs
                if (trySpread && foundSpread) return true;
            }

            // handle parameters with default values
            int nonDefaultParameters = 0;
            for (Parameter parameter : parameters) {
                if (!parameter.hasInitialExpression()) {
                    nonDefaultParameters++;
                }
            }

            if (count < parameters.length && nonDefaultParameters <= count) {
                return true;
            }
            // TODO handle spread with nonDefaultParams?
        }
    }
    return false;
}
 
Example 12
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
protected void loadArguments(final List<Expression> argumentList, final Parameter[] para) {
    if (para.length == 0) return;
    ClassNode lastParaType = para[para.length - 1].getOriginType();
    AsmClassGenerator acg = controller.getAcg();
    TypeChooser typeChooser = controller.getTypeChooser();
    OperandStack operandStack = controller.getOperandStack();
    int argumentListSize = argumentList.size();
    ClassNode lastArgType = argumentListSize > 0 ?
            typeChooser.resolveType(argumentList.get(argumentListSize -1), controller.getClassNode()) : null;
    if (lastParaType.isArray()
            && ((argumentListSize > para.length)
            || ((argumentListSize == (para.length - 1)) && !lastParaType.equals(lastArgType))
            || ((argumentListSize == para.length && lastArgType!=null && !lastArgType.isArray())
                && (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(lastArgType,lastParaType.getComponentType())))
                    || ClassHelper.GSTRING_TYPE.equals(lastArgType) && ClassHelper.STRING_TYPE.equals(lastParaType.getComponentType()))
            ) {
        int stackLen = operandStack.getStackLength() + argumentListSize;
        MethodVisitor mv = controller.getMethodVisitor();
        controller.setMethodVisitor(mv);
        // varg call
        // first parameters as usual
        for (int i = 0; i < para.length - 1; i += 1) {
            visitArgument(argumentList.get(i), para[i].getType());
        }
        // last parameters wrapped in an array
        List<Expression> lastParams = new ArrayList<>();
        for (int i = para.length - 1; i < argumentListSize; i += 1) {
            lastParams.add(argumentList.get(i));
        }
        ArrayExpression array = new ArrayExpression(lastParaType.getComponentType(), lastParams);
        array.visit(acg);
        // adjust stack length
        while (operandStack.getStackLength() < stackLen) {
            operandStack.push(ClassHelper.OBJECT_TYPE);
        }
        if (argumentListSize == para.length - 1) {
            operandStack.remove(1);
        }
    } else if (argumentListSize == para.length) {
        for (int i = 0; i < argumentListSize; i++) {
            visitArgument(argumentList.get(i), para[i].getType());
        }
    } else {
        // method call with default arguments
        ClassNode classNode = controller.getClassNode();
        Expression[] arguments = new Expression[para.length];
        for (int i = 0, j = 0, n = para.length; i < n; i += 1) {
            Parameter curParam = para[i];
            ClassNode curParamType = curParam.getType();
            Expression curArg = j < argumentListSize ? argumentList.get(j) : null;
            Expression initialExpression = curParam.getNodeMetaData(StaticTypesMarker.INITIAL_EXPRESSION);
            if (initialExpression == null && curParam.hasInitialExpression())
                initialExpression = curParam.getInitialExpression();
            if (initialExpression == null && curParam.getNodeMetaData(Verifier.INITIAL_EXPRESSION) != null) {
                initialExpression = curParam.getNodeMetaData(Verifier.INITIAL_EXPRESSION);
            }
            ClassNode curArgType = curArg == null ? null : typeChooser.resolveType(curArg, classNode);

            if (initialExpression != null && !compatibleArgumentType(curArgType, curParamType)) {
                // use default expression
                arguments[i] = initialExpression;
            } else {
                arguments[i] = curArg;
                j += 1;
            }
        }
        for (int i = 0, n = arguments.length; i < n; i += 1) {
            visitArgument(arguments[i], para[i].getType());
        }
    }
}