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

The following examples show how to use org.codehaus.groovy.ast.Parameter#getType() . 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: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void visitParameters(Parameter[] parameters, Variable variable) {
    // method is declaring given variable, let's visit only the method,
    // but we need to check also parameters as those are not part of method visit
    for (Parameter parameter : parameters) {
        ClassNode paramType = parameter.getType();
        if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
            addOccurrences(paramType, (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
        } else {
            if (parameter.getName().equals(variable.getName())) {
                occurrences.add(parameter);
                break;
            }
        }
    }
    super.visitParameters(parameters, variable);
}
 
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: 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 4
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitParameters(Parameter[] parameters, Variable variable) {
    if (!leafReached) {
        for (Parameter param : parameters) {
            if (sameVariableName(param, variable)) {
                guessedType = param.getType();
                break;
            }
        }
    }
}
 
Example 5
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression expression) {
        if (expression.isSuperExpression()) {
            guessedType = expression.getType().getSuperClass();
        }
        if (null != expression.getAccessedVariable()) {
            Variable accessedVariable = expression.getAccessedVariable();

            if (accessedVariable.hasInitialExpression()) {
                Expression initialExpression = expression.getAccessedVariable().getInitialExpression();
                if (initialExpression instanceof ConstantExpression
                        && !initialExpression.getText().equals("null")) { // NOI18N
                    guessedType = ((ConstantExpression) initialExpression).getType();
                } else if (initialExpression instanceof ConstructorCallExpression) {
                    guessedType = ClassHelper.make(((ConstructorCallExpression) initialExpression).getType().getName());
                } else if (initialExpression instanceof MethodCallExpression) {
                    int newOffset = ASTUtils.getOffset(doc, initialExpression.getLineNumber(), initialExpression.getColumnNumber());
                    AstPath newPath = new AstPath(path.root(), newOffset, doc);
                    guessedType = MethodInference.findCallerType(initialExpression, newPath, doc, newOffset);
                } else if (initialExpression instanceof ListExpression) {
                    guessedType = ((ListExpression) initialExpression).getType();
                } else if (initialExpression instanceof MapExpression) {
                    guessedType = ((MapExpression) initialExpression).getType();
                } else if (initialExpression instanceof RangeExpression) {
                    // this should work, but the type is Object - nut sure why
                    // guessedType = ((RangeExpression)initialExpression).getType();
                    guessedType = ClassHelper.makeWithoutCaching(Range.class, true);                
                }
            } else if (accessedVariable instanceof Parameter) {
                Parameter param = (Parameter) accessedVariable;
                guessedType = param.getType();
            }
        } else if (!expression.getType().getName().equals("java.lang.Object")) {
            guessedType = expression.getType();

        }
    super.visitVariableExpression(expression);
}
 
Example 6
Source File: GenericsVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodNode node) {
    Parameter[] parameters = node.getParameters();
    for (Parameter param : parameters) {
        ClassNode paramType = param.getType();
        checkGenericsUsage(paramType, paramType.redirect());
    }
    ClassNode returnType = node.getReturnType();
    checkGenericsUsage(returnType, returnType.redirect());
    super.visitMethod(node);
}
 
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: StaticTypeCheckingSupport.java    From groovy with 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 9
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void adjustTypesIfStaticMainMethod(MethodNode node) {
    if (node.getName().equals("main") && node.isStatic()) {
        Parameter[] params = node.getParameters();
        if (params.length == 1) {
            Parameter param = params[0];
            if (param.getType() == null || param.getType() == ClassHelper.OBJECT_TYPE) {
                param.setType(ClassHelper.STRING_TYPE.makeArray());
                ClassNode returnType = node.getReturnType();
                if (returnType == ClassHelper.OBJECT_TYPE) {
                    node.setReturnType(ClassHelper.VOID_TYPE);
                }
            }
        }
    }
}
 
Example 10
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void addFieldsAndGettersForLocalVariables(final InnerClassNode answer, final Parameter[] localVariableParams) {
    for (Parameter param : localVariableParams) {
        String paramName = param.getName();
        ClassNode type = param.getType();
        VariableExpression initialValue = new VariableExpression(paramName);
        initialValue.setAccessedVariable(param);
        initialValue.setUseReferenceDirectly(true);
        ClassNode realType = type;
        type = ClassHelper.makeReference();
        param.setType(ClassHelper.makeReference());
        FieldNode paramField = answer.addField(paramName, ACC_PRIVATE | ACC_SYNTHETIC, type, initialValue);
        paramField.setOriginType(ClassHelper.getWrapper(param.getOriginType()));
        paramField.setHolder(true);
        String methodName = Verifier.capitalize(paramName);

        // let's add a getter & setter
        Expression fieldExp = new FieldExpression(paramField);
        markAsGenerated(answer,
            answer.addMethod(
                "get" + methodName,
                ACC_PUBLIC,
                realType.getPlainNodeReference(),
                Parameter.EMPTY_ARRAY,
                ClassNode.EMPTY_ARRAY,
                new ReturnStatement(fieldExp)),
            true);
    }
}
 
Example 11
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean hasGenerics(Parameter[] param) {
    if (param.length == 0) return false;
    for (Parameter parameter : param) {
        ClassNode type = parameter.getType();
        if (hasGenerics(type)) return true;
    }
    return false;
}
 
Example 12
Source File: MopWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a Meta Object Protocol method, that is used to call a non public
 * method, or to make a call to super.
 *
 * @param mopCalls list of methods a mop call method should be generated for
 * @param useThis  true if "this" should be used for the naming
 */
protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {
    for (MethodNode method : mopCalls) {
        String name = getMopMethodName(method, useThis);
        Parameter[] parameters = method.getParameters();
        String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());
        MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);
        controller.setMethodVisitor(mv);
        mv.visitVarInsn(ALOAD, 0);
        int newRegister = 1;
        OperandStack operandStack = controller.getOperandStack();
        for (Parameter parameter : parameters) {
            ClassNode type = parameter.getType();
            operandStack.load(parameter.getType(), newRegister);
            newRegister += 1; // increment to next register; double/long are using two places
            if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister += 1;
        }
        operandStack.remove(parameters.length);
        ClassNode declaringClass = method.getDeclaringClass();
        // JDK 8 support for default methods in interfaces
        // TODO: this should probably be strengthened when we support the A.super.foo() syntax
        int opcode = declaringClass.isInterface() ? INVOKEINTERFACE : INVOKESPECIAL;
        mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, declaringClass.isInterface());
        BytecodeHelper.doReturn(mv, method.getReturnType());
        mv.visitMaxs(0, 0);
        mv.visitEnd();
        controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);
    }
}
 
Example 13
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
    if (!(arg instanceof VariableExpression)) return arg.getType();
    VariableExpression vexp = (VariableExpression) arg;
    String name = vexp.getName();
    for (Parameter param : node.getParameters()) {
        if (param.getName().equals(name)) {
            return param.getType();
        }
    }
    return vexp.getType();
}
 
Example 14
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());
        }
    }
}
 
Example 15
Source File: CompileStack.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void defineMethodVariables(final Parameter[] params, final boolean isInStaticContext) {
    Label startLabel  = new Label();
    thisStartLabel = startLabel;
    controller.getMethodVisitor().visitLabel(startLabel);

    makeLocalVariablesOffset(params,isInStaticContext);

    for (Parameter param : params) {
        String name = param.getName();
        BytecodeVariable answer;
        ClassNode type = param.getType();
        if (param.isClosureSharedVariable()) {
            boolean useExistingReference = param.getNodeMetaData(ClosureWriter.UseExistingReference.class) != null;
            answer = defineVar(name, param.getOriginType(), true, useExistingReference);
            answer.setStartLabel(startLabel);
            if (!useExistingReference) {
                controller.getOperandStack().load(type, currentVariableIndex);
                controller.getOperandStack().box();

                // GROOVY-4237, the original variable should always appear
                // in the variable index, otherwise some programs get into
                // trouble. So we define a dummy variable for the packaging
                // phase and let it end right away before the normal
                // reference will be used
                Label newStart = new Label();
                controller.getMethodVisitor().visitLabel(newStart);
                BytecodeVariable var = new BytecodeVariable(currentVariableIndex, param.getOriginType(), name, currentVariableIndex);
                var.setStartLabel(startLabel);
                var.setEndLabel(newStart);
                usedVariables.add(var);
                answer.setStartLabel(newStart);

                createReference(answer);
            }
        } else {
            answer = defineVar(name, type, false, false);
            answer.setStartLabel(startLabel);
        }
        stackVariables.put(name, answer);
    }

    nextVariableIndex = localVariableOffset;
}