org.codehaus.groovy.ast.stmt.BlockStatement Java Examples

The following examples show how to use org.codehaus.groovy.ast.stmt.BlockStatement. 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: ConstructorNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Return the first statement from the constructor code if it is a call to super or this, otherwise null.
 *
 * @param code
 * @return the first statement if a special call or null
 */
public static ConstructorCallExpression getFirstIfSpecialConstructorCall(Statement code) {
    if (code == null) return null;

    if (code instanceof BlockStatement) {
        final BlockStatement block = (BlockStatement) code;
        final List<Statement> statementList = block.getStatements();
        if (statementList.isEmpty()) return null;
        // handle blocks of blocks
        return getFirstIfSpecialConstructorCall(statementList.get(0));
    }

    if (!(code instanceof ExpressionStatement)) return null;

    Expression expression = ((ExpressionStatement) code).getExpression();
    if (!(expression instanceof ConstructorCallExpression)) return null;
    ConstructorCallExpression cce = (ConstructorCallExpression) expression;
    if (cce.isSpecialCall()) return cce;
    return null;
}
 
Example #2
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 #3
Source File: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected BlockStatement createBlockStatementForConstructor(final ClosureExpression expression, final ClassNode outerClass, final ClassNode thisClassNode) {
    BlockStatement block = new BlockStatement();
    // this block does not get a source position, because we don't
    // want this synthetic constructor to show up in corbertura reports
    VariableExpression outer = new VariableExpression(OUTER_INSTANCE, outerClass);
    outer.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(outer);
    VariableExpression thisObject = new VariableExpression(THIS_OBJECT, thisClassNode);
    thisObject.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(thisObject);
    TupleExpression conArgs = new TupleExpression(outer, thisObject);
    block.addStatement(
            new ExpressionStatement(
                    new ConstructorCallExpression(
                            ClassNode.SUPER,
                            conArgs)));
    return block;
}
 
Example #4
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void addDoubleCheckedLockingBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) {
    final Expression fieldExpr = varX(fieldNode);
    final VariableExpression localVar = localVarX(fieldNode.getName() + "_local");
    body.addStatement(declS(localVar, fieldExpr));
    body.addStatement(ifElseS(
            notNullX(localVar),
            returnS(localVar),
            new SynchronizedStatement(
                    syncTarget(fieldNode),
                    ifElseS(
                            notNullX(fieldExpr),
                            returnS(fieldExpr),
                            returnS(assignX(fieldExpr, initExpr))
                    )
            )
    ));
}
 
Example #5
Source File: NamedVariantASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean processExplicitNamedParam(final MethodNode mNode, final Parameter mapParam, final BlockStatement inner, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) {
    AnnotationNode namedParam = fromParam.getAnnotations(NAMED_PARAM_TYPE).get(0);
    boolean required = memberHasValue(namedParam, "required", true);
    if (getMemberStringValue(namedParam, "value") == null) {
        namedParam.addMember("value", constX(fromParam.getName()));
    }
    String name = getMemberStringValue(namedParam, "value");
    if (getMemberValue(namedParam, "type") == null) {
        namedParam.addMember("type", classX(fromParam.getType()));
    }
    if (hasDuplicates(mNode, propNames, name)) return false;
    // TODO: Check specified type is assignable from declared param type?
    //ClassNode type = getMemberClassValue(namedParam, "type");
    if (required) {
        if (fromParam.hasInitialExpression()) {
            addError("Error during " + NAMED_VARIANT + " processing. A required parameter can't have an initial value.", mNode);
            return false;
        }
        inner.addStatement(new AssertStatement(boolX(callX(varX(mapParam), "containsKey", args(constX(name)))),
                plusX(constX("Missing required named argument '" + name + "'. Keys found: "), callX(varX(mapParam), "keySet"))));
    }
    args.addExpression(propX(varX(mapParam), name));
    mapParam.addAnnotation(namedParam);
    fromParam.getAnnotations().remove(namedParam);
    return true;
}
 
Example #6
Source File: UnknownElementsIndexer.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected IStatus run(final IProgressMonitor monitor) {
    monitor.beginTask("Computing unknonwn element...", IProgressMonitor.UNKNOWN);
    overridenVariables.clear();
    unknownVaraibles.clear();

    final BlockStatement statementBlock = groovyCompilationUnit.getModuleNode().getStatementBlock();
    final VariablesVisitor variablesVisitor = new VariablesVisitor(statementBlock.getVariableScope());
    statementBlock.visit(variablesVisitor);
    final Map<String, Position> declaredExpressions = variablesVisitor.getDeclaredExpressions();
    Map<String, ScriptVariable> context = groovyCompilationUnit.getContext();
    for (final String variable : variablesVisitor.getVariableExpressions()) {
        if (!context.containsKey(variable) && !declaredExpressions.keySet().contains(variable)) {
            addUnknownVaraible(variable);
        }
    }
    for (final Entry<String, Position> declaredVariable : declaredExpressions.entrySet()) {
        if (context.containsKey(declaredVariable.getKey())) {
            addOverridenVariable(declaredVariable);
        }
    }
    return Status.OK_STATUS;
}
 
Example #7
Source File: CompletionProvider.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
private void populateItemsFromScope(ASTNode node, String namePrefix, List<CompletionItem> items) {
	Set<String> existingNames = new HashSet<>();
	ASTNode current = node;
	while (current != null) {
		if (current instanceof ClassNode) {
			ClassNode classNode = (ClassNode) current;
			populateItemsFromPropertiesAndFields(classNode.getProperties(), classNode.getFields(), namePrefix,
					existingNames, items);
			populateItemsFromMethods(classNode.getMethods(), namePrefix, existingNames, items);
		} else if (current instanceof MethodNode) {
			MethodNode methodNode = (MethodNode) current;
			populateItemsFromVariableScope(methodNode.getVariableScope(), namePrefix, existingNames, items);
		} else if (current instanceof BlockStatement) {
			BlockStatement block = (BlockStatement) current;
			populateItemsFromVariableScope(block.getVariableScope(), namePrefix, existingNames, items);
		}
		current = ast.getParent(current);
	}
	if (namePrefix.length() == 0) {
		isIncomplete = true;
	} else {
		populateTypes(node, namePrefix, existingNames, items);
	}
}
 
Example #8
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void createSoftSetter(FieldNode fieldNode, ClassNode type) {
    final BlockStatement body = new BlockStatement();
    final Expression fieldExpr = varX(fieldNode);
    final String name = getSetterName(fieldNode.getName().substring(1));
    final Parameter parameter = param(type, "value");
    final Expression paramExpr = varX(parameter);
    body.addStatement(ifElseS(
            notNullX(paramExpr),
            assignS(fieldExpr, ctorX(SOFT_REF, paramExpr)),
            assignS(fieldExpr, nullX())
    ));
    int visibility = ACC_PUBLIC;
    if (fieldNode.isStatic()) visibility |= ACC_STATIC;
    ClassNode declaringClass = fieldNode.getDeclaringClass();
    addGeneratedMethod(declaringClass, name, visibility, ClassHelper.VOID_TYPE, params(parameter), ClassNode.EMPTY_ARRAY, body);
}
 
Example #9
Source File: ClassNode.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void addStaticInitializerStatements(List<Statement> staticStatements, boolean fieldInit) {
    MethodNode method = getOrAddStaticConstructorNode();
    BlockStatement block = getCodeAsBlock(method);

    // while anything inside a static initializer block is appended
    // we don't want to append in the case we have a initialization
    // expression of a static field. In that case we want to add
    // before the other statements
    if (!fieldInit) {
        block.addStatements(staticStatements);
    } else {
        List<Statement> blockStatements = block.getStatements();
        staticStatements.addAll(blockStatements);
        blockStatements.clear();
        blockStatements.addAll(staticStatements);
    }
}
 
Example #10
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBlockStatement(final BlockStatement statement) {
    opt.push();
    boolean optAll = true;
    for (Statement stmt : statement.getStatements()) {
        opt.push();
        stmt.visit(this);
        optAll = optAll && opt.canOptimize();
        opt.pop(true);
    }
    if (statement.isEmpty()) {
        opt.chainCanOptimize(true);
        opt.pop(true);
    } else {
        opt.chainShouldOptimize(optAll);
        if (optAll) {
            addMeta(statement, opt);
        }
        opt.pop(optAll);
    }
}
 
Example #11
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustMethod(MethodNode mn, boolean includeGenerated) {
    BlockStatement newCode = getCodeAsBlock(mn);
    if (mn.getParameters().length == 0) return;
    boolean generated = isGenerated(mn);
    int startingIndex = 0;
    if (!includeGenerated && generated) return;
    if (isMarkedAsProcessed(mn)) return;
    if (mn instanceof ConstructorNode) {
        // some transform has been here already and we assume it knows what it is doing
        if (mn.getFirstStatement() instanceof BytecodeSequence) return;
        // ignore any constructors calling this(...) or super(...)
        ConstructorCallExpression cce = ConstructorNodeUtils.getFirstIfSpecialConstructorCall(mn.getCode());
        if (cce != null) {
            if (generated) {
                return;
            } else {
                startingIndex = 1; // skip over this/super() call
            }
        }
    }
    for (Parameter p : mn.getParameters()) {
        if (ClassHelper.isPrimitiveType(p.getType())) continue;
        newCode.getStatements().add(startingIndex, ifS(isNullX(varX(p)), makeThrowStmt(p.getName())));
    }
    mn.setCode(newCode);
}
 
Example #12
Source File: StaticTypesLambdaWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addDeserializeLambdaMethod() {
    ClassNode enclosingClass = controller.getClassNode();
    Parameter[] parameters = createDeserializeLambdaMethodParams();
    if (enclosingClass.hasMethod("$deserializeLambda$", parameters)) {
        return;
    }

    Statement code = block(
            declS(localVarX("enclosingClass", OBJECT_TYPE), classX(enclosingClass)),
            ((BlockStatement) new AstStringCompiler().compile(
                    "return enclosingClass" +
                            ".getDeclaredMethod(\"\\$deserializeLambda_${serializedLambda.getImplClass().replace('/', '$')}\\$\", serializedLambda.getClass())" +
                            ".invoke(null, serializedLambda)"
            ).get(0)).getStatements().get(0)
    );

    enclosingClass.addSyntheticMethod(
            "$deserializeLambda$",
            ACC_PRIVATE | ACC_STATIC,
            OBJECT_TYPE,
            parameters,
            ClassNode.EMPTY_ARRAY,
            code);
}
 
Example #13
Source File: DependenciesVisitor.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Override
public void visitArgumentlistExpression(final ArgumentListExpression argumentListExpression) {
    if (inDependenciesBlock) {
        final List<Expression> expressions = argumentListExpression.getExpressions();

        if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) {
            final ClosureExpression closureExpression = (ClosureExpression) expressions.get(0);
            if (closureExpression.getCode() instanceof BlockStatement) {
                final BlockStatement blockStatement = (BlockStatement) closureExpression.getCode();
                final List<Statement> statements = blockStatement.getStatements();
                for (final Statement statement : statements) {
                    addDependencyFromStatement(statement);
                }
            }
        }
    }

    super.visitArgumentlistExpression(argumentListExpression);
}
 
Example #14
Source File: EnumCompletionVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Add map and no-arg constructor or mirror those of the superclass (i.e. base enum).
 */
private static void addImplicitConstructors(ClassNode enumClass, boolean aic) {
    if (aic) {
        ClassNode sn = enumClass.getSuperClass();
        List<ConstructorNode> sctors = new ArrayList<ConstructorNode>(sn.getDeclaredConstructors());
        if (sctors.isEmpty()) {
            addMapConstructors(enumClass);
        } else {
            for (ConstructorNode constructorNode : sctors) {
                ConstructorNode init = new ConstructorNode(ACC_PUBLIC, constructorNode.getParameters(), ClassNode.EMPTY_ARRAY, new BlockStatement());
                enumClass.addConstructor(init);
            }
        }
    } else {
        addMapConstructors(enumClass);
    }
}
 
Example #15
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the block's last statement is a return or throw
 */
private boolean returningBlock(Statement block) {
    if (block instanceof ReturnStatement || block instanceof  ThrowStatement) {
        return true;
    }
    if (!(block instanceof BlockStatement)) {
        return false;
    }
    BlockStatement bs = (BlockStatement) block;
    if (bs.getStatements().size() == 0) {
        return false;
    }
    Statement last = DefaultGroovyMethods.last(bs.getStatements());
    if (last instanceof ReturnStatement || last instanceof ThrowStatement) {
        return true;
    }
    return false;
}
 
Example #16
Source File: TraitASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MethodNode createInitMethod(final boolean isStatic, final ClassNode cNode, final ClassNode helper) {
    MethodNode initializer = new MethodNode(
            isStatic?Traits.STATIC_INIT_METHOD:Traits.INIT_METHOD,
            ACC_STATIC | ACC_PUBLIC | ACC_SYNTHETIC,
            ClassHelper.VOID_TYPE,
            new Parameter[]{createSelfParameter(cNode, isStatic)},
            ClassNode.EMPTY_ARRAY,
            new BlockStatement()
    );
    helper.addMethod(initializer);

    // Cannot add static compilation of init method because of GROOVY-7217, see example 2 of test case
    //AnnotationNode an = new AnnotationNode(TraitComposer.COMPILESTATIC_CLASSNODE);
    //initializer.addAnnotation(an);
    //cNode.addTransform(StaticCompileTransformation.class, an);

    return initializer;
}
 
Example #17
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public Statement createPropGetter(PropertyNode pNode) {
    FieldNode fNode = pNode.getField();
    BlockStatement body = new BlockStatement();
    final ClassNode fieldType = fNode.getType();
    final Statement statement;
    if (fieldType.isArray() || implementsCloneable(fieldType)) {
        statement = createGetterBodyArrayOrCloneable(fNode);
    } else if (derivesFromDate(fieldType)) {
        statement = createGetterBodyDate(fNode);
    } else {
        statement = createGetterBodyDefault(fNode);
    }
    body.addStatement(statement);
    return body;
}
 
Example #18
Source File: RuleVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitClosureExpression(ClosureExpression expression) {
    if (inputs == null) {
        inputs = ImmutableListMultimap.builder();
        try {
            accessVariable = new VariableExpression(ACCESS_HOLDER_FIELD, ACCESS_API_TYPE);

            super.visitClosureExpression(expression);

            BlockStatement code = (BlockStatement) expression.getCode();
            code.setNodeMetaData(AST_NODE_METADATA_INPUTS_KEY, inputs.build());
            accessVariable.setClosureSharedVariable(true);
            StaticMethodCallExpression getAccessCall = new StaticMethodCallExpression(CONTEXTUAL_INPUT_TYPE, GET_ACCESS, ArgumentListExpression.EMPTY_ARGUMENTS);
            DeclarationExpression variableDeclaration = new DeclarationExpression(accessVariable, new Token(Types.ASSIGN, "=", -1, -1), getAccessCall);
            code.getStatements().add(0, new ExpressionStatement(variableDeclaration));
            code.getVariableScope().putDeclaredVariable(accessVariable);
        } finally {
            inputs = null;
        }
    } else {
        expression.getVariableScope().putReferencedLocalVariable(accessVariable);
        super.visitClosureExpression(expression);
    }
}
 
Example #19
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private CatchStatement createCatchBlockForOuterNewTryCatchStatement(String primaryExcName) {
    // { ... }
    BlockStatement blockStatement = new BlockStatement();
    String tExcName = this.genTExcName();

    // #primaryExc = #t;
    ExpressionStatement primaryExcAssignStatement =
            new ExpressionStatement(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(tExcName)));
    astBuilder.appendStatementsToBlockStatement(blockStatement, primaryExcAssignStatement);

    // throw #t;
    ThrowStatement throwTExcStatement = new ThrowStatement(new VariableExpression(tExcName));
    astBuilder.appendStatementsToBlockStatement(blockStatement, throwTExcStatement);

    // Throwable #t
    Parameter tExcParameter = new Parameter(ClassHelper.make(Throwable.class), tExcName);

    return new CatchStatement(tExcParameter, blockStatement);
}
 
Example #20
Source File: AstStringCompiler.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the String source to {@link java.util.List} of {@link ASTNode}.
 *
 * @param script
 *      a Groovy script in String form
 * @param compilePhase
 *      the int based CompilePhase to compile it to.
 * @param statementsOnly
 * @return {@link java.util.List} of {@link ASTNode}
 */
public List<ASTNode> compile(String script, CompilePhase compilePhase, boolean statementsOnly) {
    final String scriptClassName = makeScriptClassName();
    GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptClassName + ".groovy", "/groovy/script");
    CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.getCodeSource(),
            AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) GroovyClassLoader::new));
    cu.addSource(codeSource.getName(), script);
    cu.compile(compilePhase.getPhaseNumber());

    // collect all the ASTNodes into the result, possibly ignoring the script body if desired
    List<ASTNode> result = cu.getAST().getModules().stream().reduce(new LinkedList<>(), (acc, node) -> {
        BlockStatement statementBlock = node.getStatementBlock();
        if (null != statementBlock) {
            acc.add(statementBlock);
        }
        acc.addAll(
                node.getClasses().stream()
                    .filter(c -> !(statementsOnly && scriptClassName.equals(c.getName())))
                    .collect(Collectors.toList())
        );

        return acc;
    }, (o1, o2) -> o1);

    return result;
}
 
Example #21
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createCopyWith(final ClassNode cNode, final List<PropertyNode> pList) {
    BlockStatement body = new BlockStatement();
    body.addStatement(ifS(
            orX(
                    equalsNullX(varX("map", ClassHelper.MAP_TYPE)),
                    eqX(callX(varX("map", HMAP_TYPE), "size"), constX(0))
            ),
            returnS(varX("this", cNode))
    ));
    body.addStatement(declS(localVarX("dirty", ClassHelper.boolean_TYPE), ConstantExpression.PRIM_FALSE));
    body.addStatement(declS(localVarX("construct", HMAP_TYPE), ctorX(HMAP_TYPE)));

    // Check for each property
    for (final PropertyNode pNode : pList) {
        body.addStatement(createCheckForProperty(pNode));
    }

    body.addStatement(returnS(ternaryX(
            isTrueX(varX("dirty", ClassHelper.boolean_TYPE)),
            ctorX(cNode, args(varX("construct", HMAP_TYPE))),
            varX("this", cNode)
    )));

    final ClassNode clonedNode = cNode.getPlainNodeReference();

    addGeneratedMethod(cNode, COPY_WITH_METHOD,
            ACC_PUBLIC | ACC_FINAL,
            clonedNode,
            params(new Parameter(new ClassNode(Map.class), "map")),
            null,
            body);
}
 
Example #22
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createCloneSerialization(ClassNode cNode) {
    final BlockStatement body = new BlockStatement();
    // def baos = new ByteArrayOutputStream()
    final Expression baos = localVarX("baos");
    body.addStatement(declS(baos, ctorX(BAOS_TYPE)));

    // baos.withObjectOutputStream{ it.writeObject(this) }
    MethodCallExpression writeObject = callX(castX(OOS_TYPE, varX("it")), "writeObject", varX("this"));
    writeObject.setImplicitThis(false);
    ClosureExpression writeClos = closureX(block(stmt(writeObject)));
    writeClos.setVariableScope(new VariableScope());
    body.addStatement(stmt(callX(baos, "withObjectOutputStream", args(writeClos))));

    // def bais = new ByteArrayInputStream(baos.toByteArray())
    final Expression bais = localVarX("bais");
    body.addStatement(declS(bais, ctorX(BAIS_TYPE, args(callX(baos, "toByteArray")))));

    // return bais.withObjectInputStream(getClass().classLoader){ (<type>) it.readObject() }
    MethodCallExpression readObject = callX(castX(OIS_TYPE, varX("it")), "readObject");
    readObject.setImplicitThis(false);
    ClosureExpression readClos = closureX(block(stmt(castX(GenericsUtils.nonGeneric(cNode), readObject))));
    readClos.setVariableScope(new VariableScope());
    Expression classLoader = callX(callThisX("getClass"), "getClassLoader");
    body.addStatement(returnS(callX(bais, "withObjectInputStream", args(classLoader, readClos))));

    new VariableScopeVisitor(sourceUnit, true).visitClass(cNode);
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, body);
}
 
Example #23
Source File: MapConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void processProps(AbstractASTTransformation xform, AnnotationNode anno, ClassNode cNode, PropertyHandler handler, boolean allNames, List<String> excludes, List<String> includes, List<PropertyNode> superList, Parameter map, BlockStatement inner) {
    for (PropertyNode pNode : superList) {
        String name = pNode.getName();
        if (shouldSkipUndefinedAware(name, excludes, includes, allNames)) continue;
        Statement propInit = handler.createPropInit(xform, anno, cNode, pNode, map);
        if (propInit != null) {
            inner.addStatement(propInit);
        }
    }
}
 
Example #24
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createSoftGetter(FieldNode fieldNode, Expression initExpr, ClassNode type) {
    final BlockStatement body = new BlockStatement();
    final Expression fieldExpr = varX(fieldNode);
    final Expression resExpr = localVarX("_result", type);
    final MethodCallExpression callExpression = callX(fieldExpr, "get");
    callExpression.setSafe(true);
    body.addStatement(declS(resExpr, callExpression));

    final Statement mainIf = ifElseS(notNullX(resExpr), stmt(resExpr), block(
            assignS(resExpr, initExpr),
            assignS(fieldExpr, ctorX(SOFT_REF, resExpr)),
            stmt(resExpr)));

    if (fieldNode.isVolatile()) {
        body.addStatement(ifElseS(
                notNullX(resExpr),
                stmt(resExpr),
                new SynchronizedStatement(syncTarget(fieldNode), block(
                        assignS(resExpr, callExpression),
                        mainIf)
                )
        ));
    } else {
        body.addStatement(mainIf);
    }
    addMethod(fieldNode, body, type);
}
 
Example #25
Source File: TupleConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static BlockStatement processArgsBlock(ClassNode cNode, VariableExpression namedArgs) {
    BlockStatement block = new BlockStatement();
    for (PropertyNode pNode : cNode.getProperties()) {
        if (pNode.isStatic()) continue;

        // if namedArgs.containsKey(propertyName) setProperty(propertyName, namedArgs.get(propertyName));
        Statement ifStatement = ifS(
                callX(namedArgs, "containsKey", constX(pNode.getName())),
                assignS(varX(pNode), propX(namedArgs, pNode.getName())));
        block.addStatement(ifStatement);
    }
    block.addStatement(stmt(callX(CHECK_METHOD_TYPE, "checkPropNames", args(varX("this"), namedArgs))));
    return block;
}
 
Example #26
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addGetter(FieldNode fNode, ClassNode componentType) {
    ClassNode cNode = fNode.getDeclaringClass();
    BlockStatement body = new BlockStatement();
    Parameter[] params = new Parameter[1];
    params[0] = new Parameter(ClassHelper.int_TYPE, "index");
    body.addStatement(stmt(indexX(varX(fNode), varX(params[0]))));
    addGeneratedMethod(cNode, makeName(fNode, "get"), getModifiers(fNode), componentType, params, null, body);
}
 
Example #27
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSetter(FieldNode fNode, ClassNode componentType) {
    ClassNode cNode = fNode.getDeclaringClass();
    BlockStatement body = new BlockStatement();
    Parameter[] theParams = params(
            new Parameter(ClassHelper.int_TYPE, "index"),
            new Parameter(componentType, "value"));
    body.addStatement(assignS(indexX(varX(fNode), varX(theParams[0])), varX(theParams[1])));
    addGeneratedMethod(cNode, getSetterName(fNode.getName()), getModifiers(fNode), ClassHelper.VOID_TYPE, theParams, null, body);
}
 
Example #28
Source File: SortableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createCompareToMethodBody(List<PropertyNode> properties, boolean reversed) {
    List<Statement> statements = new ArrayList<Statement>();

    // if (this.is(other)) return 0;
    statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0))));

    if (properties.isEmpty()) {
        // perhaps overkill but let compareTo be based on hashes for commutativity
        // return this.hashCode() <=> other.hashCode()
        statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode")));
        statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode")));
        statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed)));
    } else {
        // int value = 0;
        statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0)));
        for (PropertyNode property : properties) {
            String propName = property.getName();
            // value = this.prop <=> other.prop;
            statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed)));
            // if (value != 0) return value;
            statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE))));
        }
        // objects are equal
        statements.add(returnS(constX(0)));
    }

    final BlockStatement body = new BlockStatement();
    body.addStatements(statements);
    return body;
}
 
Example #29
Source File: RulesVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void visitBlockStatement(BlockStatement block) {
    block.setNodeMetaData(AST_NODE_METADATA_KEY, true);

    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example #30
Source File: ConstraintInputIndexer.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected void addRefrencedInputs(final BlockStatement blockStatement) {
    final Iterator<Variable> referencedClassVariablesIterator = blockStatement.getVariableScope().getReferencedClassVariablesIterator();
    while (referencedClassVariablesIterator.hasNext()) {
        final Variable variable = referencedClassVariablesIterator.next();
        for (final ContractInput in : inputs) {
            if (in.getName().equals(variable.getName())) {
                referencedInputs.add(variable.getName());
            }
        }
    }
}