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

The following examples show how to use org.codehaus.groovy.ast.expr.ArgumentListExpression#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: 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 2
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 3
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 4
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 5
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 6
Source File: Methods.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<String> getMethodParams(MethodCallExpression methodCall) {
    final List<String> params = new ArrayList<>();
    final Expression arguments = methodCall.getArguments();

    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argumentList = ((ArgumentListExpression) arguments);
        if (argumentList.getExpressions().size() > 0) {
            for (Expression argument : argumentList.getExpressions()) {
                params.add(ElementUtils.getTypeName(argument.getType()));
            }
        }
    }
    return params;
}
 
Example 7
Source File: MethodRefactoringElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<String> getParamTypes(MethodCallExpression methodCall) {
    final Expression arguments = methodCall.getArguments();
    final List<String> paramTypes = new ArrayList<String>();

    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argumentList = ((ArgumentListExpression) arguments);
        if (argumentList.getExpressions().size() > 0) {
            for (Expression argument : argumentList.getExpressions()) {
                paramTypes.add(ElementUtils.getTypeName(argument.getType()));
            }
        }
    }
    return paramTypes;
}
 
Example 8
Source File: DependencyVisitor.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void visitArgumentlistExpression(ArgumentListExpression ale) {
	List<Expression> expressions = ale.getExpressions();

	if (expressions.size() == 1 && expressions.get(0) instanceof ConstantExpression) {
		String depStr = expressions.get(0).getText();
		String[] deps = depStr.split(":");

		if (deps.length == 3) {
			dependencies.add(deps[0] + ":" + deps[1]);
		}
	}

	super.visitArgumentlistExpression(ale);
}
 
Example 9
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 10
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 11
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 12
Source File: SignatureHelpProvider.java    From groovy-language-server with Apache License 2.0 4 votes vote down vote up
public CompletableFuture<SignatureHelp> provideSignatureHelp(TextDocumentIdentifier textDocument,
		Position position) {
	if (ast == null) {
		//this shouldn't happen, but let's avoid an exception if something
		//goes terribly wrong.
		return CompletableFuture.completedFuture(new SignatureHelp(Collections.emptyList(), -1, -1));
	}
	URI uri = URI.create(textDocument.getUri());
	ASTNode offsetNode = ast.getNodeAtLineAndColumn(uri, position.getLine(), position.getCharacter());
	if (offsetNode == null) {
		return CompletableFuture.completedFuture(new SignatureHelp(Collections.emptyList(), -1, -1));
	}
	int activeParamIndex = -1;
	MethodCall methodCall = null;
	ASTNode parentNode = ast.getParent(offsetNode);

	if (offsetNode instanceof ArgumentListExpression) {
		methodCall = (MethodCall) parentNode;

		ArgumentListExpression argsList = (ArgumentListExpression) offsetNode;
		List<Expression> expressions = argsList.getExpressions();
		activeParamIndex = getActiveParameter(position, expressions);
	}

	if (methodCall == null) {
		return CompletableFuture.completedFuture(new SignatureHelp(Collections.emptyList(), -1, -1));
	}

	List<MethodNode> methods = GroovyASTUtils.getMethodOverloadsFromCallExpression(methodCall, ast);
	if (methods.isEmpty()) {
		return CompletableFuture.completedFuture(new SignatureHelp(Collections.emptyList(), -1, -1));
	}

	List<SignatureInformation> sigInfos = new ArrayList<>();
	for (MethodNode method : methods) {
		List<ParameterInformation> parameters = new ArrayList<>();
		Parameter[] methodParams = method.getParameters();
		for (int i = 0; i < methodParams.length; i++) {
			Parameter methodParam = methodParams[i];

			ParameterInformation paramInfo = new ParameterInformation();
			paramInfo.setLabel(GroovyNodeToStringUtils.variableToString(methodParam, ast));
			parameters.add(paramInfo);
		}
		SignatureInformation sigInfo = new SignatureInformation();
		sigInfo.setLabel(GroovyNodeToStringUtils.methodToString(method, ast));
		sigInfo.setParameters(parameters);
		sigInfos.add(sigInfo);
	}

	MethodNode bestMethod = GroovyASTUtils.getMethodFromCallExpression(methodCall, ast, activeParamIndex);
	int activeSignature = methods.indexOf(bestMethod);

	return CompletableFuture.completedFuture(new SignatureHelp(sigInfos, activeSignature, activeParamIndex));
}
 
Example 13
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 14
Source File: MethodInference.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
private static ClassNode findReturnTypeFor(
        @NonNull ClassNode callerType, 
        @NonNull String methodName,
        @NonNull Expression arguments,
        @NonNull AstPath path,
        @NonNull boolean isStatic,
        @NonNull BaseDocument baseDocument,
        @NonNull int offset
        ) {

    List<ClassNode> paramTypes = new ArrayList<>();
    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argExpression = (ArgumentListExpression) arguments;
        for (Expression e : argExpression.getExpressions()) {
            if (e instanceof VariableExpression) {
                ModuleNode moduleNode = (ModuleNode) path.root();
                int newOffset = ASTUtils.getOffset(baseDocument, e.getLineNumber(), e.getColumnNumber());
                AstPath newPath = new AstPath(moduleNode, newOffset, baseDocument);
                TypeInferenceVisitor tiv = new TypeInferenceVisitor(moduleNode.getContext(), newPath, baseDocument, newOffset);
                tiv.collect();
                ClassNode guessedType = tiv.getGuessedType();
                if (null == guessedType) {
                    System.out.println("Bad guessed type");
                } else {
                    paramTypes.add(tiv.getGuessedType());
                }
            } else if(e instanceof ConstantExpression) {
                paramTypes.add(((ConstantExpression)e).getType());
            } else if (e instanceof MethodCallExpression) {
                paramTypes.add(findCallerType(e, path, baseDocument, offset));
            } else if (e instanceof BinaryExpression) {
                BinaryExpression binExpression = (BinaryExpression) e;
                paramTypes.add(binExpression.getType());
            } else if (e instanceof ClassExpression) {
                ClassExpression classExpression = (ClassExpression) e;
                // This should be Class<classExpression.getType()>
                paramTypes.add(GenericsUtils.makeClassSafeWithGenerics(Class.class, classExpression.getType()));
            } else {
                System.out.println(e.getClass());
            }
        }
    }

    MethodNode possibleMethod = tryFindPossibleMethod(callerType, methodName, paramTypes, isStatic);
    if (possibleMethod != null) {
        return possibleMethod.getReturnType();
    }
    return null;
}
 
Example 15
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(");");
}