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

The following examples show how to use org.codehaus.groovy.ast.Parameter#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: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitForLoop(ForStatement forLoop) {
    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        addOccurrences(forLoop.getVariableType(), (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
    } else {
        final Parameter forLoopVar = forLoop.getVariable();
        final String varName = forLoopVar.getName();
        
        if (leaf instanceof Variable) {
            if (varName.equals(((Variable) leaf).getName())) {
                occurrences.add(forLoopVar);
            }
        } else if (leaf instanceof ForStatement) {
            if (varName.equals(((ForStatement) leaf).getVariable().getName())) {
                occurrences.add(forLoopVar);
            }
        }
    }
    super.visitForLoop(forLoop);
}
 
Example 2
Source File: TraitComposer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a method to dispatch to "super traits" in a "stackable" fashion. The generated method looks like this:
 * <p>
 * <code>ReturnType trait$super$method(Class clazz, Arg1 arg1, Arg2 arg2, ...) {
 *     if (SomeTrait.is(A) { return SomeOtherTrait$Trait$Helper.method(this, arg1, arg2) }
 *     super.method(arg1,arg2)
 * }</code>
 * </p>
 * @param targetNode
 * @param forwarderMethod
 * @param interfacesToGenerateForwarderFor
 * @param genericsSpec
 */
private static void doCreateSuperForwarder(ClassNode targetNode, MethodNode forwarderMethod, ClassNode[] interfacesToGenerateForwarderFor, Map<String,ClassNode> genericsSpec) {
    Parameter[] parameters = forwarderMethod.getParameters();
    Parameter[] superForwarderParams = new Parameter[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        ClassNode originType = parameter.getOriginType();
        superForwarderParams[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, originType), parameter.getName());
    }
    for (int i = 0; i < interfacesToGenerateForwarderFor.length; i++) {
        final ClassNode current = interfacesToGenerateForwarderFor[i];
        final ClassNode next = i < interfacesToGenerateForwarderFor.length - 1 ? interfacesToGenerateForwarderFor[i + 1] : null;
        String forwarderName = Traits.getSuperTraitMethodName(current, forwarderMethod.getName());
        if (targetNode.getDeclaredMethod(forwarderName, superForwarderParams) == null) {
            ClassNode returnType = correctToGenericsSpecRecurse(genericsSpec, forwarderMethod.getReturnType());
            Statement delegate = next == null ? createSuperFallback(forwarderMethod, returnType) : createDelegatingForwarder(forwarderMethod, next);
            MethodNode methodNode = targetNode.addMethod(forwarderName, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, returnType, superForwarderParams, ClassNode.EMPTY_ARRAY, delegate);
            methodNode.setGenericsTypes(forwarderMethod.getGenericsTypes());
        }
    }
}
 
Example 3
Source File: ASTMethod.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<MethodParameter> getParameters() {
    if (parameters == null) {
        parameters = new ArrayList<>();
        for (Parameter parameter : ((MethodNode) node).getParameters()) {
            String paramName = parameter.getName();
            String fqnType = parameter.getType().getName();
            String type = parameter.getType().getNameWithoutPackage();

            parameters.add(new MethodParameter(fqnType, type, paramName));
        }
    }
    return parameters;
}
 
Example 4
Source File: GroovydocVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void setConstructorOrMethodCommon(MethodNode node, SimpleGroovyExecutableMemberDoc methOrCons) {
    methOrCons.setRawCommentText(getDocContent(node.getGroovydoc()));
    processModifiers(methOrCons, node, node.getModifiers());
    processAnnotations(methOrCons, node);
    if (node.isAbstract()) {
        methOrCons.setAbstract(true);
    }
    for (Parameter param : node.getParameters()) {
        SimpleGroovyParameter p = new SimpleGroovyParameter(param.getName());
        p.setType(new SimpleGroovyType(makeType(param.getType())));
        processAnnotations(p, param);
        methOrCons.add(p);
    }
}
 
Example 5
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Given a parameter, builds a new parameter for which the known generics placeholders are resolved.
 *
 * @param genericFromReceiver      resolved generics from the receiver of the message
 * @param placeholdersFromContext  resolved generics from the method context
 * @param methodParameter          the method parameter for which we want to resolve generic types
 * @param paramType                the (unresolved) type of the method parameter
 * @return a new parameter with the same name and type as the original one, but with resolved generic types
 */
private static Parameter buildParameter(final Map<GenericsTypeName, GenericsType> genericFromReceiver, final Map<GenericsTypeName, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) {
    if (genericFromReceiver.isEmpty() && (placeholdersFromContext == null || placeholdersFromContext.isEmpty())) {
        return methodParameter;
    }
    if (paramType.isArray()) {
        ClassNode componentType = paramType.getComponentType();
        Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName());
        Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType);
        return new Parameter(component.getType().makeArray(), component.getName());
    }
    ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType);

    return new Parameter(resolved, methodParameter.getName());
}
 
Example 6
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 7
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static MethodNode correctToGenericsSpec(Map<String, ClassNode> genericsSpec, MethodNode mn) {
    if (genericsSpec == null) return mn;
    if (mn.getGenericsTypes() != null) genericsSpec = addMethodGenerics(mn, genericsSpec);
    ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType());
    Parameter[] origParameters = mn.getParameters();
    Parameter[] newParameters = new Parameter[origParameters.length];
    for (int i = 0; i < origParameters.length; i++) {
        Parameter origParameter = origParameters[i];
        newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression());
    }
    return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode());
}
 
Example 8
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 9
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 10
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<FieldNode> convertParamsToFields(ClassNode builder, Parameter[] parameters) {
    List<FieldNode> fieldNodes = new ArrayList<FieldNode>();
    for (Parameter parameter: parameters) {
        Map<String,ClassNode> genericsSpec = createGenericsSpec(builder);
        ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, parameter.getType());
        FieldNode fieldNode = new FieldNode(parameter.getName(), parameter.getModifiers(), correctedType, builder, DEFAULT_INITIAL_VALUE);
        fieldNodes.add(fieldNode);
        builder.addField(fieldNode);
    }
    return fieldNodes;
}
 
Example 11
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static String getDescription(Parameter node) {
    return "parameter '" + node.getName() + "'";
}
 
Example 12
Source File: ClosureWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void writeClosure(final ClosureExpression expression) {
    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode classNode = controller.getClassNode();
    AsmClassGenerator acg = controller.getAcg();

    // generate closure as public class to make sure it can be properly invoked by classes of the
    // Groovy runtime without circumventing JVM access checks (see CachedMethod for example).
    int mods = ACC_PUBLIC | ACC_FINAL;
    if (classNode.isInterface()) {
        mods |= ACC_STATIC;
    }
    ClassNode closureClass = getOrAddClosureClass(expression, mods);
    String closureClassinternalName = BytecodeHelper.getClassInternalName(closureClass);
    List<ConstructorNode> constructors = closureClass.getDeclaredConstructors();
    ConstructorNode node = constructors.get(0);

    Parameter[] localVariableParams = node.getParameters();

    mv.visitTypeInsn(NEW, closureClassinternalName);
    mv.visitInsn(DUP);
    if (controller.isStaticMethod() || compileStack.isInSpecialConstructorCall()) {
        (new ClassExpression(classNode)).visit(acg);
        (new ClassExpression(controller.getOutermostClass())).visit(acg);
    } else {
        mv.visitVarInsn(ALOAD, 0);
        controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
        loadThis();
    }

    // now let's load the various parameters we're passing
    // we start at index 2 because the first variable we pass
    // is the owner instance and at this point it is already
    // on the stack
    for (int i = 2; i < localVariableParams.length; i++) {
        Parameter param = localVariableParams[i];
        String name = param.getName();
        loadReference(name, controller);
        if (param.getNodeMetaData(ClosureWriter.UseExistingReference.class)==null) {
            param.setNodeMetaData(ClosureWriter.UseExistingReference.class,Boolean.TRUE);
        }
    }

    // we may need to pass in some other constructors
    //cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
    mv.visitMethodInsn(INVOKESPECIAL, closureClassinternalName, "<init>", BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, localVariableParams), false);
    controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE, localVariableParams.length);
}
 
Example 13
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;
}
 
Example 14
Source File: DefaultStrategy.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static FieldNode createFieldCopy(ClassNode buildee, Parameter param) {
    Map<String, ClassNode> genericsSpec = createGenericsSpec(buildee);
    extractSuperClassGenerics(param.getType(), buildee, genericsSpec);
    ClassNode correctedParamType = correctToGenericsSpecRecurse(genericsSpec, param.getType());
    return new FieldNode(param.getName(), ACC_PRIVATE, correctedParamType, buildee, param.getInitialExpression());
}