Java Code Examples for org.codehaus.groovy.ast.expr.ConstructorCallExpression#getArguments()

The following examples show how to use org.codehaus.groovy.ast.expr.ConstructorCallExpression#getArguments() . 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: StaticImportVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformConstructorCallExpression(ConstructorCallExpression cce) {
    inSpecialConstructorCall = cce.isSpecialCall();
    Expression expression = cce.getArguments();
    if (expression instanceof TupleExpression) {
        TupleExpression tuple = (TupleExpression) expression;
        if (tuple.getExpressions().size() == 1) {
            expression = tuple.getExpression(0);
            if (expression instanceof NamedArgumentListExpression) {
                NamedArgumentListExpression namedArgs = (NamedArgumentListExpression) expression;
                List<MapEntryExpression> entryExpressions = namedArgs.getMapEntryExpressions();
                for (int i = 0; i < entryExpressions.size(); i++) {
                    entryExpressions.set(i, (MapEntryExpression) transformMapEntryExpression(entryExpressions.get(i), cce.getType()));
                }
            }
        }
    }
    Expression ret = cce.transformExpression(this);
    inSpecialConstructorCall = false;
    return ret;
}
 
Example 2
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 3
Source File: ConstructorCallTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
public MapStyleConstructorCall(
        final StaticCompilationTransformer transformer,
        final ClassNode declaringClass,
        final MapExpression map,
        final ConstructorCallExpression originalCall) {
    super(declaringClass);
    this.staticCompilationTransformer = transformer;
    this.declaringClass = declaringClass;
    this.map = map;
    this.originalCall = originalCall;
    this.setSourcePosition(originalCall);
    this.copyNodeMetaData(originalCall);
    List<Expression> originalExpressions = originalCall.getArguments() instanceof TupleExpression
            ? ((TupleExpression) originalCall.getArguments()).getExpressions()
            : null;
    this.innerClassCall = originalExpressions != null && originalExpressions.size() == 2;
}
 
Example 4
Source File: InnerClassVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void passThisReference(ConstructorCallExpression call) {
    ClassNode cn = call.getType().redirect();
    if (!shouldHandleImplicitThisForInnerClass(cn)) return;

    boolean isInStaticContext = true;
    if (currentMethod != null)
        isInStaticContext = currentMethod.getVariableScope().isInStaticContext();
    else if (currentField != null)
        isInStaticContext = currentField.isStatic();
    else if (processingObjInitStatements)
        isInStaticContext = false;

    // if constructor call is not in static context, return
    if (isInStaticContext) {
        // constructor call is in static context and the inner class is non-static - 1st arg is supposed to be
        // passed as enclosing "this" instance
        //
        Expression args = call.getArguments();
        if (args instanceof TupleExpression && ((TupleExpression) args).getExpressions().isEmpty()) {
            addError("No enclosing instance passed in constructor call of a non-static inner class", call);
        }
        return;
    }
    insertThis0ToSuperCall(call, cn);
}
 
Example 5
Source File: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
public boolean addGeneratedClosureConstructorCall(final ConstructorCallExpression call) {
    ClassNode classNode = controller.getClassNode();
    if (!classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    ClassNode callNode = classNode.getSuperClass();
    TupleExpression arguments = (TupleExpression) call.getArguments();
    if (arguments.getExpressions().size()!=2) throw new GroovyBugError("expected 2 arguments for closure constructor super call, but got"+arguments.getExpressions().size());
    arguments.getExpression(0).visit(acg);
    operandStack.box();
    arguments.getExpression(1).visit(acg);
    operandStack.box();
    //TODO: replace with normal String, p not needed
    Parameter p = new Parameter(ClassHelper.OBJECT_TYPE,"_p");
    String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, new Parameter[]{p,p});
    mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "<init>", descriptor, false);
    operandStack.remove(2);
    return true;
}
 
Example 6
Source File: Methods.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static int getParameterCount(ConstructorCallExpression constructorCall) {
    Expression expression = constructorCall.getArguments();
    if (expression instanceof ArgumentListExpression) {
        return ((ArgumentListExpression) expression).getExpressions().size();
    } else if (expression instanceof NamedArgumentListExpression) {
        // this is in fact map acting as named parameters
        // lets return size 1
        return 1;
    } else {
        return -1;
    }
}
 
Example 7
Source File: NamedParamsCompletion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean complete(List<CompletionProposal> proposals, CompletionContext context, int anchor) {
    this.context = context;

    ASTNode leaf = context.path.leaf();

    if (leaf instanceof ConstructorCallExpression) {
        ConstructorCallExpression constructorCall = (ConstructorCallExpression) leaf;
        
        Expression constructorArgs = constructorCall.getArguments();
        if (constructorArgs instanceof TupleExpression) {
            List<Expression> arguments = ((TupleExpression) constructorArgs).getExpressions();

            if (arguments.isEmpty()) {
                completeNamedParams(proposals, anchor, constructorCall, null);
            } else {
                for (Expression argExpression : arguments) {
                    if (argExpression instanceof NamedArgumentListExpression) {
                        completeNamedParams(proposals, anchor, constructorCall, (NamedArgumentListExpression) argExpression);
                    }
                }
            }
        }
    }

    ASTNode leafParent = context.path.leafParent();
    ASTNode leafGrandparent = context.path.leafGrandParent();
    if (leafParent instanceof NamedArgumentListExpression &&
        leafGrandparent instanceof ConstructorCallExpression) {

        completeNamedParams(proposals, anchor, (ConstructorCallExpression) leafGrandparent, (NamedArgumentListExpression) leafParent);
    }

    return false;
}
 
Example 8
Source File: GroovyClassFilterTransformer.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Expression transformConstructorCall(ConstructorCallExpression exp)
{
	if (allowed(exp.getType()))
	{
		Expression originalArgs = exp.getArguments();
		Expression transformedArgs = transformArguments(originalArgs);
		Expression unwrappedArgs = unwrapTransformedArguments(transformedArgs, originalArgs);
		if (unwrappedArgs.equals(originalArgs))
		{
			if (log.isDebugEnabled())
			{
				log.debug("allowed constructor call " + exp);
			}
			return exp;
		}
		
		ConstructorCallExpression transformedCall = new ConstructorCallExpression(
				exp.getType(), unwrappedArgs);
		if (log.isDebugEnabled())
		{
			log.debug("transformed constructor call " + transformedCall);
		}
		return transformedCall;
	}
	
	return super.transformConstructorCall(exp);
}
 
Example 9
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstructorCallExpression(final ConstructorCallExpression cce) {
    if (!insideScriptBody || !cce.isUsingAnonymousInnerClass()) return;
    ConstructorCallExpression old = currentAIC;
    currentAIC = cce;
    Expression newArgs = transform(cce.getArguments());
    if (cce.getArguments() instanceof TupleExpression && newArgs instanceof TupleExpression) {
        List<Expression> argList = ((TupleExpression) cce.getArguments()).getExpressions();
        argList.clear();
        argList.addAll(((TupleExpression) newArgs).getExpressions());
    }
    currentAIC = old;
}
 
Example 10
Source File: InnerClassCompletionVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addThisReference(ConstructorNode node) {
    if (!shouldHandleImplicitThisForInnerClass(classNode)) return;

    // add "this$0" field init

    //add this parameter to node
    Parameter[] params = node.getParameters();
    Parameter[] newParams = new Parameter[params.length + 1];
    System.arraycopy(params, 0, newParams, 1, params.length);
    String name = getUniqueName(params, node);

    Parameter thisPara = new Parameter(classNode.getOuterClass().getPlainNodeReference(), name);
    newParams[0] = thisPara;
    node.setParameters(newParams);

    BlockStatement block = getCodeAsBlock(node);
    BlockStatement newCode = block();
    addFieldInit(thisPara, thisField, newCode);
    ConstructorCallExpression cce = getFirstIfSpecialConstructorCall(block);
    if (cce == null) {
        cce = ctorSuperX(new TupleExpression());
        block.getStatements().add(0, stmt(cce));
    }
    if (shouldImplicitlyPassThisPara(cce)) {
        // add thisPara to this(...)
        TupleExpression args = (TupleExpression) cce.getArguments();
        List<Expression> expressions = args.getExpressions();
        VariableExpression ve = varX(thisPara.getName());
        ve.setAccessedVariable(thisPara);
        expressions.add(0, ve);
    }
    if (cce.isSuperCall()) {
        // we have a call to super here, so we need to add
        // our code after that
        block.getStatements().add(1, newCode);
    }
    node.setCode(block);
}
 
Example 11
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void writeNormalConstructorCall(final ConstructorCallExpression call) {
    Expression arguments = call.getArguments();
    if (arguments instanceof TupleExpression) {
        TupleExpression tupleExpression = (TupleExpression) arguments;
        int size = tupleExpression.getExpressions().size();
        if (size == 0) {
            arguments = MethodCallExpression.NO_ARGUMENTS;
        }
    }

    Expression receiver = new ClassExpression(call.getType());
    controller.getCallSiteWriter().makeCallSite(receiver, CallSiteWriter.CONSTRUCTOR, arguments, false, false, false, false);
}
 
Example 12
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void genSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) {
    // Select a constructor from our class, or super-class which is legal to call,
    // then write out an invoke w/nulls using casts to avoid abigous crapo

    Parameter[] params = selectAccessibleConstructorFromSuper(node);
    if (params != null) {
        out.print("super (");

        for (int i = 0; i < params.length; i++) {
            printDefaultValue(out, params[i].getType());
            if (i + 1 < params.length) {
                out.print(", ");
            }
        }

        out.println(");");
        return;
    }

    // Otherwise try the older method based on the constructor's call expression
    Expression arguments = constrCall.getArguments();

    if (constrCall.isSuperCall()) {
        out.print("super(");
    } else {
        out.print("this(");
    }

    // Else try to render some arguments
    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments;
        List<Expression> args = argumentListExpression.getExpressions();

        for (Expression arg : args) {
            if (arg instanceof ConstantExpression) {
                ConstantExpression expression = (ConstantExpression) arg;
                Object o = expression.getValue();

                if (o instanceof String) {
                    out.print("(String)null");
                } else {
                    out.print(expression.getText());
                }
            } else {
                printDefaultValue(out, arg.getType());
            }

            if (arg != args.get(args.size() - 1)) {
                out.print(", ");
            }
        }
    }

    out.println(");");
}
 
Example 13
Source File: ConstructorCallTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
Expression transformConstructorCall(final ConstructorCallExpression expr) {
    ConstructorNode node = expr.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (node == null) return expr;
    Parameter[] params = node.getParameters();
    if ((params.length == 1 || params.length == 2) // 2 is for inner class case
            && StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(params[params.length - 1].getType(), ClassHelper.MAP_TYPE)
            && node.getCode() == StaticTypeCheckingVisitor.GENERATED_EMPTY_STATEMENT) {
        Expression arguments = expr.getArguments();
        if (arguments instanceof TupleExpression) {
            TupleExpression tupleExpression = (TupleExpression) arguments;
            List<Expression> expressions = tupleExpression.getExpressions();
            if (expressions.size() == 1 || expressions.size() == 2) { // 2 = inner class case
                Expression expression = expressions.get(expressions.size() - 1);
                if (expression instanceof MapExpression) {
                    MapExpression map = (MapExpression) expression;
                    // check that the node doesn't belong to the list of declared constructors
                    ClassNode declaringClass = node.getDeclaringClass();
                    for (ConstructorNode constructorNode : declaringClass.getDeclaredConstructors()) {
                        if (constructorNode == node) {
                            return staticCompilationTransformer.superTransform(expr);
                        }
                    }
                    // replace call to <init>(Map) or <init>(this, Map)
                    // with a call to <init>() or <init>(this) + appropriate setters
                    // for example, foo(x:1, y:2) is replaced with:
                    // { def tmp = new Foo(); tmp.x = 1; tmp.y = 2; return tmp }()
                    MapStyleConstructorCall result = new MapStyleConstructorCall(
                            staticCompilationTransformer,
                            declaringClass,
                            map,
                            expr
                    );

                    return result;
                }
            }
        }

    }
    return staticCompilationTransformer.superTransform(expr);
}
 
Example 14
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) {
    // Select a constructor from our class, or super-class which is legal to call,
    // then write out an invoke w/nulls using casts to avoid ambiguous crapo

    Parameter[] params = selectAccessibleConstructorFromSuper(node);
    if (params != null) {
        out.print("super (");

        for (int i = 0; i < params.length; i++) {
            printDefaultValue(out, params[i].getType());
            if (i + 1 < params.length) {
                out.print(", ");
            }
        }

        out.println(");");
        return;
    }

    // Otherwise try the older method based on the constructor's call expression
    Expression arguments = constrCall.getArguments();

    if (constrCall.isSuperCall()) {
        out.print("super(");
    } else {
        out.print("this(");
    }

    // Else try to render some arguments
    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments;
        List<Expression> args = argumentListExpression.getExpressions();

        for (Expression arg : args) {
            if (arg instanceof ConstantExpression) {
                ConstantExpression expression = (ConstantExpression) arg;
                Object o = expression.getValue();

                if (o instanceof String) {
                    out.print("(String)null");
                } else {
                    out.print(expression.getText());
                }
            } else {
                ClassNode type = getConstructorArgumentType(arg, node);
                printDefaultValue(out, type);
            }

            if (arg != args.get(args.size() - 1)) {
                out.print(", ");
            }
        }
    }

    out.println(");");
}