Java Code Examples for org.codehaus.groovy.ast.expr.TupleExpression#getExpressions()

The following examples show how to use org.codehaus.groovy.ast.expr.TupleExpression#getExpressions() . 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: 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 2
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static TupleExpression getMacroArguments(SourceUnit source, MethodCallExpression call) {
    Expression macroCallArguments = call.getArguments();
    if (macroCallArguments == null) {
        source.addError(new SyntaxException("Call should have arguments" + '\n', call));
        return null;
    }

    if (!(macroCallArguments instanceof TupleExpression)) {
        source.addError(new SyntaxException("Call should have TupleExpression as arguments" + '\n', macroCallArguments));
        return null;
    }

    TupleExpression tupleArguments = (TupleExpression) macroCallArguments;

    if (tupleArguments.getExpressions() == null) {
        source.addError(new SyntaxException("Call arguments should have expressions" + '\n', tupleArguments));
        return null;
    }

    return tupleArguments;
}
 
Example 3
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean containsSpreadExpression(final Expression arguments) {
    List<Expression> args;
    if (arguments instanceof TupleExpression) {
        TupleExpression tupleExpression = (TupleExpression) arguments;
        args = tupleExpression.getExpressions();
    } else if (arguments instanceof ListExpression) {
        ListExpression le = (ListExpression) arguments;
        args = le.getExpressions();
    } else {
        return arguments instanceof SpreadExpression;
    }
    for (Expression arg : args) {
        if (arg instanceof SpreadExpression) return true;
    }
    return false;
}
 
Example 4
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void checkFinalFieldAccess(final Expression expression) {
    BiConsumer<VariableExpression, ASTNode> checkForFinal = (expr, node) -> {
        Variable variable = expr.getAccessedVariable();
        if (variable != null) {
            if (isFinal(variable.getModifiers()) && variable instanceof Parameter) {
                addError("Cannot assign a value to final variable '" + variable.getName() + "'", node);
            }
            // TODO: handle local variables
        }
    };

    if (expression instanceof VariableExpression) {
        checkForFinal.accept((VariableExpression) expression, expression);
    } else if (expression instanceof TupleExpression) {
        TupleExpression tuple = (TupleExpression) expression;
        for (Expression tupleExpression : tuple.getExpressions()) {
            checkForFinal.accept((VariableExpression) tupleExpression, expression);
        }
    }
    // currently not looking for PropertyExpression: dealt with at runtime using ReadOnlyPropertyException
}
 
Example 5
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visitMethodCallExpression(MethodCallExpression mce) {
    super.visitMethodCallExpression(mce);
    Expression aexp = mce.getArguments();
    if (aexp instanceof TupleExpression) {
        TupleExpression arguments = (TupleExpression) aexp;
        for (Expression e : arguments.getExpressions()) {
            checkForInvalidDeclaration(e);
        }
    } else {
        checkForInvalidDeclaration(aexp);
    }
}
 
Example 6
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void recordAssignments(BinaryExpression expression, boolean isDeclaration, Expression leftExpression, Expression rightExpression) {
    if (leftExpression instanceof Variable) {
        boolean uninitialized = isDeclaration && rightExpression instanceof EmptyExpression;
        recordAssignment((Variable) leftExpression, isDeclaration, uninitialized, false, expression);
    } else if (leftExpression instanceof TupleExpression) {
        TupleExpression te = (TupleExpression) leftExpression;
        for (Expression next : te.getExpressions()) {
            if (next instanceof Variable) {
                recordAssignment((Variable) next, isDeclaration, false, false, next);
            }
        }
    }
}
 
Example 7
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void recordFinalVars(Expression leftExpression) {
    if (leftExpression instanceof VariableExpression) {
        VariableExpression var = (VariableExpression) leftExpression;
        if (Modifier.isFinal(var.getModifiers())) {
            declaredFinalVariables.add(var);
        }
    } else if (leftExpression instanceof TupleExpression) {
        TupleExpression te = (TupleExpression) leftExpression;
        for (Expression next : te.getExpressions()) {
            if (next instanceof Variable) {
                declaredFinalVariables.add((Variable) next);
            }
        }
    }
}
 
Example 8
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitDeclarationExpression(final DeclarationExpression expression) {
    visitAnnotations(expression);
    // visit right side first to prevent the use of a variable before its declaration
    expression.getRightExpression().visit(this);

    if (expression.isMultipleAssignmentDeclaration()) {
        TupleExpression list = expression.getTupleExpression();
        for (Expression listExpression : list.getExpressions()) {
            declare((VariableExpression) listExpression);
        }
    } else {
        declare(expression.getVariableExpression());
    }
}
 
Example 9
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 10
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the given method has a possibly matching static method with the given name and arguments.
 * Handles default arguments and optionally spread expressions.
 *
 * @param cNode     the ClassNode of interest
 * @param name      the name of the method of interest
 * @param arguments the arguments to match against
 * @param trySpread whether to try to account for SpreadExpressions within the arguments
 * @return true if a matching method was found
 */
public static boolean hasPossibleStaticMethod(ClassNode cNode, String name, Expression arguments, boolean trySpread) {
    int count = 0;
    boolean foundSpread = false;

    if (arguments instanceof TupleExpression) {
        TupleExpression tuple = (TupleExpression) arguments;
        for (Expression arg : tuple.getExpressions()) {
            if (arg instanceof SpreadExpression) {
                foundSpread = true;
            } else {
                count++;
            }
        }
    } else if (arguments instanceof MapExpression) {
        count = 1;
    }

    for (MethodNode method : cNode.getMethods(name)) {
        if (method.isStatic()) {
            Parameter[] parameters = method.getParameters();
            // do fuzzy match for spread case: count will be number of non-spread args
            if (trySpread && foundSpread && parameters.length >= count) return true;

            if (parameters.length == count) return true;

            // handle varargs case
            if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) {
                if (count >= parameters.length - 1) return true;
                // fuzzy match any spread to a varargs
                if (trySpread && foundSpread) return true;
            }

            // handle parameters with default values
            int nonDefaultParameters = 0;
            for (Parameter parameter : parameters) {
                if (!parameter.hasInitialExpression()) {
                    nonDefaultParameters++;
                }
            }

            if (count < parameters.length && nonDefaultParameters <= count) {
                return true;
            }
            // TODO handle spread with nonDefaultParams?
        }
    }
    return false;
}
 
Example 11
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 12
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to make a direct method call on a bridge method, if it exists.
 */
protected boolean tryBridgeMethod(final MethodNode target, final Expression receiver, final boolean implicitThis, final TupleExpression args, final ClassNode thisClass) {
    ClassNode lookupClassNode;
    if (target.isProtected()) {
        lookupClassNode = controller.getClassNode();
        while (lookupClassNode != null && !lookupClassNode.isDerivedFrom(target.getDeclaringClass())) {
            lookupClassNode = lookupClassNode.getOuterClass();
        }
        if (lookupClassNode == null) {
            return false;
        }
    } else {
        lookupClassNode = target.getDeclaringClass().redirect();
    }
    Map<MethodNode, MethodNode> bridges = lookupClassNode.getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_BRIDGE_METHODS);
    MethodNode bridge = bridges == null ? null : bridges.get(target);
    if (bridge != null) {
        Expression fixedReceiver = receiver;
        if (implicitThis) {
            if (!controller.isInGeneratedFunction()) {
                fixedReceiver = propX(classX(lookupClassNode), "this");
            } else if (thisClass != null) {
                ClassNode current = thisClass.getOuterClass();
                fixedReceiver = varX("thisObject", current);
                // adjust for multiple levels of nesting if needed
                while (current.getOuterClass() != null && !lookupClassNode.equals(current)) {
                    FieldNode thisField = current.getField("this$0");
                    current = current.getOuterClass();
                    if (thisField != null) {
                        fixedReceiver = propX(fixedReceiver, "this$0");
                        fixedReceiver.setType(current);
                    }
                }
            }
        }
        ArgumentListExpression newArgs = args(target.isStatic() ? nullX() : fixedReceiver);
        for (Expression expression : args.getExpressions()) {
            newArgs.addExpression(expression);
        }
        return writeDirectMethodCall(bridge, implicitThis, fixedReceiver, newArgs);
    }
    return false;
}