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

The following examples show how to use org.codehaus.groovy.ast.expr.ConstructorCallExpression. 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: 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 #2
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 #3
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 #4
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitConstructorCallExpression(ConstructorCallExpression call) {
    // This might happened for constructor call with generics e.g. "new ArrayList<String>()"
    // In that case we want to highligt only in situation where the caret
    // is on "String" type, but not if the caret location is on ArrayList
     if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
         ClassNode findingNode = (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset);
         final String callName = ElementUtils.getNameWithoutPackage(call);
         final String findingNodeName = ElementUtils.getNameWithoutPackage(findingNode);
         if (!callName.equals(findingNodeName)) {
            addOccurrences(call.getType(), findingNode);
         }
    } else {
        if (leaf instanceof ConstructorNode) {
            ConstructorNode constructor = (ConstructorNode) leaf;
            if (Methods.isSameConstructor(constructor, call)) {
                occurrences.add(call);
            }
        } else if (leaf instanceof ConstructorCallExpression) {
            if (Methods.isSameConstuctor(call, (ConstructorCallExpression) leaf)) {
                occurrences.add(call);
            }
        }
    }
    super.visitConstructorCallExpression(call);
}
 
Example #5
Source File: ConstructorNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Return the first statement from the constructor code if it is a call to super or this, otherwise null.
 *
 * @param code
 * @return the first statement if a special call or null
 */
public static ConstructorCallExpression getFirstIfSpecialConstructorCall(Statement code) {
    if (code == null) return null;

    if (code instanceof BlockStatement) {
        final BlockStatement block = (BlockStatement) code;
        final List<Statement> statementList = block.getStatements();
        if (statementList.isEmpty()) return null;
        // handle blocks of blocks
        return getFirstIfSpecialConstructorCall(statementList.get(0));
    }

    if (!(code instanceof ExpressionStatement)) return null;

    Expression expression = ((ExpressionStatement) code).getExpression();
    if (!(expression instanceof ConstructorCallExpression)) return null;
    ConstructorCallExpression cce = (ConstructorCallExpression) expression;
    if (cce.isSpecialCall()) return cce;
    return null;
}
 
Example #6
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 #7
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassNode deriveExpressonType(Expression expression) {
    ClassNode derivedExpressionType = null;
    if (expression instanceof ConstantExpression
            && !expression.getText().equals("null")) { // NOI18N
        derivedExpressionType = ((ConstantExpression) expression).getType();
    } else if (expression instanceof ConstructorCallExpression) {
        derivedExpressionType = ((ConstructorCallExpression) expression).getType();
    } else if (expression instanceof MethodCallExpression) {
        int newOffset = ASTUtils.getOffset(doc, expression.getLineNumber(), expression.getColumnNumber());
        AstPath newPath = new AstPath(path.root(), newOffset, doc);
        derivedExpressionType = MethodInference.findCallerType(expression, newPath, doc, newOffset);
    } else if (expression instanceof StaticMethodCallExpression) {
        derivedExpressionType = MethodInference.findCallerType(expression, path, doc, cursorOffset);
    } else if (expression instanceof ListExpression) {
        derivedExpressionType = ((ListExpression) expression).getType();
    } else if (expression instanceof MapExpression) {
        derivedExpressionType = ((MapExpression) expression).getType();
    } else if (expression instanceof RangeExpression) {
        // this should work, but the type is Object - nut sure why
        // guessedType = ((RangeExpression)initialExpression).getType();
        derivedExpressionType = ClassHelper.makeWithoutCaching(Range.class, true);                
    } 
    return derivedExpressionType;
}
 
Example #8
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    if (!leafReached) {
        // have a look at assignment and try to get type from its right side
        Expression leftExpression = expression.getLeftExpression();
        if (leftExpression instanceof VariableExpression) {
            if (expression.getOperation().isA(Types.EQUAL) && sameVariableName(leaf, leftExpression)) {
                Expression rightExpression = expression.getRightExpression();
                if (rightExpression instanceof ConstantExpression
                        && !rightExpression.getText().equals("null")) { // NOI18N
                    guessedType = ((ConstantExpression) rightExpression).getType();
                } else if (rightExpression instanceof ConstructorCallExpression) {
                    guessedType = ClassHelper.make(((ConstructorCallExpression) rightExpression).getType().getName());
                } else if (rightExpression instanceof MethodCallExpression) {
                    guessedType = MethodInference.findCallerType(rightExpression, path, doc, cursorOffset);
                } else if (rightExpression instanceof StaticMethodCallExpression) {
                    guessedType = MethodInference.findCallerType(rightExpression, path, doc, cursorOffset);
                }
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example #9
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void visitField(FieldNode node) {
    if (sameVariableName(leaf, node)) {
        if (node.hasInitialExpression()){
            Expression expression = node.getInitialExpression();
            if (expression instanceof ConstantExpression
                    && !expression.getText().equals("null")) { // NOI18N
                guessedType = ((ConstantExpression) expression).getType();
            } else if (expression instanceof ConstructorCallExpression) {
                guessedType = ((ConstructorCallExpression) expression).getType();
            } else if (expression instanceof MethodCallExpression) {
                int newOffset = ASTUtils.getOffset(doc, expression.getLineNumber(), expression.getColumnNumber());
                AstPath newPath = new AstPath(path.root(), newOffset, doc);
                guessedType = MethodInference.findCallerType(expression, newPath, doc, newOffset);
            }
        }
    }
}
 
Example #10
Source File: InnerClassCompletionVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean shouldImplicitlyPassThisPara(ConstructorCallExpression cce) {
    boolean pass = false;
    ClassNode superCN = classNode.getSuperClass();
    if (cce.isThisCall()) {
        pass = true;
    } else if (cce.isSuperCall()) {
        // if the super class is another non-static inner class in the same outer class hierarchy, implicit this
        // needs to be passed
        if (!superCN.isEnum() && !superCN.isInterface() && superCN instanceof InnerClassNode) {
            InnerClassNode superInnerCN = (InnerClassNode) superCN;
            if (!isStatic(superInnerCN) && classNode.getOuterClass().isDerivedFrom(superCN.getOuterClass())) {
                pass = true;
            }
        }
    }
    return pass;
}
 
Example #11
Source File: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected BlockStatement createBlockStatementForConstructor(final ClosureExpression expression, final ClassNode outerClass, final ClassNode thisClassNode) {
    BlockStatement block = new BlockStatement();
    // this block does not get a source position, because we don't
    // want this synthetic constructor to show up in corbertura reports
    VariableExpression outer = new VariableExpression(OUTER_INSTANCE, outerClass);
    outer.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(outer);
    VariableExpression thisObject = new VariableExpression(THIS_OBJECT, thisClassNode);
    thisObject.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(thisObject);
    TupleExpression conArgs = new TupleExpression(outer, thisObject);
    block.addStatement(
            new ExpressionStatement(
                    new ConstructorCallExpression(
                            ClassNode.SUPER,
                            conArgs)));
    return block;
}
 
Example #12
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustMethod(MethodNode mn, boolean includeGenerated) {
    BlockStatement newCode = getCodeAsBlock(mn);
    if (mn.getParameters().length == 0) return;
    boolean generated = isGenerated(mn);
    int startingIndex = 0;
    if (!includeGenerated && generated) return;
    if (isMarkedAsProcessed(mn)) return;
    if (mn instanceof ConstructorNode) {
        // some transform has been here already and we assume it knows what it is doing
        if (mn.getFirstStatement() instanceof BytecodeSequence) return;
        // ignore any constructors calling this(...) or super(...)
        ConstructorCallExpression cce = ConstructorNodeUtils.getFirstIfSpecialConstructorCall(mn.getCode());
        if (cce != null) {
            if (generated) {
                return;
            } else {
                startingIndex = 1; // skip over this/super() call
            }
        }
    }
    for (Parameter p : mn.getParameters()) {
        if (ClassHelper.isPrimitiveType(p.getType())) continue;
        newCode.getStatements().add(startingIndex, ifS(isNullX(varX(p)), makeThrowStmt(p.getName())));
    }
    mn.setCode(newCode);
}
 
Example #13
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 #14
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void printConstructor(PrintWriter out, ClassNode clazz, ConstructorNode constructorNode) {
    printAnnotations(out, constructorNode);
    // printModifiers(out, constructorNode.getModifiers());

    out.print("public "); // temporary hack
    String className = clazz.getNameWithoutPackage();
    if (clazz instanceof InnerClassNode)
        className = className.substring(className.lastIndexOf('$') + 1);
    out.println(className);

    printParams(out, constructorNode);

    ClassNode[] exceptions = constructorNode.getExceptions();
    printExceptions(out, exceptions);

    ConstructorCallExpression constrCall = getFirstIfSpecialConstructorCall(constructorNode.getCode());
    if (constrCall == null) {
        out.println(" {}");
    } else {
        out.println(" {");
        printSpecialConstructorArgs(out, constructorNode, constrCall);
        out.println("}");
    }
}
 
Example #15
Source File: GroovyASTUtils.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
public static List<MethodNode> getMethodOverloadsFromCallExpression(MethodCall node, ASTNodeVisitor astVisitor) {
    if (node instanceof MethodCallExpression) {
        MethodCallExpression methodCallExpr = (MethodCallExpression) node;
        ClassNode leftType = getTypeOfNode(methodCallExpr.getObjectExpression(), astVisitor);
        if (leftType != null) {
            return leftType.getMethods(methodCallExpr.getMethod().getText());
        }
    } else if (node instanceof ConstructorCallExpression) {
        ConstructorCallExpression constructorCallExpr = (ConstructorCallExpression) node;
        ClassNode constructorType = constructorCallExpr.getType();
        if (constructorType != null) {
            return constructorType.getDeclaredConstructors().stream().map(constructor -> (MethodNode) constructor)
                    .collect(Collectors.toList());
        }
    }
    return Collections.emptyList();
}
 
Example #16
Source File: FindMethodUsagesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMethodCallExpression(MethodCallExpression methodCall) {
    Expression expression = methodCall.getObjectExpression();

    if (expression instanceof VariableExpression) {
        VariableExpression variableExpression = ((VariableExpression) expression);
        Variable variable = variableExpression.getAccessedVariable();

        if (variable != null) {
            if (variable.isDynamicTyped()) {
                addDynamicVarUsages(methodCall, variable);
            } else {
                addStaticVarUsages(methodCall, variable);
            }
        } else {
            addThisUsages(methodCall);
        }

    } else if (expression instanceof ConstructorCallExpression) {
        addConstructorUsages(methodCall, (ConstructorCallExpression) expression);
    }
    super.visitMethodCallExpression(methodCall);
}
 
Example #17
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 #18
Source File: GeneralUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean copyStatementsWithSuperAdjustment(final ClosureExpression pre, final BlockStatement body) {
    Statement preCode = pre.getCode();
    boolean changed = false;
    if (preCode instanceof BlockStatement) {
        BlockStatement block = (BlockStatement) preCode;
        List<Statement> statements = block.getStatements();
        for (int i = 0, n = statements.size(); i < n; i += 1) {
            Statement statement = statements.get(i);
            // adjust the first statement if it's a super call
            if (i == 0 && statement instanceof ExpressionStatement) {
                ExpressionStatement es = (ExpressionStatement) statement;
                Expression preExp = es.getExpression();
                if (preExp instanceof MethodCallExpression) {
                    MethodCallExpression mce = (MethodCallExpression) preExp;
                    String name = mce.getMethodAsString();
                    if ("super".equals(name)) {
                        es.setExpression(new ConstructorCallExpression(ClassNode.SUPER, mce.getArguments()));
                        changed = true;
                    }
                }
            }
            body.addStatement(statement);
        }
    }
    return changed;
}
 
Example #19
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ConstructorCallExpression getConstructorCallExpression(
        ConstructorNode constructorNode) {
    Statement code = constructorNode.getCode();
    if (!(code instanceof BlockStatement)) {
        return null;
    }
    BlockStatement block = (BlockStatement) code;
    List<Statement> stats = block.getStatements();
    if (stats == null || stats.isEmpty()) {
        return null;
    }
    Statement stat = stats.get(0);
    if (!(stat instanceof ExpressionStatement)) {
        return null;
    }
    Expression expr = ((ExpressionStatement) stat).getExpression();
    if (!(expr instanceof ConstructorCallExpression)) {
        return null;
    }
    return (ConstructorCallExpression) expr;
}
 
Example #20
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void genConstructor(ClassNode clazz, ConstructorNode constructorNode, PrintWriter out) {
    // <netbeans>
    if (constructorNode.isSynthetic()) {
        return;
    }
    // </netbeans>
    // printModifiers(out, constructorNode.getModifiers());

    out.print("public "); // temporary hack

    out.print(clazz.getNameWithoutPackage());

    printParams(constructorNode, out);

    ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode);
    if (constrCall == null || !constrCall.isSpecialCall()) {
        out.println(" {}");
    } else {
        out.println(" {");

        genSpecialConstructorArgs(out, constructorNode, constrCall);

        out.println("}");
    }
}
 
Example #21
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 #22
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitSpecialConstructorCall(final ConstructorCallExpression call) {
    if (controller.getClosureWriter().addGeneratedClosureConstructorCall(call)) return;
    ClassNode callNode = controller.getClassNode();
    if (call.isSuperCall()) callNode = callNode.getSuperClass();
    List<ConstructorNode> constructors = sortConstructors(call, callNode);
    if (!makeDirectConstructorCall(constructors, call, callNode)) {
        makeMOPBasedConstructorCall(constructors, call, callNode);
    }
}
 
Example #23
Source File: MacroClassTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstructorCallExpression(final ConstructorCallExpression call) {
    ClassNode type = call.getType();
    if (type instanceof InnerClassNode) {
        if (((InnerClassNode) type).isAnonymous() &&
                MACROCLASS_TYPE.getNameWithoutPackage().equals(type.getSuperClass().getNameWithoutPackage())) {
            try {
                String source = convertInnerClassToSource(type);

                MethodCallExpression macroCall = callX(
                        propX(classX(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"),
                        MACRO_METHOD,
                        args(
                                constX(source),
                                MacroGroovyMethods.buildSubstitutions(sourceUnit, type),
                                classX(ClassHelper.make(ClassNode.class))
                        )
                );

                macroCall.setSpreadSafe(false);
                macroCall.setSafe(false);
                macroCall.setImplicitThis(false);
                call.putNodeMetaData(MacroTransformation.class, macroCall);
                List<ClassNode> classes = sourceUnit.getAST().getClasses();
                for (Iterator<ClassNode> iterator = classes.iterator(); iterator.hasNext(); ) {
                    final ClassNode aClass = iterator.next();
                    if (aClass == type || type == aClass.getOuterClass()) {
                        iterator.remove();
                    }
                }
            } catch (Exception e) {
                // FIXME
                e.printStackTrace();
            }
            return;
        }
    }
    super.visitConstructorCallExpression(call);

}
 
Example #24
Source File: MacroClassTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transform(final Expression exp) {
    if (exp instanceof ConstructorCallExpression) {
        MethodCallExpression call = exp.getNodeMetaData(MacroTransformation.class);
        if (call != null) {
            return call;
        }
    }
    return super.transform(exp);
}
 
Example #25
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 #26
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 #27
Source File: ConstructorCallTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transformExpression(final ExpressionTransformer transformer) {
    Expression result = new MapStyleConstructorCall(
            staticCompilationTransformer, declaringClass,
            (MapExpression) map.transformExpression(transformer),
            (ConstructorCallExpression) originalCall.transformExpression(transformer)
    );
    result.copyNodeMetaData(this);
    result.setSourcePosition(this);
    return result;
}
 
Example #28
Source File: StaticCompilationTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transform(Expression expr) {
    if (expr instanceof StaticMethodCallExpression) {
        return staticMethodCallExpressionTransformer.transformStaticMethodCallExpression((StaticMethodCallExpression) expr);
    }
    if (expr instanceof BinaryExpression) {
        return binaryExpressionTransformer.transformBinaryExpression((BinaryExpression)expr);
    }
    if (expr instanceof MethodCallExpression) {
        return methodCallExpressionTransformer.transformMethodCallExpression((MethodCallExpression) expr);
    }
    if (expr instanceof ClosureExpression) {
        return closureExpressionTransformer.transformClosureExpression((ClosureExpression) expr);
    }
    if (expr instanceof ConstructorCallExpression) {
        return constructorCallTransformer.transformConstructorCall((ConstructorCallExpression) expr);
    }
    if (expr instanceof BooleanExpression) {
        return booleanExpressionTransformer.transformBooleanExpression((BooleanExpression)expr);
    }
    if (expr instanceof VariableExpression) {
        return variableExpressionTransformer.transformVariableExpression((VariableExpression)expr);
    }
    if (expr instanceof RangeExpression) {
        return rangeExpressionTransformer.transformRangeExpression(((RangeExpression)expr));
    }
    if (expr instanceof ListExpression) {
        return listExpressionTransformer.transformListExpression((ListExpression) expr);
    }
    if (expr instanceof CastExpression) {
        return castExpressionTransformer.transformCastExpression(((CastExpression)expr));
    }
    return super.transform(expr);
}
 
Example #29
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);
}
 
Example #30
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);
    }
}