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

The following examples show how to use org.codehaus.groovy.ast.expr.PropertyExpression. 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: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addExpressionOccurrences(PropertyExpression expression) {
    final Expression property = expression.getProperty();
    final String nodeAsString = expression.getPropertyAsString();
    
    if (nodeAsString != null) {
        if (leaf instanceof Variable && nodeAsString.equals(((Variable) leaf).getName())) {
            occurrences.add(property);
        } else if (leaf instanceof ConstantExpression && leafParent instanceof PropertyExpression) {
            PropertyExpression propertyUnderCursor = (PropertyExpression) leafParent;

            if (nodeAsString.equals(propertyUnderCursor.getPropertyAsString())) {
                occurrences.add(property);
            }
        }
    }
}
 
Example #2
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 #3
Source File: VariableExpressionTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Expression tryTransformPrivateFieldAccess(final VariableExpression expr) {
    FieldNode field = expr.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);
    if (field == null) {
        field = expr.getNodeMetaData(StaticTypesMarker.PV_FIELDS_MUTATION);
    }
    if (field != null) {
        // access to a private field from a section of code that normally doesn't have access to it, like a closure or an inner class
        PropertyExpression pexp = thisPropX(true, expr.getName());
        // store the declaring class so that the class writer knows that it will have to call a bridge method
        pexp.getObjectExpression().putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, field.getDeclaringClass());
        pexp.putNodeMetaData(StaticTypesMarker.DECLARATION_INFERRED_TYPE, field.getOriginType());
        pexp.getProperty().setSourcePosition(expr);
        return pexp;
    }
    return null;
}
 
Example #4
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean getField(final PropertyExpression expression, final Expression receiver, ClassNode receiverType, final String name) {
    boolean safe = expression.isSafe();
    boolean implicitThis = expression.isImplicitThis();

    if (makeGetField(receiver, receiverType, name, safe, implicitThis)) return true;
    if (receiver instanceof ClassExpression) {
        if (makeGetField(receiver, receiver.getType(), name, safe, implicitThis)) return true;
        if (makeGetPrivateFieldWithBridgeMethod(receiver, receiver.getType(), name, safe, implicitThis)) return true;
    }
    if (makeGetPrivateFieldWithBridgeMethod(receiver, receiverType, name, safe, implicitThis)) return true;

    boolean isClassReceiver = false;
    if (isClassClassNodeWrappingConcreteType(receiverType)) {
        isClassReceiver = true;
        receiverType = receiverType.getGenericsTypes()[0].getType();
    }
    if (isClassReceiver && makeGetField(receiver, CLASS_Type, name, safe, false)) return true;
    if (receiverType.isEnum()) {
        controller.getMethodVisitor().visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(receiverType), name, BytecodeHelper.getTypeDescription(receiverType));
        controller.getOperandStack().push(receiverType);
        return true;
    }
    return false;
}
 
Example #5
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ConstantExpression getConstantExpression(Expression exp, ClassNode attrType) {
    Expression result = exp;
    if (!(result instanceof ConstantExpression)) {
        result = transformInlineConstants(result, attrType);
    }
    if (result instanceof ConstantExpression) {
        return (ConstantExpression) result;
    }
    String base = "Expected '" + exp.getText() + "' to be an inline constant of type " + attrType.getName();
    if (exp instanceof PropertyExpression) {
        addError(base + " not a property expression", exp);
    } else if (exp instanceof VariableExpression && ((VariableExpression)exp).getAccessedVariable() instanceof FieldNode) {
        addError(base + " not a field expression", exp);
    } else {
        addError(base, exp);
    }
    ConstantExpression ret = new ConstantExpression(null);
    ret.setSourcePosition(exp);
    return ret;
}
 
Example #6
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void execMethodAndStoreForSubscriptOperator(final int op, String method, final Expression expression, final VariableSlotLoader usesSubscript, final Expression orig) {
    writePostOrPrefixMethod(op, method, expression, orig);

    // we need special code for arrays to store the result (like for a[1]++)
    if (usesSubscript != null) {
        BinaryExpression be = (BinaryExpression) expression;
        CompileStack compileStack = controller.getCompileStack();
        OperandStack operandStack = controller.getOperandStack();
        ClassNode methodResultType = operandStack.getTopOperand();
        int resultIdx = compileStack.defineTemporaryVariable("postfix_" + method, methodResultType, true);
        BytecodeExpression methodResultLoader = new VariableSlotLoader(methodResultType, resultIdx, operandStack);

        // execute the assignment, this will leave the right side (here the method call result) on the stack
        assignToArray(be, be.getLeftExpression(), usesSubscript, methodResultLoader, be.isSafe());

        compileStack.removeVar(resultIdx);

    } else if (expression instanceof VariableExpression || expression instanceof PropertyExpression || expression instanceof FieldExpression) {
        // here we handle a++ and a.b++
        controller.getOperandStack().dup();
        controller.getCompileStack().pushLHS(true);
        expression.visit(controller.getAcg());
        controller.getCompileStack().popLHS();
    }
    // other cases don't need storing, so nothing to be done for them
}
 
Example #7
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 #8
Source File: ContractInputProposalsCodeVisitorSupport.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    proposals = completionComputer.computeCompletionProposals(context, monitor);
    final BinaryExpression binaryExpression = (BinaryExpression) contentAssistContext.getPerceivedCompletionNode();
    final Expression leftExpression = binaryExpression.getLeftExpression();
    String multipleInputName = null;
    if (leftExpression instanceof PropertyExpression) {
        final PropertyExpression propertyExpr = (PropertyExpression) leftExpression;
        final Expression objectExpression = propertyExpr.getProperty();
        multipleInputName = objectExpression.getText();
    } else if (leftExpression instanceof VariableExpression) {
        multipleInputName = ((VariableExpression) leftExpression).getName();
    }
    if (multipleInputName != null) {
        final ContractInput multipleInput = getInputWithName(multipleInputName, inputs);
        final ContractInput copy = EcoreUtil.copy(multipleInput);
        copy.setMultiple(false);
        final String fullyQualifiedType = ExpressionHelper.getContractInputReturnType(copy);
        if (fullyQualifiedType != null && prefix.isEmpty()) {
            proposals = getMethodProposals(contentAssistContext, context, inputs, prefix, multipleInputName, fullyQualifiedType);
        }
    }
}
 
Example #9
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 #10
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitArrayExpression(ArrayExpression visitedArray) {
    final ClassNode visitedType = visitedArray.getElementType();
    final String visitedName = ElementUtils.getTypeName(visitedType);

    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        ASTNode currentNode = FindTypeUtils.findCurrentNode(path, doc, cursorOffset);
        addOccurrences(visitedType, (ClassNode) currentNode);
    } else if (leaf instanceof Variable) {
        String varName = removeParentheses(((Variable) leaf).getName());
        if (varName.equals(visitedName)) {
            occurrences.add(new FakeASTNode(visitedType, visitedName));
        }
    } else if (leaf instanceof ConstantExpression && leafParent instanceof PropertyExpression) {
        if (visitedName.equals(((PropertyExpression) leafParent).getPropertyAsString())) {
            occurrences.add(new FakeASTNode(visitedType, visitedName));
        }
    }
    super.visitArrayExpression(visitedArray);
}
 
Example #11
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 #12
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 #13
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 #14
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
/**
 * This returns a String representation of the object if it is a valid expression for a parent
 * object. Otherwise, it will return null. For instance in `defaultConfig.minSdkVersion 14`,
 * defaultConfig would be a valid parent expression.
 */
private String getValidParentString(Expression objectExpression) {
  if (objectExpression instanceof PropertyExpression) {
    return ((PropertyExpression) objectExpression).getPropertyAsString();
  } else if (objectExpression instanceof VariableExpression) {
    VariableExpression variableExpression = (VariableExpression) objectExpression;
    if (!variableExpression.getName().equals("this")) {
      return variableExpression.getName();
    }
  }
  return null;
}
 
Example #15
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 #16
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transform(final Expression exp) {
    if (exp == null) return null;
    Expression ret;
    if (exp instanceof VariableExpression) {
        ret = transformVariableExpression((VariableExpression) exp);
    } else if (exp.getClass() == PropertyExpression.class) {
        ret = transformPropertyExpression((PropertyExpression) exp);
    } else if (exp instanceof DeclarationExpression) {
        ret = transformDeclarationExpression((DeclarationExpression) exp);
    } else if (exp instanceof BinaryExpression) {
        ret = transformBinaryExpression((BinaryExpression) exp);
    } else if (exp instanceof MethodCallExpression) {
        ret = transformMethodCallExpression((MethodCallExpression) exp);
    } else if (exp instanceof ClosureExpression) {
        ret = transformClosureExpression((ClosureExpression) exp);
    } else if (exp instanceof ConstructorCallExpression) {
        ret = transformConstructorCallExpression((ConstructorCallExpression) exp);
    } else if (exp instanceof AnnotationConstantExpression) {
        ret = transformAnnotationConstantExpression((AnnotationConstantExpression) exp);
    } else {
        resolveOrFail(exp.getType(), exp);
        ret = exp.transformExpression(this);
    }
    if (ret != null && ret != exp) {
        ret.setSourcePosition(exp);
    }
    return ret;
}
 
Example #17
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<groovy.transform.PackageScopeTarget> determineTargets(Expression expr) {
    List<groovy.transform.PackageScopeTarget> list = new ArrayList<groovy.transform.PackageScopeTarget>();
    if (expr instanceof PropertyExpression) {
        list.add(extractTarget((PropertyExpression) expr));
    } else if (expr instanceof ListExpression) {
        final ListExpression expressionList = (ListExpression) expr;
        final List<Expression> expressions = expressionList.getExpressions();
        for (Expression ex : expressions) {
            if (ex instanceof PropertyExpression) {
                list.add(extractTarget((PropertyExpression) ex));
            }
        }
    }
    return list;
}
 
Example #18
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void visitEnumExpression(String attrName, PropertyExpression propExpr, ClassNode attrType) {
    if (!propExpr.getObjectExpression().getType().isDerivedFrom(attrType)) {
        addError("Attribute '" + attrName + "' should have type '" + attrType.getName() + "' (Enum), but found "
                + propExpr.getObjectExpression().getType().getName(),
                propExpr);
    }
}
 
Example #19
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluateEqual(final BinaryExpression expression, final boolean defineVariable) {
    Expression leftExpression = expression.getLeftExpression();
    if (!defineVariable) {
        if (leftExpression instanceof PropertyExpression) {
            PropertyExpression pexp = (PropertyExpression) leftExpression;
            if (makeSetProperty(
                    pexp.getObjectExpression(),
                    pexp.getProperty(),
                    expression.getRightExpression(),
                    pexp.isSafe(),
                    pexp.isSpreadSafe(),
                    pexp.isImplicitThis(),
                    pexp instanceof AttributeExpression)) {
                return;
            }
        }
    } else {
        Expression rightExpression = expression.getRightExpression();
        if (rightExpression instanceof LambdaExpression || rightExpression instanceof MethodReferenceExpression) {
            rightExpression.putNodeMetaData(INFERRED_FUNCTIONAL_INTERFACE_TYPE, leftExpression.getNodeMetaData(INFERRED_TYPE));
        }
    }
    // GROOVY-5620: spread-safe operator on LHS is not supported
    if (leftExpression instanceof PropertyExpression
            && ((PropertyExpression) leftExpression).isSpreadSafe()
            && StaticTypeCheckingSupport.isAssignment(expression.getOperation().getType())) {
        // rewrite it so that it can be statically compiled
        transformSpreadOnLHS(expression);
        return;
    }
    super.evaluateEqual(expression, defineVariable);
}
 
Example #20
Source File: GroovyTypeCheckingExtensionSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleUnresolvedProperty(final PropertyExpression pexp) {
    setHandled(false);
    List<Closure> list = eventHandlers.get("handleUnresolvedProperty");
    if (list != null) {
        for (Closure closure : list) {
            safeCall(closure, pexp);
        }
    }
    return handled;
}
 
Example #21
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void makeGroovyObjectGetPropertySite(final Expression receiver, final String propertyName, final boolean safe, final boolean implicitThis) {
    ClassNode receiverType = controller.getClassNode();
    if (!AsmClassGenerator.isThisExpression(receiver) || controller.isInGeneratedFunction()) {
        receiverType = controller.getTypeChooser().resolveType(receiver, receiverType);
    }

    String property = propertyName;
    if (implicitThis && controller.getInvocationWriter() instanceof StaticInvocationWriter) {
        Expression currentCall = ((StaticInvocationWriter) controller.getInvocationWriter()).getCurrentCall();
        if (currentCall != null && currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) != null) {
            property = currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
            String[] props = property.split("\\.");
            BytecodeExpression thisLoader = bytecodeX(CLOSURE_TYPE, mv -> mv.visitVarInsn(ALOAD, 0));
            PropertyExpression pexp = propX(thisLoader, constX(props[0]), safe);
            for (int i = 1, n = props.length; i < n; i += 1) {
                pexp.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, CLOSURE_TYPE);
                pexp = propX(pexp, props[i]);
            }
            pexp.visit(controller.getAcg());
            return;
        }
    }

    if (makeGetPropertyWithGetter(receiver, receiverType, property, safe, implicitThis)) return;
    if (makeGetPrivateFieldWithBridgeMethod(receiver, receiverType, property, safe, implicitThis)) return;
    if (makeGetField(receiver, receiverType, property, safe, implicitThis)) return;

    MethodCallExpression call = callX(receiver, "getProperty", args(constX(property)));
    call.setImplicitThis(implicitThis);
    call.setMethodTarget(GROOVYOBJECT_GETPROPERTY_METHOD);
    call.setSafe(safe);
    call.visit(controller.getAcg());
}
 
Example #22
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
 * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
 * {@link groovy.transform.Generated} annotations will be copied if {@code includeGenerated} is true.
 * <p>
 * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
 */
public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, final List<AnnotationNode> notCopied, final boolean includeGenerated) {
    List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
    for (AnnotationNode annotation : annotationList)  {
        List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
        if (annotations.isEmpty()) continue;

        if (hasClosureMember(annotation)) {
            notCopied.add(annotation);
            continue;
        }

        if (!includeGenerated && annotation.getClassNode().getName().equals("groovy.transform.Generated")) {
            continue;
        }

        AnnotationNode retentionPolicyAnnotation = annotations.get(0);
        Expression valueExpression = retentionPolicyAnnotation.getMember("value");
        if (!(valueExpression instanceof PropertyExpression)) continue;

        PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
        boolean processAnnotation = propertyExpression.getProperty() instanceof ConstantExpression
                && ("RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
                    || "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()));
        if (processAnnotation)  {
            AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
            for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet())  {
                newAnnotation.addMember(member.getKey(), member.getValue());
            }
            newAnnotation.setSourcePosition(annotatedNode);

            copied.add(newAnnotation);
        }
    }
}
 
Example #23
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private BinaryExpression createAssignmentToField(final Expression rightExpression,
                                                 final Token operation, final String fieldName) {
    return new BinaryExpression(
            new PropertyExpression(
                    new VariableExpression(weaved),
                    fieldName
            ),
            operation,
            transform(rightExpression));
}
 
Example #24
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression createFieldHelperCall(Expression exp, ClassNode weavedType, String propName) {
    String method = Traits.helperGetterName(new FieldNode(propName, 0, ClassHelper.OBJECT_TYPE, weavedType, null));
    MethodCallExpression mce = new MethodCallExpression(
            createFieldHelperReceiver(),
            method,
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setSourcePosition(exp instanceof PropertyExpression ? ((PropertyExpression) exp).getProperty() : exp);
    mce.setImplicitThis(false);
    return mce;
}
 
Example #25
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 #26
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Instructs the type checker that a property access is dynamic.
 * Calling this method automatically sets the handled flag to true.
 * @param pexp the property or attribute expression
 * @param returnType the type of the property
 */
public void makeDynamic(PropertyExpression pexp, ClassNode returnType) {
    context.getEnclosingMethod().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
    pexp.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
    storeType(pexp, returnType);
    setHandled(true);
    if (debug) {
        LOG.info("Turning '"+pexp.getText()+"' into a dynamic property access of type "+returnType.toString(false));
    }
}
 
Example #27
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression transformPropertyAssignmentToSetterCall(final PropertyExpression leftExpression, final Expression rightExpression, final MethodNode directMCT) {
    // transform "a.x = b" into "def tmp = b; a.setX(tmp); tmp"
    return StaticPropertyAccessHelper.transformToSetterCall(
            leftExpression.getObjectExpression(),
            directMCT,
            rightExpression,
            false,
            leftExpression.isSafe(),
            false,
            true, // to be replaced with a proper test whether a return value should be used or not
            leftExpression
    );
}
 
Example #28
Source File: StaticCompilationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitPropertyExpression(final PropertyExpression expression) {
    super.visitPropertyExpression(expression);
    Object dynamic = expression.getNodeMetaData(DYNAMIC_RESOLUTION);
    if (dynamic != null) {
        expression.getObjectExpression().putNodeMetaData(RECEIVER_OF_DYNAMIC_PROPERTY, dynamic);
    }
}
 
Example #29
Source File: ReferenceDetectingVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visitPropertyExpression(final PropertyExpression expression) {
    extractReferencePath(expression, new Action<PropertyExpression>() {
        public void execute(PropertyExpression propertyExpression) {
            referenceStack.push(expression.getPropertyAsString());
            expression.getObjectExpression().visit(ReferenceDetectingVisitor.this);
        }
    });
}
 
Example #30
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformMethodCallExpression(final MethodCallExpression exp) {
    if (isTraitSuperPropertyExpression(exp.getObjectExpression())) {
        Expression objectExpression = exp.getObjectExpression();
        ClassNode traitReceiver = ((PropertyExpression) objectExpression).getObjectExpression().getType();

        if (traitReceiver != null) {
            // (SomeTrait.super).foo() --> SomeTrait$Helper.foo(this)
            ClassExpression receiver = new ClassExpression(
                    getHelper(traitReceiver)
            );
            ArgumentListExpression newArgs = new ArgumentListExpression();
            Expression arguments = exp.getArguments();
            newArgs.addExpression(new VariableExpression("this"));
            if (arguments instanceof TupleExpression) {
                List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
                for (Expression expression : expressions) {
                    newArgs.addExpression(transform(expression));
                }
            } else {
                newArgs.addExpression(transform(arguments));
            }
            MethodCallExpression result = new MethodCallExpression(
                    receiver,
                    transform(exp.getMethod()),
                    newArgs
            );
            result.setImplicitThis(false);
            result.setSpreadSafe(exp.isSpreadSafe());
            result.setSafe(exp.isSafe());
            result.setSourcePosition(exp);
            return result;
        }
    }
    return super.transform(exp);
}