org.codehaus.groovy.ast.Parameter Java Examples

The following examples show how to use org.codehaus.groovy.ast.Parameter. 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: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void createSoftSetter(FieldNode fieldNode, ClassNode type) {
    final BlockStatement body = new BlockStatement();
    final Expression fieldExpr = varX(fieldNode);
    final String name = getSetterName(fieldNode.getName().substring(1));
    final Parameter parameter = param(type, "value");
    final Expression paramExpr = varX(parameter);
    body.addStatement(ifElseS(
            notNullX(paramExpr),
            assignS(fieldExpr, ctorX(SOFT_REF, paramExpr)),
            assignS(fieldExpr, nullX())
    ));
    int visibility = ACC_PUBLIC;
    if (fieldNode.isStatic()) visibility |= ACC_STATIC;
    ClassNode declaringClass = fieldNode.getDeclaringClass();
    addGeneratedMethod(declaringClass, name, visibility, ClassHelper.VOID_TYPE, params(parameter), ClassNode.EMPTY_ARRAY, body);
}
 
Example #2
Source File: ParameterUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean parametersMatch(Parameter[] a, Parameter[] b, BiPredicate<ClassNode, ClassNode> typeChecker) {
    if (a.length == b.length) {
        boolean answer = true;
        for (int i = 0, n = a.length; i < n; i += 1) {
            ClassNode aType = a[i].getType();
            ClassNode bType = b[i].getType();

            if (!typeChecker.test(aType, bType)) {
                answer = false;
                break;
            }
        }
        return answer;
    }
    return false;
}
 
Example #3
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 #4
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private MethodNode addSyntheticMethodForDGSM(MethodNode mn) {
    Parameter[] parameters = removeFirstParameter(mn.getParameters());
    ArgumentListExpression args = args(parameters);
    args.getExpressions().add(0, ConstantExpression.NULL);

    MethodNode syntheticMethodNode = controller.getClassNode().addSyntheticMethod(
            "dgsm$$" + mn.getParameters()[0].getType().getName().replace(".", "$") + "$$" + mn.getName(),
            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
            mn.getReturnType(),
            parameters,
            ClassNode.EMPTY_ARRAY,
            block(
                    returnS(
                            callX(new ClassExpression(mn.getDeclaringClass()), mn.getName(), args)
                    )
            )
    );

    syntheticMethodNode.addAnnotation(new AnnotationNode(GENERATED_TYPE));
    syntheticMethodNode.addAnnotation(new AnnotationNode(COMPILE_STATIC_TYPE));

    return syntheticMethodNode;
}
 
Example #5
Source File: GroovyASTUtils.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
public static MethodNode getMethodFromCallExpression(MethodCall node, ASTNodeVisitor astVisitor, int argIndex) {
    List<MethodNode> possibleMethods = getMethodOverloadsFromCallExpression(node, astVisitor);
    if (!possibleMethods.isEmpty() && node.getArguments() instanceof ArgumentListExpression) {
        ArgumentListExpression actualArguments = (ArgumentListExpression) node.getArguments();
        MethodNode foundMethod = possibleMethods.stream().max(new Comparator<MethodNode>() {
            public int compare(MethodNode m1, MethodNode m2) {
                Parameter[] p1 = m1.getParameters();
                Parameter[] p2 = m2.getParameters();
                int m1Value = calculateArgumentsScore(p1, actualArguments, argIndex);
                int m2Value = calculateArgumentsScore(p2, actualArguments, argIndex);
                if (m1Value > m2Value) {
                    return 1;
                } else if (m1Value < m2Value) {
                    return -1;
                }
                return 0;
            }
        }).orElse(null);
        return foundMethod;
    }
    return null;
}
 
Example #6
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Statement createConstructorStatement(AbstractASTTransformation xform, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    final List<String> knownImmutableClasses = ImmutablePropertyUtils.getKnownImmutableClasses(xform, cNode);
    final List<String> knownImmutables = ImmutablePropertyUtils.getKnownImmutables(xform, cNode);
    FieldNode fNode = pNode.getField();
    final ClassNode fType = fNode.getType();
    Statement statement;
    boolean shouldNullCheck = NullCheckASTTransformation.hasIncludeGenerated(cNode);
    if (ImmutablePropertyUtils.isKnownImmutableType(fType, knownImmutableClasses) || isKnownImmutable(pNode.getName(), knownImmutables)) {
        statement = createConstructorStatementDefault(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isArray() || implementsCloneable(fType)) {
        statement = createConstructorStatementArrayOrCloneable(fNode, namedArgsMap, shouldNullCheck);
    } else if (derivesFromDate(fType)) {
        statement = createConstructorStatementDate(fNode, namedArgsMap, shouldNullCheck);
    } else if (isOrImplements(fType, COLLECTION_TYPE) || fType.isDerivedFrom(COLLECTION_TYPE) || isOrImplements(fType, MAP_TYPE) || fType.isDerivedFrom(MAP_TYPE)) {
        statement = createConstructorStatementCollection(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isResolved()) {
        xform.addError(ImmutablePropertyUtils.createErrorMessage(cNode.getName(), fNode.getName(), fType.getName(), "compiling"), fNode);
        statement = EmptyStatement.INSTANCE;
    } else {
        statement = createConstructorStatementGuarded(fNode, namedArgsMap, knownImmutables, knownImmutableClasses, shouldNullCheck);
    }
    return statement;
}
 
Example #7
Source File: ImmutablePropertyHandler.java    From groovy with 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 #8
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createConstructor(final ClassNode classNode) {
    Parameter[] params = new Parameter[]{
            new Parameter(MarkupTemplateEngine.MARKUPTEMPLATEENGINE_CLASSNODE, "engine"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "model"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "modelTypes"),
            new Parameter(TEMPLATECONFIG_CLASSNODE, "tplConfig")
    };
    List<Expression> vars = new LinkedList<Expression>();
    for (Parameter param : params) {
        vars.add(new VariableExpression(param));
    }
    ExpressionStatement body = new ExpressionStatement(
            new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(vars)));
    ConstructorNode ctor = new ConstructorNode(Opcodes.ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, body);
    classNode.addConstructor(ctor);
}
 
Example #9
Source File: MethodSignatureBuilder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MethodSignatureBuilder appendMethodParams(MethodNode method) {
    Parameter[] params = method.getParameters();

    builder.append("("); // NOI18N
    if (params.length > 0) {
        for (Parameter param : params) {
            builder.append(ElementUtils.getType(param.getType()).getNameWithoutPackage());
            builder.append(" "); // NOI18N
            builder.append(param.getName());
            builder.append(","); // NOI18N
        }
        builder.setLength(builder.length() - 1);
    }
    builder.append(")"); // NOI18N
    return this;
}
 
Example #10
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void printParams(PrintWriter out, MethodNode methodNode) {
    out.print("(");
    Parameter[] parameters = methodNode.getParameters();
    if (parameters != null && parameters.length != 0) {
        int lastIndex = parameters.length - 1;
        boolean vararg = parameters[lastIndex].getType().isArray();
        for (int i = 0; i != parameters.length; ++i) {
            printAnnotations(out, parameters[i]);
            if (i == lastIndex && vararg) {
                printType(out, parameters[i].getType().getComponentType());
                out.print("...");
            } else {
                printType(out, parameters[i].getType());
            }
            out.print(" ");
            out.print(parameters[i].getName());
            if (i + 1 < parameters.length) {
                out.print(", ");
            }
        }
    }
    out.print(")");
}
 
Example #11
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode type) {
    ConstructorNode newConstructor = type.addConstructor(ctor.getModifiers(), newParams, ctor.getExceptions(), code);
    newConstructor.putNodeMetaData(DEFAULT_PARAMETER_GENERATED, Boolean.TRUE);
    markAsGenerated(type, newConstructor);
    // TODO: Copy annotations, etc.?

    // set anon. inner enclosing method reference
    code.visit(new CodeVisitorSupport() {
        @Override
        public void visitConstructorCallExpression(ConstructorCallExpression call) {
            if (call.isUsingAnonymousInnerClass()) {
                call.getType().setEnclosingMethod(newConstructor);
            }
            super.visitConstructorCallExpression(call);
        }
    });
}
 
Example #12
Source File: AbstractExtensionMethodCache.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void accumulate(Map<String, List<MethodNode>> accumulator, boolean isStatic, MethodNode metaMethod,
                               Function<MethodNode, String> mapperFunction) {

    Parameter[] types = metaMethod.getParameters();
    Parameter[] parameters = new Parameter[types.length - 1];
    System.arraycopy(types, 1, parameters, 0, parameters.length);
    ExtensionMethodNode node = new ExtensionMethodNode(
            metaMethod,
            metaMethod.getName(),
            metaMethod.getModifiers(),
            metaMethod.getReturnType(),
            parameters,
            ClassNode.EMPTY_ARRAY, null,
            isStatic);
    node.setGenericsTypes(metaMethod.getGenericsTypes());
    ClassNode declaringClass = types[0].getType();
    node.setDeclaringClass(declaringClass);

    String key = mapperFunction.apply(metaMethod);

    List<MethodNode> nodes = accumulator.computeIfAbsent(key, k -> new ArrayList<>());
    nodes.add(node);
}
 
Example #13
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 #14
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void addHolderClassIdiomBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) {
    final ClassNode declaringClass = fieldNode.getDeclaringClass();
    final ClassNode fieldType = fieldNode.getType();
    final int visibility = ACC_PRIVATE | ACC_STATIC;
    final String fullName = declaringClass.getName() + "$" + fieldType.getNameWithoutPackage() + "Holder_" + fieldNode.getName().substring(1);
    final InnerClassNode holderClass = new InnerClassNode(declaringClass, fullName, visibility, ClassHelper.OBJECT_TYPE);
    final String innerFieldName = "INSTANCE";

    // we have two options:
    // (1) embed initExpr within holder class but redirect field access/method calls to declaring class members
    // (2) keep initExpr within a declaring class method that is only called by the holder class
    // currently we have gone with (2) for simplicity with only a slight memory footprint increase in the declaring class
    final String initializeMethodName = (fullName + "_initExpr").replace('.', '_');
    addGeneratedMethod(declaringClass, initializeMethodName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(initExpr));
    holderClass.addField(innerFieldName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            callX(declaringClass, initializeMethodName));

    final Expression innerField = propX(classX(holderClass), innerFieldName);
    declaringClass.getModule().addClass(holderClass);
    body.addStatement(returnS(innerField));
}
 
Example #15
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static int measureParametersAndArgumentsDistance(final Parameter[] parameters, final ClassNode[] argumentTypes) {
    int dist = -1;
    if (parameters.length == argumentTypes.length) {
        int allPMatch = allParametersAndArgumentsMatch(parameters, argumentTypes);
        int firstParamDist = firstParametersAndArgumentsMatch(parameters, argumentTypes);
        int lastArgMatch = isVargs(parameters) && firstParamDist >= 0 ? lastArgMatchesVarg(parameters, argumentTypes) : -1;
        if (lastArgMatch >= 0) {
            lastArgMatch += getVarargsDistance(parameters);
        }
        dist = allPMatch >= 0 ? Math.max(allPMatch, lastArgMatch) : lastArgMatch;
    } else if (isVargs(parameters)) {
        dist = firstParametersAndArgumentsMatch(parameters, argumentTypes);
        if (dist >= 0) {
            // varargs methods must not be preferred to methods without varargs
            // for example :
            // int sum(int x) should be preferred to int sum(int x, int... y)
            dist += getVarargsDistance(parameters);
            // there are three case for vargs
            // (1) varg part is left out (there's one less argument than there are parameters)
            // (2) last argument is put in the vargs array
            //     that case is handled above already when params and args have the same length
            if (parameters.length < argumentTypes.length) {
                // (3) there is more than one argument for the vargs array
                int excessArgumentsDistance = excessArgumentsMatchesVargsParameter(parameters, argumentTypes);
                if (excessArgumentsDistance < 0) {
                    dist = -1;
                } else {
                    dist += excessArgumentsDistance;
                }
            }
        }
    }
    return dist;
}
 
Example #16
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void addPropertyMethod(MethodNode method) {
    classNode.addMethod(method);
    markAsGenerated(classNode, method);
    // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one
    String methodName = method.getName();
    Parameter[] parameters = method.getParameters();
    ClassNode methodReturnType = method.getReturnType();
    for (MethodNode node : classNode.getAbstractMethods()) {
        if (!node.getDeclaringClass().equals(classNode)) continue;
        if (node.getName().equals(methodName) && node.getParameters().length == parameters.length) {
            if (parameters.length == 1) {
                // setter
                ClassNode abstractMethodParameterType = node.getParameters()[0].getType();
                ClassNode methodParameterType = parameters[0].getType();
                if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) {
                    continue;
                }
            }
            ClassNode nodeReturnType = node.getReturnType();
            if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) {
                continue;
            }
            // matching method, remove abstract status and use the same body
            node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT);
            node.setCode(method.getCode());
        }
    }
}
 
Example #17
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 #18
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Return an existing method if one exists or else create a new method and mark it as {@code @Generated}.
 *
 * @see ClassNode#addMethod(String, int, ClassNode, Parameter[], ClassNode[], Statement)
 */
public static MethodNode addGeneratedMethod(ClassNode cNode, String name,
                            int modifiers,
                            ClassNode returnType,
                            Parameter[] parameters,
                            ClassNode[] exceptions,
                            Statement code) {
    MethodNode existing = cNode.getDeclaredMethod(name, parameters);
    if (existing != null) return existing;
    MethodNode result = new MethodNode(name, modifiers, returnType, parameters, exceptions, code);
    addGeneratedMethod(cNode, result);
    return result;
}
 
Example #19
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 #20
Source File: ExternalizeMethodsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createReadExternal(ClassNode cNode, List<String> excludes, List<FieldNode> list) {
    final BlockStatement body = new BlockStatement();
    Parameter oin = param(OBJECTINPUT_TYPE, "oin");
    for (FieldNode fNode : list) {
        if (excludes != null && excludes.contains(fNode.getName())) continue;
        if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue;
        String suffix = suffixForField(fNode);
        MethodCallExpression readObject = callX(varX(oin), "read" + suffix);
        readObject.setImplicitThis(false);
        body.addStatement(assignS(varX(fNode), suffix.equals("Object") ? castX(GenericsUtils.nonGeneric(fNode.getType()), readObject) : readObject));
    }
    addGeneratedMethod(cNode, "readExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, params(oin), ClassNode.EMPTY_ARRAY, body);
}
 
Example #21
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 #22
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private BlockStatement createFinallyBlockForNewTryCatchStatement(String primaryExcName, String firstResourceIdentifierName) {
    BlockStatement finallyBlock = new BlockStatement();

    // primaryExc != null
    BooleanExpression conditionExpression =
            new BooleanExpression(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1),
                            new ConstantExpression(null)));

    // try-catch statement
    TryCatchStatement newTryCatchStatement =
            new TryCatchStatement(
                    astBuilder.createBlockStatement(this.createCloseResourceStatement(firstResourceIdentifierName)), // { Identifier?.close(); }
                    EmptyStatement.INSTANCE);


    String suppressedExcName = this.genSuppressedExcName();
    newTryCatchStatement.addCatch(
            // catch (Throwable #suppressedExc) { .. }
            new CatchStatement(
                    new Parameter(ClassHelper.make(Throwable.class), suppressedExcName),
                    astBuilder.createBlockStatement(this.createAddSuppressedStatement(primaryExcName, suppressedExcName)) // #primaryExc.addSuppressed(#suppressedExc);
            )
    );

    // if (#primaryExc != null) { ... }
    IfStatement ifStatement =
            new IfStatement(
                    conditionExpression,
                    newTryCatchStatement,
                    this.createCloseResourceStatement(firstResourceIdentifierName) // Identifier?.close();
            );
    astBuilder.appendStatementsToBlockStatement(finallyBlock, ifStatement);

    return astBuilder.createBlockStatement(finallyBlock);
}
 
Example #23
Source File: DefaultPropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement assignFieldS(boolean useSetters, Parameter map, String name) {
    ArgumentListExpression nameArg = args(constX(name));
    MethodCallExpression var = callX(varX(map), "get", nameArg);
    var.setImplicitThis(false);
    MethodCallExpression containsKey = callX(varX(map), "containsKey", nameArg);
    containsKey.setImplicitThis(false);
    return ifS(containsKey, useSetters ?
            setViaSetterS(name, var) :
            assignToFieldS(name, var));
}
 
Example #24
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Parameter[] cleanParameters(Parameter[] parameters) {
    Parameter[] params = new Parameter[parameters.length];
    for (int i = 0; i < params.length; i++) {
        params[i] = new Parameter(cleanType(parameters[i].getType()), parameters[i].getName());
    }
    return params;
}
 
Example #25
Source File: EqualsAndHashCodeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void createHashCode(ClassNode cNode, boolean cacheResult, boolean includeFields, boolean callSuper, List<String> excludes, List<String> includes, boolean allNames, boolean allProperties) {
    // make a public method if none exists otherwise try a private method with leading underscore
    boolean hasExistingHashCode = hasDeclaredMethod(cNode, "hashCode", 0);
    if (hasExistingHashCode && hasDeclaredMethod(cNode, "_hashCode", 0)) return;

    final BlockStatement body = new BlockStatement();
    // TODO use pList and fList
    if (cacheResult) {
        final FieldNode hashField = cNode.addField("$hash$code", ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.int_TYPE, null);
        final Expression hash = varX(hashField);
        body.addStatement(ifS(
                isZeroX(hash),
                calculateHashStatements(cNode, hash, includeFields, callSuper, excludes, includes, allNames, allProperties)
        ));
        body.addStatement(returnS(hash));
    } else {
        body.addStatement(calculateHashStatements(cNode, null, includeFields, callSuper, excludes, includes, allNames, allProperties));
    }

    addGeneratedMethod(cNode,
            hasExistingHashCode ? "_hashCode" : "hashCode",
            hasExistingHashCode ? ACC_PRIVATE : ACC_PUBLIC,
            ClassHelper.int_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            body);
}
 
Example #26
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createSimpleClone(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    if (cNode.getDeclaredConstructors().isEmpty()) {
        // add no-arg constructor
        addGeneratedConstructor(cNode, ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, block(EmptyStatement.INSTANCE));
    }
    addSimpleCloneHelperMethod(cNode, fieldNodes, excludes);
    final Expression result = localVarX("_result");
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, block(
        declS(result, ctorX(cNode)),
        stmt(callThisX("cloneOrCopyMembers", args(result))),
        returnS(result)));
}
 
Example #27
Source File: FindTypeUsagesVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitConstructorOrMethod(MethodNode method, boolean isConstructor) {
    if (!isConstructor && isEquals(method.getReturnType())) {
        addIfEquals(method);
    }

    for (Parameter param : method.getParameters()) {
        addIfEquals(param);
    }
    super.visitConstructorOrMethod(method, isConstructor);
}
 
Example #28
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSetter(FieldNode fNode, ClassNode componentType) {
    ClassNode cNode = fNode.getDeclaringClass();
    BlockStatement body = new BlockStatement();
    Parameter[] theParams = params(
            new Parameter(ClassHelper.int_TYPE, "index"),
            new Parameter(componentType, "value"));
    body.addStatement(assignS(indexX(varX(fNode), varX(theParams[0])), varX(theParams[1])));
    addGeneratedMethod(cNode, getSetterName(fNode.getName()), getModifiers(fNode), ClassHelper.VOID_TYPE, theParams, null, body);
}
 
Example #29
Source File: GroovyDeclarationFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getFqNameForNode(ASTNode node) {
    if (node instanceof DeclarationExpression) {
        return ((BinaryExpression) node).getLeftExpression().getType().getName();
    } else if (node instanceof Expression) {
        return ((Expression) node).getType().getName();
    } else if (node instanceof PropertyNode) {
        return ((PropertyNode) node).getField().getType().getName();
    } else if (node instanceof FieldNode) {
        return ((FieldNode) node).getType().getName();
    } else if (node instanceof Parameter) {
        return ((Parameter) node).getType().getName();
    }

    return "";
}
 
Example #30
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSimpleCloneHelperMethod(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    Parameter methodParam = new Parameter(GenericsUtils.nonGeneric(cNode), "other");
    final Expression other = varX(methodParam);
    boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
    BlockStatement methodBody = new BlockStatement();
    if (hasParent) {
        methodBody.addStatement(stmt(callSuperX("cloneOrCopyMembers", args(other))));
    }
    for (FieldNode fieldNode : fieldNodes) {
        String name = fieldNode.getName();
        if (excludes != null && excludes.contains(name)) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression direct = propX(varX("this"), name);
        Expression to = propX(other, name);
        Statement assignDirect = assignS(to, direct);
        Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
        Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
        if (isCloneableType(fieldType)) {
            methodBody.addStatement(assignCloned);
        } else if (!possiblyCloneable(fieldType)) {
            methodBody.addStatement(assignDirect);
        } else {
            methodBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
        }
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "cloneOrCopyMembers", ACC_PROTECTED, ClassHelper.VOID_TYPE, params(methodParam), exceptions, methodBody);
}