Java Code Examples for org.codehaus.groovy.ast.FieldNode#isPrivate()

The following examples show how to use org.codehaus.groovy.ast.FieldNode#isPrivate() . 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: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean isValidFieldNodeForByteCodeAccess(final FieldNode fn, final ClassNode accessingNode) {
    if (fn == null) return false;
    ClassNode declaringClass = fn.getDeclaringClass();
    // same class is always allowed access
    if (fn.isPublic() || declaringClass.equals(accessingNode)) return true;
    boolean samePackages = Objects.equals(declaringClass.getPackageName(), accessingNode.getPackageName());
    // protected means same class or same package, or subclass
    if (fn.isProtected() && (samePackages || accessingNode.isDerivedFrom(declaringClass))) {
        return true;
    }
    if (!fn.isPrivate()) {
        // package private is the only modifier left. It means  same package is allowed, subclass not, same class is
        return samePackages;
    }
    return false;
}
 
Example 2
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Direct access is allowed from the declaring class of the field and sometimes from inner and peer types.
 *
 * @return {@code true} if GETFIELD or GETSTATIC is safe for given field and receiver
 */
private static boolean isDirectAccessAllowed(final FieldNode field, final ClassNode receiver) {
    // first, direct access from anywhere for public fields
    if (field.isPublic()) return true;

    ClassNode declaringType = field.getDeclaringClass().redirect(), receiverType = receiver.redirect();

    // next, direct access from within the declaring class
    if (receiverType.equals(declaringType)) return true;

    if (field.isPrivate()) return false;

    // next, direct access from within the declaring package
    if (Objects.equals(receiver.getPackageName(), declaringType.getPackageName())) return true;

    // last, inner class access to outer class fields
    receiverType = receiverType.getOuterClass();
    while (receiverType != null) {
        if (receiverType.equals(declaringType)) {
            return true;
        }
        receiverType = receiverType.getOuterClass();
    }
    return false;
}
 
Example 3
Source File: GroovyNodeToStringUtils.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public static String variableToString(Variable variable, ASTNodeVisitor ast) {
	StringBuilder builder = new StringBuilder();
	if (variable instanceof FieldNode) {
		FieldNode fieldNode = (FieldNode) variable;
		if (fieldNode.isPublic()) {
			builder.append("public ");
		}
		if (fieldNode.isProtected()) {
			builder.append("protected ");
		}
		if (fieldNode.isPrivate()) {
			builder.append("private ");
		}

		if (fieldNode.isFinal()) {
			builder.append("final ");
		}

		if (fieldNode.isStatic()) {
			builder.append("static ");
		}
	}
	ClassNode varType = null;
	if (variable instanceof ASTNode) {
		varType = GroovyASTUtils.getTypeOfNode((ASTNode) variable, ast);
	} else {
		varType = variable.getType();
	}
	builder.append(varType.getNameWithoutPackage());
	builder.append(" ");
	builder.append(variable.getName());
	return builder.toString();
}
 
Example 4
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkStaticOuterField(final PropertyExpression pexp, final String propertyName) {
    for (final ClassNode outer : controller.getClassNode().getOuterClasses()) {
        FieldNode field = outer.getDeclaredField(propertyName);
        if (field != null) {
            if (!field.isStatic()) break;

            Expression outerClass = classX(outer);
            outerClass.setNodeMetaData(PROPERTY_OWNER, outer);
            outerClass.setSourcePosition(pexp.getObjectExpression());

            Expression outerField = attrX(outerClass, pexp.getProperty());
            outerField.setSourcePosition(pexp);
            outerField.visit(this);
            return true;
        } else {
            field = outer.getField(propertyName); // checks supers
            if (field != null && !field.isPrivate() && (field.isPublic() || field.isProtected()
                    || Objects.equals(field.getDeclaringClass().getPackageName(), outer.getPackageName()))) {
                if (!field.isStatic()) break;

                Expression upperClass = classX(field.getDeclaringClass());
                upperClass.setNodeMetaData(PROPERTY_OWNER, field.getDeclaringClass());
                upperClass.setSourcePosition(pexp.getObjectExpression());

                Expression upperField = propX(upperClass, pexp.getProperty());
                upperField.setSourcePosition(pexp);
                upperField.visit(this);
                return true;
            }
        }
    }
    return false;
}
 
Example 5
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean makeSetPrivateFieldWithBridgeMethod(final Expression receiver, final ClassNode receiverType, final String fieldName, final Expression arguments, final boolean safe, final boolean spreadSafe, final boolean implicitThis) {
    FieldNode field = receiverType.getField(fieldName);
    ClassNode outerClass = receiverType.getOuterClass();
    if (field == null && implicitThis && outerClass != null && !receiverType.isStaticClass()) {
        Expression pexp;
        if (controller.isInGeneratedFunction()) {
            MethodCallExpression mce = callThisX("getThisObject");
            mce.setImplicitThis(true);
            mce.setMethodTarget(CLOSURE_GETTHISOBJECT_METHOD);
            mce.putNodeMetaData(INFERRED_TYPE, controller.getOutermostClass());
            pexp = castX(controller.getOutermostClass(), mce);
        } else {
            pexp = propX(classX(outerClass), "this");
            ((PropertyExpression) pexp).setImplicitThis(true);
        }
        pexp.putNodeMetaData(INFERRED_TYPE, outerClass);
        pexp.setSourcePosition(receiver);
        return makeSetPrivateFieldWithBridgeMethod(pexp, outerClass, fieldName, arguments, safe, spreadSafe, true);
    }
    ClassNode classNode = controller.getClassNode();
    if (field != null && field.isPrivate() && !receiverType.equals(classNode)
            && (StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(receiverType, classNode)
                || StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(classNode,receiverType))) {
        Map<String, MethodNode> mutators = receiverType.redirect().getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_FIELDS_MUTATORS);
        if (mutators != null) {
            MethodNode methodNode = mutators.get(fieldName);
            if (methodNode != null) {
                MethodCallExpression call = callX(receiver, methodNode.getName(), args(field.isStatic() ? nullX() : receiver, arguments));
                call.setImplicitThis(implicitThis);
                call.setMethodTarget(methodNode);
                call.setSafe(safe);
                call.setSpreadSafe(spreadSafe);
                call.visit(controller.getAcg());
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties,
                                                  final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters,
                                                  final boolean traverseSuperClasses, final boolean skipReadonly, final boolean reverse, final boolean allNames, final boolean includeStatic) {
    List<PropertyNode> result = new ArrayList<>();
    if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && !reverse) {
        result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
    }
    if (includeProperties) {
        for (PropertyNode pNode : cNode.getProperties()) {
            if ((!pNode.isStatic() || includeStatic) && !names.contains(pNode.getName())) {
                result.add(pNode);
                names.add(pNode.getName());
            }
        }
        if (includePseudoGetters || includePseudoSetters) {
            BeanUtils.addPseudoProperties(origType, cNode, result, names, includeStatic, includePseudoGetters, includePseudoSetters);
        }
    }
    if (includeFields) {
        for (FieldNode fNode : cNode.getFields()) {
            if ((fNode.isStatic() && !includeStatic) || fNode.isSynthetic() || cNode.getProperty(fNode.getName()) != null || names.contains(fNode.getName())) {
                continue;
            }

            // internal field
            if (fNode.getName().contains("$") && !allNames) {
                continue;
            }

            if (fNode.isPrivate() && !cNode.equals(origType)) {
                continue;
            }
            if (fNode.isFinal() && fNode.getInitialExpression() != null && skipReadonly) {
                continue;
            }
            result.add(new PropertyNode(fNode, fNode.getModifiers(), null, null));
            names.add(fNode.getName());
        }
    }
    if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && reverse) {
        result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
    }
    return result;
}
 
Example 7
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private boolean tryPropertyOfSuperClass(final PropertyExpression pexp, final String propertyName) {
    ClassNode classNode = controller.getClassNode();

    if (!controller.getCompileStack().isLHS()) {
        String methodName = "get" + capitalize(propertyName); // TODO: "is"
        callX(pexp.getObjectExpression(), methodName).visit(this);
        return true;
    }

    FieldNode fieldNode = classNode.getSuperClass().getField(propertyName);

    if (fieldNode == null) {
        throw new RuntimeParserException("Failed to find field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }
    if (fieldNode.isFinal()) {
        throw new RuntimeParserException("Cannot modify final field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }

    MethodNode setter = classNode.getSuperClass().getSetterMethod(getSetterName(propertyName));
    MethodNode getter = classNode.getSuperClass().getGetterMethod("get" + capitalize(propertyName));

    if (fieldNode.isPrivate() && (setter == null || getter == null || !setter.getDeclaringClass().equals(getter.getDeclaringClass()))) {
        throw new RuntimeParserException("Cannot access private field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp);
    }

    OperandStack operandStack = controller.getOperandStack();
    operandStack.doAsType(fieldNode.getType());

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    operandStack.push(classNode);

    operandStack.swap();

    String owner = BytecodeHelper.getClassInternalName(classNode.getSuperClass().getName());
    String desc = BytecodeHelper.getTypeDescription(fieldNode.getType());
    if (fieldNode.isPublic() || fieldNode.isProtected()) {
        mv.visitFieldInsn(PUTFIELD, owner, propertyName, desc);
    } else {
        mv.visitMethodInsn(INVOKESPECIAL, owner, setter.getName(), BytecodeHelper.getMethodDescriptor(setter), false);
    }
    return true;
}
 
Example 8
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());
    }
}