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

The following examples show how to use org.codehaus.groovy.ast.expr.MapExpression. 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
private void addDependencyFromMapExpression(final MapExpression mapExpression) {
    final List<MapEntryExpression> mapEntryExpressions = mapExpression.getMapEntryExpressions();

    String group = null;
    String name = null;
    String version = null;
    for (final MapEntryExpression mapEntryExpression : mapEntryExpressions) {
        final String key = mapEntryExpression.getKeyExpression().getText();
        final String value = mapEntryExpression.getValueExpression().getText();
        if ("group".equals(key)) {
            group = value;
        } else if ("name".equals(key)) {
            name = value;
        } else if ("version".equals(key)) {
            version = value;
        }
    }

    addDependency(group, name, version);
}
 
Example #2
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 #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: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addGrabResolverAsStaticInitIfNeeded(ClassNode grapeClassNode, AnnotationNode node,
                                                  List<Statement> grabResolverInitializers, Map<String, Object> grabResolverMap) {
    if ((node.getMember("initClass") == null)
        || (node.getMember("initClass") == ConstantExpression.TRUE))
    {
        MapExpression resolverArgs = new MapExpression();
        for (Map.Entry<String, Object> next : grabResolverMap.entrySet()) {
            resolverArgs.addMapEntryExpression(constX(next.getKey()), constX(next.getValue()));
        }
        grabResolverInitializers.add(stmt(callX(grapeClassNode, "addResolver", args(resolverArgs))));
    }
}
 
Example #5
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitMapExpression(MapExpression node) {
	pushASTNode(node);
	try {
		super.visitMapExpression(node);
	} finally {
		popASTNode();
	}
}
 
Example #6
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateProperties(AbstractASTTransformation xform, BlockStatement body, ClassNode cNode, List<PropertyNode> props) {
    if (xform instanceof MapConstructorASTTransformation) {
        body.addStatement(ifS(equalsNullX(varX("args")), assignS(varX("args"), new MapExpression())));
        body.addStatement(stmt(callX(SELF_TYPE, "checkPropNames", args("this", "args"))));
    }
    return super.validateProperties(xform, body, cNode, props);
}
 
Example #7
Source File: DefaultPropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateProperties(AbstractASTTransformation xform, BlockStatement body, ClassNode cNode, List<PropertyNode> props) {
    if (xform instanceof MapConstructorASTTransformation) {
        body.addStatement(ifS(equalsNullX(varX("args")), assignS(varX("args"), new MapExpression())));
        body.addStatement(stmt(callX(IMMUTABLE_XFORM_TYPE, "checkPropNames", args("this", "args"))));
    }
    return super.validateProperties(xform, body, cNode, props);
}
 
Example #8
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression expression) {
    MethodVisitor mv = controller.getMethodVisitor();

    List<MapEntryExpression> entries = expression.getMapEntryExpressions();
    int size = entries.size();
    BytecodeHelper.pushConstant(mv, size * 2);

    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");

    int i = 0;
    for (Object object : entries) {
        MapEntryExpression entry = (MapEntryExpression) object;

        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i++);
        entry.getKeyExpression().visit(this);
        controller.getOperandStack().box();
        mv.visitInsn(AASTORE);

        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i++);
        entry.getValueExpression().visit(this);
        controller.getOperandStack().box();
        mv.visitInsn(AASTORE);

        controller.getOperandStack().remove(2);
    }
    createMapMethod.call(mv);
    controller.getOperandStack().push(ClassHelper.MAP_TYPE);
}
 
Example #9
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 #10
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression serialize(AnnotationNode an) {
    ClassExpression type = new ClassExpression(an.getClassNode());
    type.setSourcePosition(an.getClassNode());

    MapExpression map = new MapExpression();
    for (Map.Entry<String, Expression> entry : an.getMembers().entrySet()) {
        Expression key = new ConstantExpression(entry.getKey());
        Expression val = serialize(entry.getValue());
        map.addMapEntryExpression(key, val);
    }

    return new ArrayExpression(ClassHelper.OBJECT_TYPE, Arrays.asList(type, map));
}
 
Example #11
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression tryTransformInclude(final MethodCallExpression exp) {
    Expression arguments = exp.getArguments();
    if (arguments instanceof TupleExpression) {
        List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
        if (expressions.size() == 1 && expressions.get(0) instanceof MapExpression) {
            MapExpression map = (MapExpression) expressions.get(0);
            List<MapEntryExpression> entries = map.getMapEntryExpressions();
            if (entries.size() == 1) {
                MapEntryExpression mapEntry = entries.get(0);
                Expression keyExpression = mapEntry.getKeyExpression();
                try {
                    IncludeType includeType = IncludeType.valueOf(keyExpression.getText().toLowerCase());
                    MethodCallExpression call = new MethodCallExpression(
                            exp.getObjectExpression(),
                            includeType.getMethodName(),
                            new ArgumentListExpression(
                                    mapEntry.getValueExpression()
                            )
                    );
                    call.setImplicitThis(true);
                    call.setSafe(exp.isSafe());
                    call.setSpreadSafe(exp.isSpreadSafe());
                    call.setSourcePosition(exp);
                    return call;
                } catch (IllegalArgumentException e) {
                    // not a valid import type, do not modify the code
                }
            }

        }
    }
    return super.transform(exp);
}
 
Example #12
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression expression) {
        if (expression.isSuperExpression()) {
            guessedType = expression.getType().getSuperClass();
        }
        if (null != expression.getAccessedVariable()) {
            Variable accessedVariable = expression.getAccessedVariable();

            if (accessedVariable.hasInitialExpression()) {
                Expression initialExpression = expression.getAccessedVariable().getInitialExpression();
                if (initialExpression instanceof ConstantExpression
                        && !initialExpression.getText().equals("null")) { // NOI18N
                    guessedType = ((ConstantExpression) initialExpression).getType();
                } else if (initialExpression instanceof ConstructorCallExpression) {
                    guessedType = ClassHelper.make(((ConstructorCallExpression) initialExpression).getType().getName());
                } else if (initialExpression instanceof MethodCallExpression) {
                    int newOffset = ASTUtils.getOffset(doc, initialExpression.getLineNumber(), initialExpression.getColumnNumber());
                    AstPath newPath = new AstPath(path.root(), newOffset, doc);
                    guessedType = MethodInference.findCallerType(initialExpression, newPath, doc, newOffset);
                } else if (initialExpression instanceof ListExpression) {
                    guessedType = ((ListExpression) initialExpression).getType();
                } else if (initialExpression instanceof MapExpression) {
                    guessedType = ((MapExpression) initialExpression).getType();
                } else if (initialExpression instanceof RangeExpression) {
                    // this should work, but the type is Object - nut sure why
                    // guessedType = ((RangeExpression)initialExpression).getType();
                    guessedType = ClassHelper.makeWithoutCaching(Range.class, true);                
                }
            } else if (accessedVariable instanceof Parameter) {
                Parameter param = (Parameter) accessedVariable;
                guessedType = param.getType();
            }
        } else if (!expression.getType().getName().equals("java.lang.Object")) {
            guessedType = expression.getType();

        }
    super.visitVariableExpression(expression);
}
 
Example #13
Source File: MapConstructorASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createNoArgConstructor(ClassNode cNode, int modifiers) {
    Statement body = stmt(ctorX(ClassNode.THIS, args(new MapExpression())));
    ConstructorNode consNode = new ConstructorNode(modifiers, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body);
    markAsGenerated(cNode, consNode);
    cNode.addConstructor(consNode);
}
 
Example #14
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression expression) {
    assertExpressionAuthorized(expression);
    visitListOfExpressions(expression.getMapEntryExpressions());
}
 
Example #15
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static boolean isGroovyConstructorCompatible(final Expression rightExpression) {
    return rightExpression instanceof ListExpression
            || rightExpression instanceof MapExpression
            || rightExpression instanceof ArrayExpression;
}
 
Example #16
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 #17
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 #18
Source File: ContextualClassCodeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression expression) {
    pushContext(expression);
    super.visitMapExpression(expression);
    popContext();
}
 
Example #19
Source File: TransformingCodeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression expression) {
    super.visitMapExpression(expression);
    trn.visitMapExpression(expression);
}
 
Example #20
Source File: CodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(MapExpression expression) {
    visitListOfExpressions(expression.getMapEntryExpressions());
}
 
Example #21
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static MapExpression mapX(final List<MapEntryExpression> expressions) {
    return new MapExpression(expressions);
}
 
Example #22
Source File: ASTFinder.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression expression) {
    super.visitMapExpression(expression);
    tryFind(MapExpression.class, expression);
}
 
Example #23
Source File: PathFinderVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void visitMapExpression(MapExpression node) {
    if (isInside(node, line, column)) {
        super.visitMapExpression(node);
    }
}
 
Example #24
Source File: GroovyCodeVisitor.java    From groovy with Apache License 2.0 votes vote down vote up
void visitMapExpression(MapExpression expression);