org.codehaus.groovy.ast.expr.ArgumentListExpression Java Examples

The following examples show how to use org.codehaus.groovy.ast.expr.ArgumentListExpression. 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: MethodCallExpressionTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Identifies a method call expression on {@link DefaultGroovyMethods#is(Object, Object)} and if recognized, transforms it into a {@link CompareIdentityExpression}.
 * @param call a method call to be transformed
 * @return null if the method call is not DGM#is, or {@link CompareIdentityExpression}
 */
private static Expression tryTransformIsToCompareIdentity(MethodCallExpression call) {
    if (call.isSafe()) return null;
    MethodNode methodTarget = call.getMethodTarget();
    if (methodTarget instanceof ExtensionMethodNode && "is".equals(methodTarget.getName()) && methodTarget.getParameters().length==1) {
        methodTarget = ((ExtensionMethodNode) methodTarget).getExtensionMethodNode();
        ClassNode owner = methodTarget.getDeclaringClass();
        if (DGM_CLASSNODE.equals(owner)) {
            Expression args = call.getArguments();
            if (args instanceof ArgumentListExpression) {
                ArgumentListExpression arguments = (ArgumentListExpression) args;
                List<Expression> exprs = arguments.getExpressions();
                if (exprs.size() == 1) {
                    CompareIdentityExpression cid = new CompareIdentityExpression(call.getObjectExpression(), exprs.get(0));
                    cid.setSourcePosition(call);
                    return cid;
                }
            }
        }
    }
    return null;
}
 
Example #2
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 6 votes vote down vote up
@Override
public void visitTupleExpression(TupleExpression tupleExpression) {
  if (!methodCallStack.isEmpty()) {
    MethodCallExpression call = Iterables.getLast(methodCallStack);
    if (call.getArguments() == tupleExpression) {
      String parent = call.getMethodAsString();
      String parentParent = getParentParent();
      if (!(tupleExpression instanceof ArgumentListExpression)) {
        Map<String, String> namedArguments = new HashMap<>();
        for (Expression subExpr : tupleExpression.getExpressions()) {
          if (subExpr instanceof NamedArgumentListExpression) {
            NamedArgumentListExpression nale = (NamedArgumentListExpression) subExpr;
            for (MapEntryExpression mae : nale.getMapEntryExpressions()) {
              namedArguments.put(
                  mae.getKeyExpression().getText(), mae.getValueExpression().getText());
            }
          }
        }
        checkMethodCall(parent, parentParent, namedArguments);
      }
    }
  }
  super.visitTupleExpression(tupleExpression);
}
 
Example #3
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * This will return an initial guess as to the string representation of the parent parent object,
 * based solely on the method callstack hierarchy. Any direct property or variable parents should
 * be resolved by using the getValidStringRepresentation function.
 */
private String getParentParent() {
  for (int i = methodCallStack.size() - 2; i >= 0; i--) {
    MethodCallExpression expression = methodCallStack.get(i);
    Expression arguments = expression.getArguments();
    if (arguments instanceof ArgumentListExpression) {
      ArgumentListExpression ale = (ArgumentListExpression) arguments;
      List<Expression> expressions = ale.getExpressions();
      if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) {
        return expression.getMethodAsString();
      }
    }
  }

  return null;
}
 
Example #4
Source File: DependenciesVisitor.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Override
public void visitArgumentlistExpression(final ArgumentListExpression argumentListExpression) {
    if (inDependenciesBlock) {
        final List<Expression> expressions = argumentListExpression.getExpressions();

        if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) {
            final ClosureExpression closureExpression = (ClosureExpression) expressions.get(0);
            if (closureExpression.getCode() instanceof BlockStatement) {
                final BlockStatement blockStatement = (BlockStatement) closureExpression.getCode();
                final List<Statement> statements = blockStatement.getStatements();
                for (final Statement statement : statements) {
                    addDependencyFromStatement(statement);
                }
            }
        }
    }

    super.visitArgumentlistExpression(argumentListExpression);
}
 
Example #5
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void despreadList(final List<Expression> expressions, final boolean wrap) {
    List<Expression> spreadIndexes = new ArrayList<>();
    List<Expression> spreadExpressions = new ArrayList<>();
    List<Expression> normalArguments = new ArrayList<>();
    for (int i = 0, n = expressions.size(); i < n; i += 1) {
        Expression expr = expressions.get(i);
        if (!(expr instanceof SpreadExpression)) {
            normalArguments.add(expr);
        } else {
            spreadIndexes.add(new ConstantExpression(i - spreadExpressions.size(), true));
            spreadExpressions.add(((SpreadExpression) expr).getExpression());
        }
    }

    // load normal arguments as array
    visitTupleExpression(new ArgumentListExpression(normalArguments), wrap);
    // load spread expressions as array
    new TupleExpression(spreadExpressions).visit(this);
    // load insertion index
    new ArrayExpression(ClassHelper.int_TYPE, spreadIndexes, null).visit(this);

    controller.getOperandStack().remove(1);
    despreadList.call(controller.getMethodVisitor());
}
 
Example #6
Source File: InnerClassVisitorHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static void setMethodDispatcherCode(BlockStatement block, Expression thiz, Parameter[] parameters) {
    List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>();
    gStringStrings.add(new ConstantExpression(""));
    gStringStrings.add(new ConstantExpression(""));
    List<Expression> gStringValues = new ArrayList<Expression>();
    gStringValues.add(new VariableExpression(parameters[0]));
    block.addStatement(
            new ReturnStatement(
                    new MethodCallExpression(
                            thiz,
                            new GStringExpression("$name", gStringStrings, gStringValues),
                            new ArgumentListExpression(
                                    new SpreadExpression(new VariableExpression(parameters[1]))
                            )
                    )
            )
    );
}
 
Example #7
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 #8
Source File: CompletionHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ArgumentListExpression getSurroundingArgumentList(AstPath path) {
    if (path == null) {
        LOG.log(Level.FINEST, "path == null"); // NOI18N
        return null;
    }

    LOG.log(Level.FINEST, "AEL, Path : {0}", path);

    for (Iterator<ASTNode> it = path.iterator(); it.hasNext();) {
        ASTNode current = it.next();
        if (current instanceof ArgumentListExpression) {

            return (ArgumentListExpression) current;
        }
    }
    return null;
}
 
Example #9
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 #10
Source File: MethodSignatureBuilder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MethodSignatureBuilder appendMethodParams(Expression arguments) {
    builder.append("("); // NOI18N

    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argumentList = ((ArgumentListExpression) arguments);
        if (argumentList.getExpressions().size() > 0) {
            for (Expression argument : argumentList.getExpressions()) {
                builder.append(ElementUtils.getTypeNameWithoutPackage(argument.getType()));
                builder.append(" "); // NOI18N
                builder.append(argument.getText());
                builder.append(","); // NOI18N
            }
            builder.setLength(builder.length() - 1);
        }
    }
    builder.append(")"); // NOI18N
    return this;
}
 
Example #11
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 #12
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 #13
Source File: AstBuilderTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean handleTargetMethodCallExpression(MethodCallExpression call) {
    ClosureExpression closureExpression = getClosureArgument(call);
    List<Expression> otherArgs = getNonClosureArguments(call);
    String source = convertClosureToSource(closureExpression);

    // parameter order is build(CompilePhase, boolean, String)
    otherArgs.add(new ConstantExpression(source));
    call.setArguments(new ArgumentListExpression(otherArgs));
    call.setMethod(new ConstantExpression("buildFromBlock"));
    call.setSpreadSafe(false);
    call.setSafe(false);
    call.setImplicitThis(false);
    
    return false;
}
 
Example #14
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void findPossibleOuterClassNodeForNonStaticInnerClassInstantiation(final ConstructorCallExpression cce) {
    // GROOVY-8947: Fail to resolve non-static inner class outside of outer class
    // `new Computer().new Cpu(4)` will be parsed to `new Cpu(new Computer(), 4)`
    // so non-static inner class instantiation expression's first argument is a constructor call of outer class
    // but the first argument is constructor call can not be non-static inner class instantiation expression, e.g.
    // `new HashSet(new ArrayList())`, so we add "possible" to the variable name
    Expression argumentExpression = cce.getArguments();
    if (argumentExpression instanceof ArgumentListExpression) {
        ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentExpression;
        List<Expression> expressionList = argumentListExpression.getExpressions();
        if (!expressionList.isEmpty()) {
            Expression firstExpression = expressionList.get(0);

            if (firstExpression instanceof ConstructorCallExpression) {
                ConstructorCallExpression constructorCallExpression = (ConstructorCallExpression) firstExpression;
                ClassNode possibleOuterClassNode = constructorCallExpression.getType();
                possibleOuterClassNodeMap.put(cce.getType(), possibleOuterClassNode);
            }
        }
    }
}
 
Example #15
Source File: GroovyTypeCheckingExtensionSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<MethodNode> handleMissingMethod(final ClassNode receiver, final String name, final ArgumentListExpression argumentList, final ClassNode[] argumentTypes, final MethodCall call) {
    List<Closure> onMethodSelection = eventHandlers.get("handleMissingMethod");
    List<MethodNode> methodList = new LinkedList<MethodNode>();
    if (onMethodSelection != null) {
        for (Closure closure : onMethodSelection) {
            Object result = safeCall(closure, receiver, name, argumentList, argumentTypes, call);
            if (result != null) {
                if (result instanceof MethodNode) {
                    methodList.add((MethodNode) result);
                } else if (result instanceof Collection) {
                    methodList.addAll((Collection<? extends MethodNode>) result);
                } else {
                    throw new GroovyBugError("Type checking extension returned unexpected method list: " + result);
                }
            }
        }
    }
    return methodList;
}
 
Example #16
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitArgumentlistExpression(ArgumentListExpression ale) {
    boolean old = inArgumentList;
    inArgumentList = true;
    super.visitArgumentlistExpression(ale);
    inArgumentList = old;
}
 
Example #17
Source File: Script.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a newline to the current 'out' variable which should be a PrintWriter
 * or at least have a println() method defined on it.
 * If there is no 'out' property then print to standard out.
 */
public void println() {
    Object object;

    try {
        object = getProperty("out");
    } catch (MissingPropertyException e) {
        System.out.println();
        return;
    }

    InvokerHelper.invokeMethod(object, "println", ArgumentListExpression.EMPTY_ARRAY);
}
 
Example #18
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transform(Expression expr) {
    if (expr == null) return null;
    if (expr instanceof DeclarationExpression) {
        DeclarationExpression de = (DeclarationExpression) expr;
        if (de.getLeftExpression() == candidate.getLeftExpression()) {
            if (insideScriptBody) {
                // TODO make EmptyExpression work
                // partially works but not if only thing in script
                // return EmptyExpression.INSTANCE;
                return nullX();
            }
            addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script body.", expr);
            return expr;
        }
    } else if (insideScriptBody && expr instanceof VariableExpression && currentClosure != null) {
        VariableExpression ve = (VariableExpression) expr;
        if (ve.getName().equals(variableName)) {
            adjustToClassVar(ve);
            return ve;
        }
    } else if (currentAIC != null && expr instanceof ArgumentListExpression) {
        // if a match is found, the compiler will have already set up aic constructor to hav
        // an argument which isn't needed since we'll be accessing the field; we must undo it
        Expression skip = null;
        List<Expression> origArgList = ((ArgumentListExpression) expr).getExpressions();
        for (int i = 0; i < origArgList.size(); i++) {
            Expression arg = origArgList.get(i);
            if (matchesCandidate(arg)) {
                skip = arg;
                adjustConstructorAndFields(i, currentAIC.getType());
                break;
            }
        }
        if (skip != null) {
            return adjustedArgList(skip, origArgList);
        }
    }
    return expr.transformExpression(this);
}
 
Example #19
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private TernaryExpression createStaticReceiver(final Expression receiver) {
    return new TernaryExpression(
            new BooleanExpression(new BinaryExpression(
                    receiver,
                    Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1),
                    new ClassExpression(ClassHelper.CLASS_Type)
            )),
            receiver,
            new MethodCallExpression(createFieldHelperReceiver(), "getClass", ArgumentListExpression.EMPTY_ARGUMENTS)
    );
}
 
Example #20
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitArgumentlistExpression(final ArgumentListExpression ale) {
    if (containsSpreadExpression(ale)) {
        despreadList(ale.getExpressions(), true);
    } else {
        visitTupleExpression(ale, true);
    }
}
 
Example #21
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformFieldExpression(final FieldExpression exp) {
    FieldNode field = exp.getField();
    MethodCallExpression mce = new MethodCallExpression(
            createFieldHelperReceiver(),
            Traits.helperGetterName(field),
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setSourcePosition(exp);
    mce.setImplicitThis(false);
    markDynamicCall(mce, field, field.isStatic());
    return mce;
}
 
Example #22
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression createFieldHelperCall(Expression exp, ClassNode weavedType, String propName) {
    String method = Traits.helperGetterName(new FieldNode(propName, 0, ClassHelper.OBJECT_TYPE, weavedType, null));
    MethodCallExpression mce = new MethodCallExpression(
            createFieldHelperReceiver(),
            method,
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setSourcePosition(exp instanceof PropertyExpression ? ((PropertyExpression) exp).getProperty() : exp);
    mce.setImplicitThis(false);
    return mce;
}
 
Example #23
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createSuperFallback(MethodNode forwarderMethod, ClassNode returnType) {
    ArgumentListExpression args = new ArgumentListExpression();
    Parameter[] forwarderMethodParameters = forwarderMethod.getParameters();
    for (final Parameter forwarderMethodParameter : forwarderMethodParameters) {
        args.addExpression(new VariableExpression(forwarderMethodParameter));
    }
    BinaryExpression instanceOfExpr = new BinaryExpression(new VariableExpression("this"), Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1), new ClassExpression(Traits.GENERATED_PROXY_CLASSNODE));
    MethodCallExpression superCall = new MethodCallExpression(
            new VariableExpression("super"),
            forwarderMethod.getName(),
            args
    );
    superCall.setImplicitThis(false);
    CastExpression proxyReceiver = new CastExpression(Traits.GENERATED_PROXY_CLASSNODE, new VariableExpression("this"));
    MethodCallExpression getProxy = new MethodCallExpression(proxyReceiver, "getProxyTarget", ArgumentListExpression.EMPTY_ARGUMENTS);
    getProxy.setImplicitThis(true);
    StaticMethodCallExpression proxyCall = new StaticMethodCallExpression(
            ClassHelper.make(InvokerHelper.class),
            "invokeMethod",
            new ArgumentListExpression(getProxy, new ConstantExpression(forwarderMethod.getName()), new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions()))
    );
    IfStatement stmt = new IfStatement(
            new BooleanExpression(instanceOfExpr),
            new ExpressionStatement(new CastExpression(returnType,proxyCall)),
            new ExpressionStatement(superCall)
    );
    return stmt;
}
 
Example #24
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformMethodCallExpression(final MethodCallExpression exp) {
    if (isTraitSuperPropertyExpression(exp.getObjectExpression())) {
        Expression objectExpression = exp.getObjectExpression();
        ClassNode traitReceiver = ((PropertyExpression) objectExpression).getObjectExpression().getType();

        if (traitReceiver != null) {
            // (SomeTrait.super).foo() --> SomeTrait$Helper.foo(this)
            ClassExpression receiver = new ClassExpression(
                    getHelper(traitReceiver)
            );
            ArgumentListExpression newArgs = new ArgumentListExpression();
            Expression arguments = exp.getArguments();
            newArgs.addExpression(new VariableExpression("this"));
            if (arguments instanceof TupleExpression) {
                List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
                for (Expression expression : expressions) {
                    newArgs.addExpression(transform(expression));
                }
            } else {
                newArgs.addExpression(transform(arguments));
            }
            MethodCallExpression result = new MethodCallExpression(
                    receiver,
                    transform(exp.getMethod()),
                    newArgs
            );
            result.setImplicitThis(false);
            result.setSpreadSafe(exp.isSpreadSafe());
            result.setSafe(exp.isSafe());
            result.setSourcePosition(exp);
            return result;
        }
    }
    return super.transform(exp);
}
 
Example #25
Source File: StaticCompilationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstructorCallExpression(final ConstructorCallExpression call) {
    super.visitConstructorCallExpression(call);

    if (call.isUsingAnonymousInnerClass() && call.getType().getNodeMetaData(StaticTypeCheckingVisitor.class) != null) {
        ClassNode anonType = call.getType();
        anonType.putNodeMetaData(STATIC_COMPILE_NODE, anonType.getEnclosingMethod().getNodeMetaData(STATIC_COMPILE_NODE));
        anonType.putNodeMetaData(WriterControllerFactory.class, anonType.getOuterClass().getNodeMetaData(WriterControllerFactory.class));
    }

    MethodNode target = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (target == null && call.getLineNumber() > 0) {
        addError("Target constructor for constructor call expression hasn't been set", call);
    } else if (target == null) {
        // try to find a target
        ArgumentListExpression argumentListExpression = InvocationWriter.makeArgumentList(call.getArguments());
        List<Expression> expressions = argumentListExpression.getExpressions();
        ClassNode[] args = new ClassNode[expressions.size()];
        for (int i = 0, n = args.length; i < n; i += 1) {
            args[i] = typeChooser.resolveType(expressions.get(i), classNode);
        }
        target = findMethodOrFail(call, call.isSuperCall() ? classNode.getSuperClass() : classNode, "<init>", args);
        call.putNodeMetaData(DIRECT_METHOD_CALL_TARGET, target);
    }
    if (target != null) {
        memorizeInitialExpressions(target);
    }
}
 
Example #26
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * if Class.forName(x) is recognized, make a direct method call
 */
protected boolean makeClassForNameCall(final Expression origin, final Expression receiver, final Expression message, final Expression arguments) {
    if (!(receiver instanceof ClassExpression)) return false;
    ClassExpression ce = (ClassExpression) receiver;
    if (!ClassHelper.CLASS_Type.equals(ce.getType())) return false;
    String msg = getMethodName(message);
    if (!"forName".equals(msg)) return false;
    ArgumentListExpression ae = makeArgumentList(arguments);
    if (ae.getExpressions().size() != 1) return false;
    return writeDirectMethodCall(CLASS_FOR_NAME_STRING, false, receiver, ae);
}
 
Example #27
Source File: ListExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformRegularConstructor(final ListExpression expr, final MethodNode target) {
    // can be replaced with a direct constructor call
    List<Expression> transformedArgs = transformArguments(expr);
    ConstructorCallExpression cce = new ConstructorCallExpression(
            target.getDeclaringClass(),
            new ArgumentListExpression(transformedArgs)
    );
    cce.setSourcePosition(expr);
    cce.putNodeMetaData(DIRECT_METHOD_CALL_TARGET, target);
    return cce;
}
 
Example #28
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void assignToArray(final Expression parent, final Expression receiver, final Expression index, final Expression rhsValueLoader, final boolean safe) {
    // let's replace this assignment to a subscript operator with a
    // method call
    // e.g. x[5] = 10
    // -> (x, [], 5), =, 10
    // -> methodCall(x, "putAt", [5, 10])
    ArgumentListExpression ae = new ArgumentListExpression(index,rhsValueLoader);
    controller.getInvocationWriter().makeCall(parent, receiver, constX("putAt"), ae, InvocationWriter.invokeMethod, safe, false, false);
    controller.getOperandStack().pop();
    // return value of assignment
    rhsValueLoader.visit(controller.getAcg());
}
 
Example #29
Source File: InvokeDynamicWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void makeIndyCall(MethodCallerMultiAdapter adapter, Expression receiver, boolean implicitThis, boolean safe, String methodName, Expression arguments) {
    OperandStack operandStack = controller.getOperandStack();

    StringBuilder sig = new StringBuilder(prepareIndyCall(receiver, implicitThis));

    // load arguments
    int numberOfArguments = 1;
    ArgumentListExpression ae = makeArgumentList(arguments);
    boolean containsSpreadExpression = AsmClassGenerator.containsSpreadExpression(arguments);
    AsmClassGenerator acg = controller.getAcg();
    if (containsSpreadExpression) {
        acg.despreadList(ae.getExpressions(), true);
        sig.append(getTypeDescription(Object[].class));
    } else {
        for (Expression arg : ae.getExpressions()) {
            arg.visit(acg);
            if (arg instanceof CastExpression) {
                operandStack.box();
                acg.loadWrapper(arg);
                sig.append(getTypeDescription(Wrapper.class));
            } else {
                sig.append(getTypeDescription(operandStack.getTopOperand()));
            }
            numberOfArguments++;
        }
    }

    sig.append(")Ljava/lang/Object;");
    String callSiteName = METHOD.getCallSiteName();
    if (adapter == null) callSiteName = INIT.getCallSiteName();
    int flags = getMethodCallFlags(adapter, safe, containsSpreadExpression);
    finishIndyCall(BSM, callSiteName, sig.toString(), numberOfArguments, methodName, flags);
}
 
Example #30
Source File: RangeExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Expression transformRangeExpression(RangeExpression range) {
    final ClassNode inferred = range.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
    if (INTRANGE_TYPE.equals(inferred)) {
        ArgumentListExpression bounds = new ArgumentListExpression(new ConstantExpression(range.isInclusive(),true),range.getFrom(), range.getTo());
        ConstructorCallExpression cce = new ConstructorCallExpression(INTRANGE_TYPE, bounds);
        cce.setSourcePosition(range);
        cce.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, INTRANGE_CTOR);
        cce.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, INTRANGE_TYPE);
        return transformer.transform(cce);
    }
    return transformer.superTransform(range);
}