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

The following examples show how to use org.codehaus.groovy.ast.expr.ConstantExpression. 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: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private MethodNode addSyntheticMethodForDGSM(MethodNode mn) {
    Parameter[] parameters = removeFirstParameter(mn.getParameters());
    ArgumentListExpression args = args(parameters);
    args.getExpressions().add(0, ConstantExpression.NULL);

    MethodNode syntheticMethodNode = controller.getClassNode().addSyntheticMethod(
            "dgsm$$" + mn.getParameters()[0].getType().getName().replace(".", "$") + "$$" + mn.getName(),
            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
            mn.getReturnType(),
            parameters,
            ClassNode.EMPTY_ARRAY,
            block(
                    returnS(
                            callX(new ClassExpression(mn.getDeclaringClass()), mn.getName(), args)
                    )
            )
    );

    syntheticMethodNode.addAnnotation(new AnnotationNode(GENERATED_TYPE));
    syntheticMethodNode.addAnnotation(new AnnotationNode(COMPILE_STATIC_TYPE));

    return syntheticMethodNode;
}
 
Example #2
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 #3
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression annotationValueToExpression (Object value) {
    if (value == null || value instanceof String || value instanceof Number || value instanceof Character || value instanceof Boolean)
        return new ConstantExpression(value);

    if (value instanceof Class)
        return new ClassExpression(ClassHelper.makeWithoutCaching((Class<?>)value));

    if (value.getClass().isArray()) {
        ListExpression elementExprs = new ListExpression();
        int len = Array.getLength(value);
        for (int i = 0; i != len; ++i)
            elementExprs.addExpression(annotationValueToExpression(Array.get(value, i)));
        return elementExprs;
    }

    return null;
}
 
Example #4
Source File: MacroCallTransformingVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to call given macroMethod
 * @param call MethodCallExpression before the transformation
 * @param macroMethod a macro method candidate
 * @param macroArguments arguments to pass to
 * @return true if call succeeded and current call was transformed
 */
private boolean tryMacroMethod(MethodCallExpression call, ExtensionMethodNode macroMethod, Object[] macroArguments) {
    Expression result = (Expression) InvokerHelper.invokeStaticMethod(
        macroMethod.getExtensionMethodNode().getDeclaringClass().getTypeClass(),
        macroMethod.getName(),
        macroArguments
    );

    if (result == null) {
        // Allow macro methods to return null as an indicator that they didn't match a method call
        return false;
    }

    call.setObjectExpression(MACRO_STUB_INSTANCE);
    call.setMethod(new ConstantExpression(MACRO_STUB_METHOD_NAME));

    // TODO check that we reset everything here
    call.setSpreadSafe(false);
    call.setSafe(false);
    call.setImplicitThis(false);
    call.setArguments(result);
    call.setGenericsTypes(GenericsType.EMPTY_ARRAY);

    return true;
}
 
Example #5
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Statement createConstructorStatementGuarded(FieldNode fNode, Parameter namedArgsMap, List<String> knownImmutables, List<String> knownImmutableClasses, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = assignS(fieldExpr, createCheckImmutable(fNode, param, knownImmutables, knownImmutableClasses));
    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, createCheckImmutable(fNode, initExpr, knownImmutables, knownImmutableClasses));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example #6
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean isEmpty(SourceUnit source) {
    if (!source.getAST().getMethods().isEmpty()) {
        return false;
    }
    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    if (statements.size() > 1) {
        return false;
    }
    if (statements.isEmpty()) {
        return true;
    }

    Statement statement = statements.get(0);
    if (statement instanceof ReturnStatement) {
        ReturnStatement returnStatement = (ReturnStatement) statement;
        if (returnStatement.getExpression() instanceof ConstantExpression) {
            ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression();
            if (constantExpression.getValue() == null) {
                return true;
            }
        }
    }

    return false;
}
 
Example #7
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 #8
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 #9
Source File: TypeResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ClassNode resolveType(AstPath path, FileObject fo) {
    final ASTNode leaf = path.leaf();
    final ASTNode leafParent = path.leafParent();

    if (leaf instanceof VariableExpression) {
        return resolveType(path, (VariableExpression) leaf, fo);
    }
    if (leaf instanceof ConstantExpression) {
        if (leafParent instanceof MethodCallExpression) {
            return resolveMethodType(path, (MethodCallExpression) leafParent, fo);
        }
        if (leafParent instanceof PropertyExpression) {
            return resolveVariableType(path, (PropertyExpression) leafParent, fo);
        }
    }

    return null;
}
 
Example #10
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 #11
Source File: AstBuilderTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean handleTargetMethodCallExpression(MethodCallExpression call) {
    ClosureExpression closureExpression = getClosureArgument(call);
    List<Expression> otherArgs = getNonClosureArguments(call);
    String source = convertClosureToSource(closureExpression);

    // parameter order is build(CompilePhase, boolean, String)
    otherArgs.add(new ConstantExpression(source));
    call.setArguments(new ArgumentListExpression(otherArgs));
    call.setMethod(new ConstantExpression("buildFromBlock"));
    call.setSpreadSafe(false);
    call.setSafe(false);
    call.setImplicitThis(false);
    
    return false;
}
 
Example #12
Source File: InvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected String getMethodName(final Expression message) {
    String methodName = null;
    if (message instanceof CastExpression) {
        CastExpression msg = (CastExpression) message;
        if (msg.getType() == ClassHelper.STRING_TYPE) {
            final Expression methodExpr = msg.getExpression();
            if (methodExpr instanceof ConstantExpression) {
                methodName = methodExpr.getText();
            }
        }
    }

    if (methodName == null && message instanceof ConstantExpression) {
        ConstantExpression constantExpression = (ConstantExpression) message;
        methodName = constantExpression.getText();
    }
    return methodName;
}
 
Example #13
Source File: GroovydocManager.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void attachGroovydocAnnotation(ASTNode node, String docCommentNodeText) {
    if (!runtimeGroovydocEnabled) {
        return;
    }

    if (!(node instanceof AnnotatedNode)) {
        return;
    }

    if (!docCommentNodeText.startsWith(RUNTIME_GROOVYDOC_PREFIX)) {
        return;
    }

    AnnotatedNode annotatedNode = (AnnotatedNode) node;
    AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(Groovydoc.class));
    annotationNode.addMember(VALUE, new ConstantExpression(docCommentNodeText));
    annotatedNode.addAnnotation(annotationNode);
}
 
Example #14
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void evaluateLogicalAndExpression(final BinaryExpression expression) {
    AsmClassGenerator acg = controller.getAcg();
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();

    expression.getLeftExpression().visit(acg);
    operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
    Label falseCase = operandStack.jump(IFEQ);

    expression.getRightExpression().visit(acg);
    operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
    operandStack.jump(IFEQ, falseCase);

    ConstantExpression.PRIM_TRUE.visit(acg);
    Label trueCase = new Label();
    mv.visitJumpInsn(GOTO, trueCase);

    mv.visitLabel(falseCase);
    ConstantExpression.PRIM_FALSE.visit(acg);

    mv.visitLabel(trueCase);
    operandStack.remove(1); // have to remove 1 because of the GOTO
}
 
Example #15
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression transformMapEntryExpression(MapEntryExpression me, ClassNode constructorCallType) {
    Expression key = me.getKeyExpression();
    Expression value = me.getValueExpression();
    ModuleNode module = currentClass.getModule();
    if (module != null && key instanceof ConstantExpression) {
        Map<String, ImportNode> importNodes = module.getStaticImports();
        if (importNodes.containsKey(key.getText())) {
            ImportNode importNode = importNodes.get(key.getText());
            if (importNode.getType().equals(constructorCallType)) {
                String newKey = importNode.getFieldName();
                return new MapEntryExpression(new ConstantExpression(newKey), value.transformExpression(this));
            }
        }
    }
    return me;
}
 
Example #16
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 #17
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean isEmpty(SourceUnit source) {
    if (!source.getAST().getMethods().isEmpty()) {
        return false;
    }
    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    if (statements.size() > 1) {
        return false;
    }
    if (statements.isEmpty()) {
        return true;
    }

    Statement statement = statements.get(0);
    if (statement instanceof ReturnStatement) {
        ReturnStatement returnStatement = (ReturnStatement) statement;
        if (returnStatement.getExpression() instanceof ConstantExpression) {
            ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression();
            if (constantExpression.getValue() == null) {
                return true;
            }
        }
    }

    return false;
}
 
Example #18
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<String> getValueStringList(ListExpression listExpression) {
    List<String> list = new ArrayList<>();
    for (Expression itemExpr : listExpression.getExpressions()) {
        if (itemExpr instanceof ConstantExpression) {
            Object value = ((ConstantExpression) itemExpr).getValue();
            if (value != null) list.add(value.toString());
        }
    }
    return list;
}
 
Example #19
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkConstantTypeIfNotMethodNameOrProperty(final Expression expr) {
    if (expr instanceof ConstantExpression) {
        if (!"java.lang.String".equals(expr.getType().getName())) {
            expr.visit(this);
        }
    } else {
        expr.visit(this);
    }
}
 
Example #20
Source File: ExpressionUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression findConstant(final FieldNode fn) {
    if (fn != null && !fn.isEnum() && fn.isStatic() && fn.isFinal()
            && fn.getInitialValueExpression() instanceof ConstantExpression) {
        return fn.getInitialValueExpression();
    }
    return null;
}
 
Example #21
Source File: ToStringASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void appendCommaIfNotFirst(BlockStatement body, Expression result, VariableExpression first) {
    // if ($toStringFirst) $toStringFirst = false else result.append(", ")
    body.addStatement(ifElseS(
            first,
            assignS(first, ConstantExpression.FALSE),
            appendS(result, constX(", "))));
}
 
Example #22
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void pushDynamicName(Expression name) {
    if (name instanceof ConstantExpression) {
        ConstantExpression ce = (ConstantExpression) name;
        Object value = ce.getValue();
        if (value instanceof String) {
            pushConstant(ce);
            return;
        }
    }
    new CastExpression(ClassHelper.STRING_TYPE, name).visit(controller.getAcg());
}
 
Example #23
Source File: IndyBinHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void writePostOrPrefixMethod(int op, String method, Expression expression, Expression orig) {
    getController().getInvocationWriter().makeCall(
            orig, EmptyExpression.INSTANCE, 
            new ConstantExpression(method), 
            MethodCallExpression.NO_ARGUMENTS, 
            InvocationWriter.invokeMethod, 
            false, false, false);
}
 
Example #24
Source File: DetectorTransform.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example #25
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private BlockStatement createFinallyBlockForNewTryCatchStatement(String primaryExcName, String firstResourceIdentifierName) {
    BlockStatement finallyBlock = new BlockStatement();

    // primaryExc != null
    BooleanExpression conditionExpression =
            new BooleanExpression(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1),
                            new ConstantExpression(null)));

    // try-catch statement
    TryCatchStatement newTryCatchStatement =
            new TryCatchStatement(
                    astBuilder.createBlockStatement(this.createCloseResourceStatement(firstResourceIdentifierName)), // { Identifier?.close(); }
                    EmptyStatement.INSTANCE);


    String suppressedExcName = this.genSuppressedExcName();
    newTryCatchStatement.addCatch(
            // catch (Throwable #suppressedExc) { .. }
            new CatchStatement(
                    new Parameter(ClassHelper.make(Throwable.class), suppressedExcName),
                    astBuilder.createBlockStatement(this.createAddSuppressedStatement(primaryExcName, suppressedExcName)) // #primaryExc.addSuppressed(#suppressedExc);
            )
    );

    // if (#primaryExc != null) { ... }
    IfStatement ifStatement =
            new IfStatement(
                    conditionExpression,
                    newTryCatchStatement,
                    this.createCloseResourceStatement(firstResourceIdentifierName) // Identifier?.close();
            );
    astBuilder.appendStatementsToBlockStatement(finallyBlock, ifStatement);

    return astBuilder.createBlockStatement(finallyBlock);
}
 
Example #26
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Macro
public static Expression macro(MacroContext macroContext, PropertyExpression phaseExpression, ConstantExpression asIsConstantExpression, ClosureExpression closureExpression) {
    if (closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
        macroContext.getSourceUnit().addError(new SyntaxException("Macro closure arguments are not allowed" + '\n', closureExpression));
        return macroContext.getCall();
    }

    final String source;
    try {
        source = ClosureUtils.convertClosureToSource(macroContext.getSourceUnit().getSource(), closureExpression);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();

    Boolean asIs = (Boolean) asIsConstantExpression.getValue();

    return callX(
            propX(classX(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"),
            "macro",
            args(
                    phaseExpression != null ? phaseExpression : constX(null),
                    asIsConstantExpression,
                    constX(source),
                    buildSubstitutions(macroContext.getSourceUnit(), closureExpression),
                    classX(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false))
            )
    );
}
 
Example #27
Source File: MemberSignatureParser.java    From groovy with Apache License 2.0 5 votes vote down vote up
static FieldNode createFieldNode(FieldStub field, AsmReferenceResolver resolver, DecompiledClassNode owner) {
    final ClassNode[] type = {resolver.resolveType(Type.getType(field.desc))};
    if (field.signature != null) {
        new SignatureReader(field.signature).accept(new TypeSignatureParser(resolver) {
            @Override
            void finished(ClassNode result) {
                type[0] = applyErasure(result, type[0]);
            }
        });
    }
    ConstantExpression value = field.value == null ? null : new ConstantExpression(field.value);
    return new FieldNode(field.fieldName, field.accessModifiers, type[0], owner, value);
}
 
Example #28
Source File: DetectorTransform.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example #29
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addGrabResolverAsStaticInitIfNeeded(ClassNode grapeClassNode, AnnotationNode node,
                                                  List<Statement> grabResolverInitializers, Map<String, Object> grabResolverMap) {
    if ((node.getMember("initClass") == null)
        || (node.getMember("initClass") == ConstantExpression.TRUE))
    {
        MapExpression resolverArgs = new MapExpression();
        for (Map.Entry<String, Object> next : grabResolverMap.entrySet()) {
            resolverArgs.addMapEntryExpression(constX(next.getKey()), constX(next.getValue()));
        }
        grabResolverInitializers.add(stmt(callX(grapeClassNode, "addResolver", args(resolverArgs))));
    }
}
 
Example #30
Source File: DetectorTransform.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}