Java Code Examples for org.codehaus.groovy.ast.expr.PropertyExpression#getObjectExpression()

The following examples show how to use org.codehaus.groovy.ast.expr.PropertyExpression#getObjectExpression() . 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: FindVariableUsages.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitPropertyExpression(PropertyExpression expression) {
    final Expression objectExpression = expression.getObjectExpression();
    if (objectExpression == null) {
        return;
    }

    final String varName = expression.getPropertyAsString();
    if (objectExpression instanceof VariableExpression) {
        final VariableExpression varExpression = ((VariableExpression) objectExpression);

        final String varType;
        if ("this".equals(varExpression.getName())) { // NOI18N
            String fileName = getSourceUnit().getName();            // returns file name (e.g. Tester.groovy)
            varType = fileName.substring(0, fileName.indexOf(".")); // remove the .groovy suffix
        } else {
            varType = varExpression.getType().getName();
        }
        addIfEqual(expression.getProperty(), varType, varName);
    } else {
        // No need to check for "this" here
        addIfEqual(expression.getProperty(), objectExpression.getType().getName(), varName);
    }
    super.visitPropertyExpression(expression);
}
 
Example 2
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static groovy.transform.PackageScopeTarget extractTarget(PropertyExpression expr) {
    Expression oe = expr.getObjectExpression();
    if (oe instanceof ClassExpression) {
        ClassExpression ce = (ClassExpression) oe;
        if (ce.getType().getName().equals("groovy.transform.PackageScopeTarget")) {
            Expression prop = expr.getProperty();
            if (prop instanceof ConstantExpression) {
                String propName = (String) ((ConstantExpression) prop).getValue();
                try {
                    return PackageScopeTarget.valueOf(propName);
                } catch(IllegalArgumentException iae) {
                    /* ignore */
                }
            }
        }
    }
    throw new GroovyBugError("Internal error during " + MY_TYPE_NAME
            + " processing. Annotation parameters must be of type: " + TARGET_CLASS_NAME + ".");
}
 
Example 3
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean validateEnumConstant(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        String name = pe.getPropertyAsString();
        if (pe.getObjectExpression() instanceof ClassExpression && name != null) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            if (type.isEnum()) {
                boolean ok = false;
                try {
                    FieldNode enumField = type.getDeclaredField(name);
                    ok = enumField != null && enumField.getType().equals(type);
                } catch(Exception ex) {
                    // ignore
                }
                if(!ok) {
                    addError("No enum const " + type.getName() + "." + name, pe);
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example 4
Source File: ExpressionUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * The attribute values of annotations must be primitive, String or Enum constants.
 * In various places, such constants can be seen during type resolution but won't be
 * readily accessible in later phases, e.g. they might be embedded into constructor code.
 * This method transforms constants that would appear in annotations early so they aren't lost.
 * Subsequent processing determines whether they are valid, this method simply retains
 * the constant value as a constant expression.
 *
 * @param exp the original expression
 * @return the converted expression
 */
public static Expression transformInlineConstants(final Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        if (pe.getObjectExpression() instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            FieldNode field = ClassNodeUtils.getField(type, pe.getPropertyAsString());
            if (type.isEnum() && field != null && field.isEnum()) return exp;
            Expression constant = findConstant(field);
            if (constant != null) return constant;
        }
    } else if (exp instanceof BinaryExpression) {
        BinaryExpression be = (BinaryExpression) exp;
        be.setLeftExpression(transformInlineConstants(be.getLeftExpression()));
        be.setRightExpression(transformInlineConstants(be.getRightExpression()));
        return be;
    } else if (exp instanceof ListExpression) {
        ListExpression origList = (ListExpression) exp;
        ListExpression newList = new ListExpression();
        boolean changed = false;
        for (Expression e : origList.getExpressions()) {
            Expression transformed = transformInlineConstants(e);
            newList.addExpression(transformed);
            if (transformed != e) changed = true;
        }
        if (changed) {
            newList.setSourcePosition(origList);
            return newList;
        }
        return origList;
    }

    return exp;
}
 
Example 5
Source File: VisibilityUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Visibility getVisibility(Expression e) {
    if (e instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) e;
        if (pe.getObjectExpression() instanceof ClassExpression && pe.getObjectExpression().getText().equals("groovy.transform.options.Visibility")) {
            return Visibility.valueOf(pe.getPropertyAsString());
        }
    }
    return Visibility.UNDEFINED;
}
 
Example 6
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Expression transformPropertyExpression(PropertyExpression pe) {
    if (currentMethod!=null && currentMethod.isStatic()
            && pe.getObjectExpression() instanceof VariableExpression
            && ((VariableExpression) pe.getObjectExpression()).isSuperExpression()) {
        PropertyExpression pexp = new PropertyExpression(
                new ClassExpression(currentClass.getSuperClass()),
                transform(pe.getProperty())
        );
        pexp.setSourcePosition(pe);
        return pexp;
    }
    boolean oldInPropertyExpression = inPropertyExpression;
    Expression oldFoundArgs = foundArgs;
    Expression oldFoundConstant = foundConstant;
    inPropertyExpression = true;
    foundArgs = null;
    foundConstant = null;
    Expression objectExpression = transform(pe.getObjectExpression());
    boolean candidate = false;
    if (objectExpression instanceof MethodCallExpression) {
        candidate = ((MethodCallExpression)objectExpression).isImplicitThis();
    }

    if (foundArgs != null && foundConstant != null && candidate) {
        Expression result = findStaticMethodImportFromModule(foundConstant, foundArgs);
        if (result != null) {
            objectExpression = result;
            objectExpression.setSourcePosition(pe);
        }
    }
    inPropertyExpression = oldInPropertyExpression;
    foundArgs = oldFoundArgs;
    foundConstant = oldFoundConstant;
    pe.setObjectExpression(objectExpression);
    return pe;
}
 
Example 7
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkThisAndSuperAsPropertyAccess(final PropertyExpression expression) {
    if (expression.isImplicitThis()) return;
    String prop = expression.getPropertyAsString();
    if (prop == null) return;
    if (!prop.equals("this") && !prop.equals("super")) return;

    ClassNode type = expression.getObjectExpression().getType();
    if (expression.getObjectExpression() instanceof ClassExpression) {
        if (!(currentClass instanceof InnerClassNode) && !Traits.isTrait(type)) {
            addError("The usage of 'Class.this' and 'Class.super' is only allowed in nested/inner classes.", expression);
            return;
        }
        if (currentScope != null && !currentScope.isInStaticContext() && Traits.isTrait(type) && "super".equals(prop) && directlyImplementsTrait(type)) {
            return;
        }
        ClassNode iterType = currentClass;
        while (iterType != null) {
            if (iterType.equals(type)) break;
            iterType = iterType.getOuterClass();
        }
        if (iterType == null) {
            addError("The class '" + type.getName() + "' needs to be an outer class of '" +
                    currentClass.getName() + "' when using '.this' or '.super'.", expression);
        }
        if ((currentClass.getModifiers() & Opcodes.ACC_STATIC) == 0) return;
        if (currentScope != null && !currentScope.isInStaticContext()) return;
        addError("The usage of 'Class.this' and 'Class.super' within static nested class '" +
                currentClass.getName() + "' is not allowed in a static context.", expression);
    }
}
 
Example 8
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkAnnotationMemberValue(final Expression newValue) {
    if (newValue instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) newValue;
        if (!(pe.getObjectExpression() instanceof ClassExpression)) {
            addError("unable to find class '" + pe.getText() + "' for annotation attribute constant", pe.getObjectExpression());
        }
    } else if (newValue instanceof ListExpression) {
        ListExpression le = (ListExpression) newValue;
        for (Expression e : le.getExpressions()) {
            checkAnnotationMemberValue(e);
        }
    }
}
 
Example 9
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitPropertyExpression(final PropertyExpression expression) {
    assertExpressionAuthorized(expression);
    Expression receiver = expression.getObjectExpression();
    final String typeName = receiver.getType().getName();
    if (allowedReceivers != null && !allowedReceivers.contains(typeName)) {
        throw new SecurityException("Property access not allowed on [" + typeName + "]");
    } else if (disallowedReceivers != null && disallowedReceivers.contains(typeName)) {
        throw new SecurityException("Property access not allowed on [" + typeName + "]");
    }
    receiver.visit(this);
    final Expression property = expression.getProperty();
    checkConstantTypeIfNotMethodNameOrProperty(property);
}
 
Example 10
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static AutoCloneStyle getStyle(AnnotationNode node, String name) {
    final Expression member = node.getMember(name);
    if (member instanceof PropertyExpression) {
        PropertyExpression prop = (PropertyExpression) member;
        Expression oe = prop.getObjectExpression();
        if (oe instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) oe;
            if (ce.getType().getName().equals("groovy.transform.AutoCloneStyle")) {
                return AutoCloneStyle.valueOf(prop.getPropertyAsString());
            }
        }
    }
    return null;
}
 
Example 11
Source File: PathFinderVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitPropertyExpression(PropertyExpression node) {

    // XXX PropertyExpression has wrong offsets, e.g. 4-4 for 'this.field1 = 77'
    // and was never added to path,
    // therefore let's check if its children are wraping given position
    // and add it then

    Expression objectExpression = node.getObjectExpression();
    Expression property = node.getProperty();

    if (isInside(node, line, column, false)) {
        path.add(node);
    } else {
        boolean nodeAdded = false;
        if (isInside(objectExpression, line, column, false)) {
            path.add(node);
            nodeAdded = true;
        }
        if (isInside(property, line, column, false)) {
            if (!nodeAdded) {
                path.add(node);
            }
        }
    }

    objectExpression.visit(this);
    property.visit(this);
}
 
Example 12
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isTraitSuperPropertyExpression(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pexp = (PropertyExpression) exp;
        Expression objectExpression = pexp.getObjectExpression();
        if (objectExpression instanceof ClassExpression) {
            ClassNode type = objectExpression.getType();
            if (Traits.isTrait(type) && "super".equals(pexp.getPropertyAsString())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 13
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkFinalFieldAccess(Expression expression) {
    if (!(expression instanceof VariableExpression) && !(expression instanceof PropertyExpression)) return;
    Variable v = null;
    if (expression instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) expression;
        v = ve.getAccessedVariable();
    } else {
        PropertyExpression propExp = ((PropertyExpression) expression);
        Expression objectExpression = propExp.getObjectExpression();
        if (objectExpression instanceof VariableExpression) {
            VariableExpression varExp = (VariableExpression) objectExpression;
            if (varExp.isThisExpression()) {
                v = currentClass.getDeclaredField(propExp.getPropertyAsString());
            }
        }
    }
    if (v instanceof FieldNode) {
        FieldNode fn = (FieldNode) v;

        /*
         *  if it is static final but not accessed inside a static constructor, or,
         *  if it is an instance final but not accessed inside a instance constructor, it is an error
         */
        boolean isFinal = fn.isFinal();
        boolean isStatic = fn.isStatic();
        boolean error = isFinal && ((isStatic && !inStaticConstructor) || (!isStatic && !inConstructor));

        if (error) addError("cannot modify" + (isStatic ? " static" : "") + " final field '" + fn.getName() +
                "' outside of " + (isStatic ? "static initialization block." : "constructor."), expression);
    }
}
 
Example 14
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * A property on "this", like this.x is transformed to a direct field access,
 * so we need to check the static context here.
 */
private void checkPropertyOnExplicitThis(final PropertyExpression expression) {
    if (!currentScope.isInStaticContext()) return;
    Expression object = expression.getObjectExpression();
    if (!(object instanceof VariableExpression)) return;
    VariableExpression ve = (VariableExpression) object;
    if (!ve.getName().equals("this")) return;
    String name = expression.getPropertyAsString();
    if (name == null || name.equals("class")) return;
    Variable member = findClassMember(currentClass, name);
    if (member == null) return;
    checkVariableContextAccess(member, expression);
}
 
Example 15
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void transformSpreadOnLHS(final BinaryExpression expression) {
    PropertyExpression spreadExpression = (PropertyExpression) expression.getLeftExpression();
    Expression receiver = spreadExpression.getObjectExpression();

    int counter = labelCounter.incrementAndGet();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();

    // create an empty arraylist
    VariableExpression result = varX(this.getClass().getSimpleName() + "$spreadresult" + counter, ARRAYLIST_CLASSNODE);
    ConstructorCallExpression newArrayList = ctorX(ARRAYLIST_CLASSNODE);
    newArrayList.setNodeMetaData(DIRECT_METHOD_CALL_TARGET, ARRAYLIST_CONSTRUCTOR);
    Expression decl = declX(result, newArrayList);
    decl.visit(controller.getAcg());
    // if (receiver != null)
    receiver.visit(controller.getAcg());
    Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitJumpInsn(IFNULL, ifnull);
    operandStack.remove(1); // receiver consumed by if()
    Label nonull = compileStack.createLocalLabel("nonull_" + counter);
    mv.visitLabel(nonull);
    ClassNode componentType = StaticTypeCheckingVisitor.inferLoopElementType(
            controller.getTypeChooser().resolveType(receiver, controller.getClassNode()));
    Parameter iterator = new Parameter(componentType, "for$it$" + counter);
    VariableExpression iteratorAsVar = varX(iterator);
    PropertyExpression pexp = spreadExpression instanceof AttributeExpression
        ? new AttributeExpression(iteratorAsVar, spreadExpression.getProperty(), true)
        : new PropertyExpression(iteratorAsVar, spreadExpression.getProperty(), true);
    pexp.setImplicitThis(spreadExpression.isImplicitThis());
    pexp.setSourcePosition(spreadExpression);
    BinaryExpression assignment = binX(pexp, expression.getOperation(), expression.getRightExpression());
    MethodCallExpression add = callX(result, "add", assignment);
    add.setMethodTarget(ARRAYLIST_ADD_METHOD);
    // for (e in receiver) { result.add(e?.method(arguments) }
    ForStatement stmt = new ForStatement(
            iterator,
            receiver,
            stmt(add)
    );
    stmt.visit(controller.getAcg());
    // else { empty list }
    mv.visitLabel(ifnull);
    // end of if/else
    // return result list
    result.visit(controller.getAcg());
}
 
Example 16
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitPropertyExpression(final PropertyExpression expression) {
    Expression objectExpression = expression.getObjectExpression();
    OperandStack operandStack = controller.getOperandStack();
    int mark = operandStack.getStackLength() - 1;
    boolean visited = false;

    if (isThisOrSuper(objectExpression)) {
        String name = expression.getPropertyAsString();
        if (name != null) {
            FieldNode fieldNode = null;
            ClassNode classNode = controller.getClassNode();

            if (isThisExpression(objectExpression)) {
                if (controller.isInGeneratedFunction()) { // params are stored as fields
                    if (expression.isImplicitThis()) fieldNode = classNode.getDeclaredField(name);
                } else {
                    fieldNode = classNode.getDeclaredField(name);

                    if (fieldNode == null && !isValidFieldNodeForByteCodeAccess(classNode.getField(name), classNode)) {
                        // GROOVY-9501, GROOVY-9569
                        if (checkStaticOuterField(expression, name)) return;
                    }
                }
            } else {
                fieldNode = classNode.getSuperClass().getDeclaredField(name);
                // GROOVY-4497: do not visit super class field if it is private
                if (fieldNode != null && fieldNode.isPrivate()) fieldNode = null;

                if (fieldNode == null) {
                    visited = tryPropertyOfSuperClass(expression, name);
                }
            }

            if (fieldNode != null) {
                fieldX(fieldNode).visit(this);
                visited = true;
            }
        }
    }

    if (!visited) {
        boolean useMetaObjectProtocol = isGroovyObject(objectExpression)
                && (!isThisOrSuper(objectExpression) || !controller.isStaticContext() || controller.isInGeneratedFunction());

        MethodCallerMultiAdapter adapter;
        if (controller.getCompileStack().isLHS()) {
            adapter = useMetaObjectProtocol ? setGroovyObjectProperty : setProperty;
        } else {
            adapter = useMetaObjectProtocol ? getGroovyObjectProperty : getProperty;
        }
        visitAttributeOrProperty(expression, adapter);
    }

    if (controller.getCompileStack().isLHS()) {
        operandStack.remove(operandStack.getStackLength() - mark);
    } else {
        controller.getAssertionWriter().record(expression.getProperty());
    }
}
 
Example 17
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitAttributeOrProperty(final PropertyExpression pexp, final MethodCallerMultiAdapter adapter) {
    ClassNode classNode = controller.getClassNode();
    String propertyName = pexp.getPropertyAsString();
    Expression objectExpression = pexp.getObjectExpression();

    if (objectExpression instanceof ClassExpression && "this".equals(propertyName)) {
        // we have something like A.B.this, and need to make it
        // into this.this$0.this$0, where this.this$0 returns
        // A.B and this.this$0.this$0 return A.
        ClassNode type = objectExpression.getType();
        if (controller.getCompileStack().isInSpecialConstructorCall() && type.equals(classNode.getOuterClass())) {
            // Outer.this in a special constructor call
            ConstructorNode ctor = controller.getConstructorNode();
            Expression receiver = !classNode.isStaticClass() ? new VariableExpression(ctor.getParameters()[0]) : new ClassExpression(type);
            receiver.setSourcePosition(pexp);
            receiver.visit(this);
            return;
        }

        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitVarInsn(ALOAD, 0);
        ClassNode iterType = classNode;
        while (!iterType.equals(type)) {
            String ownerName = BytecodeHelper.getClassInternalName(iterType);
            if (iterType.getOuterClass() == null) break;
            FieldNode thisField = iterType.getField("this$0");
            iterType = iterType.getOuterClass();
            if (thisField == null) {
                // closure within inner class
                while (ClassHelper.isGeneratedFunction(iterType)) {
                    // GROOVY-8881: cater for closures within closures - getThisObject is already outer class of all closures
                    iterType = iterType.getOuterClass();
                }
                mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
            } else {
                ClassNode thisFieldType = thisField.getType();
                if (ClassHelper.CLOSURE_TYPE.equals(thisFieldType)) {
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", BytecodeHelper.getTypeDescription(ClassHelper.CLOSURE_TYPE));
                    mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                    mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
                } else {
                    String typeName = BytecodeHelper.getTypeDescription(iterType);
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", typeName);
                }
            }
        }
        controller.getOperandStack().push(type);
        return;
    }

    if (propertyName != null) {
        // TODO: spread safe should be handled inside
        if (adapter == getProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else if (adapter == getGroovyObjectProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGroovyObjectGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else {
            controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, propertyName, adapter);
        }
    } else {
        controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, null, adapter);
    }
}
 
Example 18
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression transformBinaryExpression(final BinaryExpression exp) {
    Expression trn = super.transform(exp);
    if (trn instanceof BinaryExpression) {
        BinaryExpression bin = (BinaryExpression) trn;
        Expression leftExpression = bin.getLeftExpression();
        if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof PropertyExpression) {
            ClassNode traitReceiver = null;
            PropertyExpression leftPropertyExpression = (PropertyExpression) leftExpression;
            if (isTraitSuperPropertyExpression(leftPropertyExpression.getObjectExpression())) {
                PropertyExpression pexp = (PropertyExpression) leftPropertyExpression.getObjectExpression();
                traitReceiver = pexp.getObjectExpression().getType();
            }
            if (traitReceiver!=null) {
                // A.super.foo = ...
                TraitHelpersTuple helpers = Traits.findHelpers(traitReceiver);
                ClassNode helper = helpers.getHelper();
                String setterName = MetaProperty.getSetterName(leftPropertyExpression.getPropertyAsString());
                List<MethodNode> methods = helper.getMethods(setterName);
                for (MethodNode method : methods) {
                    Parameter[] parameters = method.getParameters();
                    if (parameters.length==2 && parameters[0].getType().equals(traitReceiver)) {
                        ArgumentListExpression args = new ArgumentListExpression(
                                new VariableExpression("this"),
                                transform(exp.getRightExpression())
                        );
                        MethodCallExpression setterCall = new MethodCallExpression(
                                new ClassExpression(helper),
                                setterName,
                                args
                        );
                        setterCall.setMethodTarget(method);
                        setterCall.setImplicitThis(false);
                        return setterCall;
                    }
                }
                return bin;
            }
        }
    }
    return trn;
}