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

The following examples show how to use org.codehaus.groovy.ast.expr.Expression. 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: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * This will return an initial guess as to the string representation of the parent parent object,
 * based solely on the method callstack hierarchy. Any direct property or variable parents should
 * be resolved by using the getValidStringRepresentation function.
 */
private String getParentParent() {
  for (int i = methodCallStack.size() - 2; i >= 0; i--) {
    MethodCallExpression expression = methodCallStack.get(i);
    Expression arguments = expression.getArguments();
    if (arguments instanceof ArgumentListExpression) {
      ArgumentListExpression ale = (ArgumentListExpression) arguments;
      List<Expression> expressions = ale.getExpressions();
      if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) {
        return expression.getMethodAsString();
      }
    }
  }

  return null;
}
 
Example #2
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ConstructorCallExpression getConstructorCallExpression(
        ConstructorNode constructorNode) {
    Statement code = constructorNode.getCode();
    if (!(code instanceof BlockStatement)) {
        return null;
    }
    BlockStatement block = (BlockStatement) code;
    List<Statement> stats = block.getStatements();
    if (stats == null || stats.isEmpty()) {
        return null;
    }
    Statement stat = stats.get(0);
    if (!(stat instanceof ExpressionStatement)) {
        return null;
    }
    Expression expr = ((ExpressionStatement) stat).getExpression();
    if (!(expr instanceof ConstructorCallExpression)) {
        return null;
    }
    return (ConstructorCallExpression) expr;
}
 
Example #3
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 #4
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void writePostOrPrefixMethod(final int op, final String method, final Expression expression, final Expression orig) {
    MethodNode mn = orig.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (mn != null) {
        controller.getOperandStack().pop();
        MethodCallExpression call = callX(expression, method);
        call.setMethodTarget(mn);
        call.visit(controller.getAcg());
        return;
    }

    ClassNode top = controller.getOperandStack().getTopOperand();
    if (ClassHelper.isPrimitiveType(top) && (ClassHelper.isNumberType(top) || char_TYPE.equals(top))) {
        MethodVisitor mv = controller.getMethodVisitor();
        visitInsnByType(top, mv, ICONST_1, LCONST_1, FCONST_1, DCONST_1);
        if ("next".equals(method)) {
            visitInsnByType(top, mv, IADD, LADD, FADD, DADD);
        } else {
            visitInsnByType(top, mv, ISUB, LSUB, FSUB, DSUB);
        }
        return;
    }

    super.writePostOrPrefixMethod(op, method, expression, orig);
}
 
Example #5
Source File: AutoNewLineTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression call) {
    boolean old = inBuilderMethod;
    inBuilderMethod = false;
    if (call.isImplicitThis() && call.getArguments() instanceof TupleExpression) {
        List<Expression> expressions = ((TupleExpression) call.getArguments()).getExpressions();
        if (!expressions.isEmpty()) {
            Expression lastArg = expressions.get(expressions.size() - 1);
            if (lastArg instanceof ClosureExpression) {
                call.getObjectExpression().visit(this);
                call.getMethod().visit(this);
                for (Expression expression : expressions) {
                    inBuilderMethod =  (expression == lastArg);
                    expression.visit(this);
                }
            }
        }
    } else {
        super.visitMethodCallExpression(call);
    }
    inBuilderMethod = old;
}
 
Example #6
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void visitField(FieldNode node) {
    if (sameVariableName(leaf, node)) {
        if (node.hasInitialExpression()){
            Expression expression = node.getInitialExpression();
            if (expression instanceof ConstantExpression
                    && !expression.getText().equals("null")) { // NOI18N
                guessedType = ((ConstantExpression) expression).getType();
            } else if (expression instanceof ConstructorCallExpression) {
                guessedType = ((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);
                guessedType = MethodInference.findCallerType(expression, newPath, doc, newOffset);
            }
        }
    }
}
 
Example #7
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createListenerSetter(SourceUnit source, boolean bindable, ClassNode declaringClass, PropertyNode propertyNode) {
    if (bindable && needsPropertyChangeSupport(declaringClass, source)) {
        addPropertyChangeSupport(declaringClass);
    }
    if (needsVetoableChangeSupport(declaringClass, source)) {
        addVetoableChangeSupport(declaringClass);
    }
    String setterName = getSetterName(propertyNode.getName());
    if (declaringClass.getMethods(setterName).isEmpty()) {
        Expression fieldExpression = fieldX(propertyNode.getField());
        BlockStatement setterBlock = new BlockStatement();
        setterBlock.addStatement(createConstrainedStatement(propertyNode, fieldExpression));
        if (bindable) {
            setterBlock.addStatement(createBindableStatement(propertyNode, fieldExpression));
        } else {
            setterBlock.addStatement(createSetStatement(fieldExpression));
        }

        // create method void <setter>(<type> fieldName)
        createSetterMethod(declaringClass, propertyNode, setterName, setterBlock);
    } else {
        wrapSetterMethod(declaringClass, bindable, propertyNode.getName());
    }
}
 
Example #8
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    boolean assignment = StaticTypeCheckingSupport.isAssignment(expression.getOperation().getType());
    boolean isDeclaration = expression instanceof DeclarationExpression;
    Expression leftExpression = expression.getLeftExpression();
    Expression rightExpression = expression.getRightExpression();
    if (isDeclaration) {
        recordFinalVars(leftExpression);
    }
    // visit RHS first for expressions like a = b = 0
    inAssignmentRHS = assignment;
    rightExpression.visit(this);
    inAssignmentRHS = false;
    leftExpression.visit(this);
    if (assignment) {
        recordAssignments(expression, isDeclaration, leftExpression, rightExpression);
    }
}
 
Example #9
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement createConstructorStatementCollection(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    ClassNode fieldType = fieldExpr.getType();
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = ifElseS(
            isInstanceOfX(param, CLONEABLE_TYPE),
            assignS(fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(param, fieldType), fieldType)),
            assignS(fieldExpr, cloneCollectionExpr(param, fieldType)));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example #10
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean doAssignmentToLocalVariable(final String method, final BinaryExpression binExp) {
    Expression left = binExp.getLeftExpression();
    if (left instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) left;
        Variable v = ve.getAccessedVariable();
        if (v instanceof DynamicVariable) return false;
        if (v instanceof PropertyExpression) return false;
        /* field and declaration we don't return false */
    } else {
        return false;
    }

    evaluateBinaryExpression(method, binExp);
    controller.getOperandStack().dup();
    controller.getCompileStack().pushLHS(true);
    binExp.getLeftExpression().visit(controller.getAcg());
    controller.getCompileStack().popLHS();

    return true;
}
 
Example #11
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void visitAnnotationArrayElement(final Expression expr, final int arrayElementType, final AnnotationVisitor av) {
    switch (arrayElementType) {
        case 1:
            AnnotationNode atAttr = (AnnotationNode) ((AnnotationConstantExpression) expr).getValue();
            AnnotationVisitor av2 = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(atAttr.getClassNode()));
            visitAnnotationAttributes(atAttr, av2);
            av2.visitEnd();
            break;
        case 2:
            av.visit(null, ((ConstantExpression) expr).getValue());
            break;
        case 3:
            av.visit(null, Type.getType(BytecodeHelper.getTypeDescription(expr.getType())));
            break;
        case 4:
            PropertyExpression propExpr = (PropertyExpression) expr;
            av.visitEnum(null,
                    BytecodeHelper.getTypeDescription(propExpr.getObjectExpression().getType()),
                    String.valueOf(((ConstantExpression) propExpr.getProperty()).getValue()));
            break;
    }
}
 
Example #12
Source File: InnerClassVisitorHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static void setMethodDispatcherCode(BlockStatement block, Expression thiz, Parameter[] parameters) {
    List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>();
    gStringStrings.add(new ConstantExpression(""));
    gStringStrings.add(new ConstantExpression(""));
    List<Expression> gStringValues = new ArrayList<Expression>();
    gStringValues.add(new VariableExpression(parameters[0]));
    block.addStatement(
            new ReturnStatement(
                    new MethodCallExpression(
                            thiz,
                            new GStringExpression("$name", gStringStrings, gStringValues),
                            new ArgumentListExpression(
                                    new SpreadExpression(new VariableExpression(parameters[1]))
                            )
                    )
            )
    );
}
 
Example #13
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitDeclarationExpression(final DeclarationExpression expression) {
    Expression rightExpression = expression.getRightExpression();
    rightExpression.visit(this);

    ClassNode leftType = typeChooser.resolveType(expression.getLeftExpression(), node);
    ClassNode rightType = optimizeDivWithIntOrLongTarget(rightExpression, leftType);
    if (rightType == null) rightType = typeChooser.resolveType(rightExpression, node);
    if (isPrimitiveType(leftType) && isPrimitiveType(rightType)) {
        // if right is a constant, then we optimize only if it makes a block complete, so we set a maybe
        if (rightExpression instanceof ConstantExpression) {
            opt.chainCanOptimize(true);
        } else {
            opt.chainShouldOptimize(true);
        }
        addMeta(expression).type = Optional.ofNullable(typeChooser.resolveType(expression, node)).orElse(leftType);
        opt.chainInvolvedType(leftType);
        opt.chainInvolvedType(rightType);
    }
}
 
Example #14
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static void visitField(ErrorCollecting xform, AnnotationNode node, FieldNode fieldNode) {
    final Expression soft = node.getMember("soft");
    final Expression init = getInitExpr(xform, fieldNode);

    String backingFieldName = "$" + fieldNode.getName();
    fieldNode.rename(backingFieldName);
    fieldNode.setModifiers(ACC_PRIVATE | ACC_SYNTHETIC | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED))));
    PropertyNode pNode = fieldNode.getDeclaringClass().getProperty(backingFieldName);
    if (pNode != null) {
        fieldNode.getDeclaringClass().getProperties().remove(pNode);
    }

    if (soft instanceof ConstantExpression && ((ConstantExpression) soft).getValue().equals(true)) {
        createSoft(fieldNode, init);
    } else {
        create(fieldNode, init);
        // @Lazy not meaningful with primitive so convert to wrapper if needed
        if (ClassHelper.isPrimitiveType(fieldNode.getType())) {
            fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType()));
        }
    }
}
 
Example #15
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void fallbackAttributeOrPropertySite(final PropertyExpression expression, final Expression objectExpression, final String name, final MethodCallerMultiAdapter adapter) {
    if (name != null && (adapter == AsmClassGenerator.setField || adapter == AsmClassGenerator.setGroovyObjectField)) {
        TypeChooser typeChooser = controller.getTypeChooser();
        ClassNode classNode = controller.getClassNode();
        ClassNode rType = typeChooser.resolveType(objectExpression, classNode);
        if (controller.getCompileStack().isLHS()) {
            if (setField(expression, objectExpression, rType, name)) return;
        } else {
            if (getField(expression, objectExpression, rType, name)) return;
        }
    }
    super.fallbackAttributeOrPropertySite(expression, objectExpression, name, adapter);
}
 
Example #16
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression getInitExpr(ErrorCollecting xform, FieldNode fieldNode) {
    Expression initExpr = fieldNode.getInitialValueExpression();
    fieldNode.setInitialValueExpression(null);

    if (initExpr == null || initExpr instanceof EmptyExpression) {
        if (fieldNode.getType().isAbstract()) {
            xform.addError("You cannot lazily initialize '" + fieldNode.getName() + "' from the abstract class '" +
                    fieldNode.getType().getName() + "'", fieldNode);
        }
        initExpr = ctorX(fieldNode.getType());
    }

    return initExpr;
}
 
Example #17
Source File: ExternalStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static MethodNode createBuildMethod(BuilderASTTransformation transform, AnnotationNode anno, ClassNode sourceClass, List<PropertyInfo> fields) {
    String buildMethodName = transform.getMemberStringValue(anno, "buildMethodName", "build");
    final BlockStatement body = new BlockStatement();
    Expression sourceClassInstance = initializeInstance(sourceClass, fields, body);
    body.addStatement(returnS(sourceClassInstance));
    return new MethodNode(buildMethodName, ACC_PUBLIC, sourceClass, NO_PARAMS, NO_EXCEPTIONS, body);
}
 
Example #18
Source File: AnnotationConstantsVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression revertType(Expression val, ClassNode returnWrapperType) {
    ConstantExpression ce = (ConstantExpression) val;
    if (ClassHelper.Character_TYPE.equals(returnWrapperType) && ClassHelper.STRING_TYPE.equals(val.getType())) {
        return configure(val, Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) val));
    }
    ClassNode valWrapperType = ClassHelper.getWrapper(val.getType());
    if (ClassHelper.Integer_TYPE.equals(valWrapperType)) {
        Integer i = (Integer) ce.getValue();
        if (ClassHelper.Character_TYPE.equals(returnWrapperType)) {
            return configure(val, new ConstantExpression((char) i.intValue(), true));
        }
        if (ClassHelper.Short_TYPE.equals(returnWrapperType)) {
            return configure(val, new ConstantExpression(i.shortValue(), true));
        }
        if (ClassHelper.Byte_TYPE.equals(returnWrapperType)) {
            return configure(val, new ConstantExpression(i.byteValue(), true));
        }
    }
    if (ClassHelper.BigDecimal_TYPE.equals(valWrapperType)) {
        BigDecimal bd = (BigDecimal) ce.getValue();
        if (ClassHelper.Float_TYPE.equals(returnWrapperType)) {
            return configure(val, new ConstantExpression(bd.floatValue(), true));
        }
        if (ClassHelper.Double_TYPE.equals(returnWrapperType)) {
            return configure(val, new ConstantExpression(bd.doubleValue(), true));
        }
    }
    return null;
}
 
Example #19
Source File: AbstractInterruptibleASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static boolean getBooleanAnnotationParameter(AnnotationNode node, String parameterName, boolean defaultValue) {
    Expression member = node.getMember(parameterName);
    if (member != null) {
        if (member instanceof ConstantExpression) {
            try {
                return DefaultGroovyMethods.asType(((ConstantExpression) member).getValue(), Boolean.class);
            } catch (Exception e) {
                internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member");
            }
        } else {
            internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member");
        }
    }
    return defaultValue;
}
 
Example #20
Source File: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void findCollectedAnnotations(final AnnotationNode alias, final AnnotatedNode origin, final Integer index, final Map<Integer, AnnotationCollectorMode> modes, final Map<Integer, List<AnnotationNode>> existing, final Map<Integer, List<AnnotationNode>> replacements) {
    for (AnnotationNode annotation : alias.getClassNode().getAnnotations()) {
        if (annotation.getClassNode().getName().equals(AnnotationCollector.class.getName())) {
            Expression mode = annotation.getMember("mode");
            modes.put(index, Optional.ofNullable(mode)
                .map(exp -> evaluateExpression(exp, source.getConfiguration()))
                .map(val -> (AnnotationCollectorMode) val)
                .orElse(AnnotationCollectorMode.DUPLICATE)
            );

            Expression processor = annotation.getMember("processor");
            AnnotationCollectorTransform act = null;
            if (processor != null) {
                String className = (String) evaluateExpression(processor, source.getConfiguration());
                Class<?> klass = loadTransformClass(className, alias);
                if (klass != null) {
                    try {
                        act = (AnnotationCollectorTransform) klass.getDeclaredConstructor().newInstance();
                    } catch (ReflectiveOperationException | RuntimeException e) {
                        source.getErrorCollector().addErrorAndContinue(new ExceptionMessage(e, true, source));
                    }
                }
            } else {
                act = new AnnotationCollectorTransform();
            }
            if (act != null) {
                List<AnnotationNode> result = act.visit(annotation, alias, origin, source);
                replacements.put(index, result);
                return;
            }
        }
    }
    if (!replacements.containsKey(index)) {
        existing.put(index, Collections.singletonList(alias));
    }
}
 
Example #21
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<String> getMemberStringList(AnnotationNode anno, String name) {
    Expression expr = anno.getMember(name);
    if (expr == null) {
        return null;
    }
    if (expr instanceof ListExpression) {
        final ListExpression listExpression = (ListExpression) expr;
        if (isUndefinedMarkerList(listExpression)) {
            return null;
        }

        return getValueStringList(listExpression);
    }
    return tokenize(getMemberStringValue(anno, name));
}
 
Example #22
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean containsOnlyConstants(final ListExpression list) {
    for (Expression exp : list.getExpressions()) {
        if (exp instanceof ConstantExpression) continue;
        return false;
    }
    return true;
}
 
Example #23
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 #24
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 #25
Source File: GroovyClassFilterTransformer.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Expression transformConstructorCall(ConstructorCallExpression exp)
{
	if (allowed(exp.getType()))
	{
		Expression originalArgs = exp.getArguments();
		Expression transformedArgs = transformArguments(originalArgs);
		Expression unwrappedArgs = unwrapTransformedArguments(transformedArgs, originalArgs);
		if (unwrappedArgs.equals(originalArgs))
		{
			if (log.isDebugEnabled())
			{
				log.debug("allowed constructor call " + exp);
			}
			return exp;
		}
		
		ConstructorCallExpression transformedCall = new ConstructorCallExpression(
				exp.getType(), unwrappedArgs);
		if (log.isDebugEnabled())
		{
			log.debug("transformed constructor call " + transformedCall);
		}
		return transformedCall;
	}
	
	return super.transformConstructorCall(exp);
}
 
Example #26
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ClassNode getMemberClassValue(AnnotationNode node, String name, ClassNode defaultValue) {
    final Expression member = node.getMember(name);
    if (member != null) {
        if (member instanceof ClassExpression) {
            if (!isUndefined(member.getType())) return member.getType();
        } else if (member instanceof VariableExpression) {
            addError("Error expecting to find class value for '" + name + "' but found variable: " + member.getText() + ". Missing import?", node);
            return null;
        } else if (member instanceof ConstantExpression) {
            addError("Error expecting to find class value for '" + name + "' but found constant: " + member.getText() + "!", node);
            return null;
        }
    }
    return defaultValue;
}
 
Example #27
Source File: CategoryASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getTargetClass(SourceUnit source, AnnotationNode annotation) {
    Expression value = annotation.getMember("value");
    if (!(value instanceof ClassExpression)) {
        //noinspection ThrowableInstanceNeverThrown
        source.getErrorCollector().addErrorAndContinue("@groovy.lang.Category must define 'value' which is the class to apply this category to", annotation, source);
        return null;
    } else {
        ClassExpression ce = (ClassExpression) value;
        return ce.getType();
    }
}
 
Example #28
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitArrayAttributes(final AnnotationNode an, final Map<String, ListExpression> arrayAttr, final AnnotationVisitor av) {
    if (arrayAttr.isEmpty()) return;
    for (Map.Entry<String, ListExpression> entry : arrayAttr.entrySet()) {
        AnnotationVisitor av2 = av.visitArray(entry.getKey());
        List<Expression> values = entry.getValue().getExpressions();
        if (!values.isEmpty()) {
            int arrayElementType = determineCommonArrayType(values);
            for (Expression exprChild : values) {
                visitAnnotationArrayElement(exprChild, arrayElementType, av2);
            }
        }
        av2.visitEnd();
    }
}
 
Example #29
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void create(FieldNode fieldNode, final Expression initExpr) {
    final BlockStatement body = new BlockStatement();
    if (fieldNode.isStatic()) {
        addHolderClassIdiomBody(body, fieldNode, initExpr);
    } else if (fieldNode.isVolatile()) {
        addDoubleCheckedLockingBody(body, fieldNode, initExpr);
    } else {
        addNonThreadSafeBody(body, fieldNode, initExpr);
    }
    addMethod(fieldNode, body, fieldNode.getType());
}
 
Example #30
Source File: FindMethodUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Find and add method usage if the given type contains method corresponding
 * with the given method call. In other words we are looking for the method
 * declaration in the given type and the method we are looking for is based
 * on given method call. Might return null if the type can't be interfered
 * properly and thus we are not able to find correct method - this is typical
 * for dynamic types.
 *
 * @param type where we are looking for the specific method
 * @param methodCall method call for which we want to find method in given
 * type or null if the type is dynamic
 */
private static MethodNode findMethod(ClassNode type, MethodCallExpression methodCall) {
    String findingMethod = methodCall.getMethodAsString();
    Expression arguments = methodCall.getArguments();
    
    if (!type.isResolved()) {
        type = type.redirect();
    }

    MethodNode method = type.tryFindPossibleMethod(findingMethod, arguments);
    if (method != null) {
        return method;
    }
    return findMostAccurateMethod(methodCall, type.getMethods(findingMethod));
}