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

The following examples show how to use org.codehaus.groovy.ast.expr.VariableExpression. 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: GroovydocVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
    if (currentClassDoc.isScript()) {
        if (hasAnno(expression, "Field")) {
            VariableExpression varx = expression.getVariableExpression();
            SimpleGroovyFieldDoc field = new SimpleGroovyFieldDoc(varx.getName(), currentClassDoc);
            field.setType(new SimpleGroovyType(makeType(varx.getType())));
            int mods = varx.getModifiers();
            processModifiers(field, varx, mods);
            boolean isProp = (mods & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)) == 0;
            if (isProp) {
                currentClassDoc.addProperty(field);
            } else {
                currentClassDoc.add(field);
            }
        }
    }
    super.visitDeclarationExpression(expression);
}
 
Example #2
Source File: PicocliScriptASTTransformation.java    From picocli with Apache License 2.0 6 votes vote down vote up
private void changeBaseScriptTypeFromDeclaration(final SourceUnit source, final DeclarationExpression de, final AnnotationNode node) {
    if (de.isMultipleAssignmentDeclaration()) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", de);
        return;
    }

    ClassNode cNode = de.getDeclaringClass();
    ClassNode baseScriptType = de.getVariableExpression().getType().getPlainNodeReference();
    if (baseScriptType.isScript()) {
        if (!(de.getRightExpression() instanceof EmptyExpression)) {
            addError("Annotation " + MY_TYPE_NAME + " not supported with variable assignment.", de);
            return;
        }
        de.setRightExpression(new VariableExpression("this"));
    } else {
        baseScriptType = BASE_SCRIPT_TYPE;
    }
    Expression value = node.getMember("value");
    if (value != null) {
        addError("Annotation " + MY_TYPE_NAME + " cannot have member 'value' if used on a declaration.", value);
        return;
    }


    changeBaseScriptType(source, de, cNode, baseScriptType, node);
}
 
Example #3
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_not_add_to_unknonwn_variables_a_variable_declared_but_not_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);

    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getUnknownVaraibles()).isEmpty();
}
 
Example #4
Source File: ProcessVariableRenamer.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final Variable accessedVar = expression.getAccessedVariable();
    // look for dynamic variables since the parameters already have the
    // new names, the actual references to the parameters are using the
    // old names
    if (accessedVar instanceof DynamicVariable) {
        final String newName = findReplacement(accessedVar.getName());
        if (newName != null) {
            ReplaceEdit replaceEdit = new ReplaceEdit(expression.getStart(), expression.getLength(), newName);
            try {
                edits.addChild(replaceEdit);
            }catch (MalformedTreeException e) {
                BonitaStudioLog.error(e);
            }
        }
    }
}
 
Example #5
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 #6
Source File: SandboxCpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
@Override
protected void visitAssignmentOrCast(final VariableExpression varExp, final Expression rhs) {
    if (SandboxTransformer.mightBePositionalArgumentConstructor(varExp)) {
        makeNode("sandboxCastOrCoerce", new Runnable() {
            @Override
            public void run() {
                loc(varExp);
                visit(rhs);
                literal(varExp.getType());
                literal(false);
                literal(true);
                literal(false);
            }
        });
    } else {
        super.visitAssignmentOrCast(varExp, rhs);
    }
}
 
Example #7
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_add_to_overriden_variables_a_variable_declared_and_already_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);
    Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>();
    context.put("declaredVar", null);
    when(groovyCompilationUnit.getContext()).thenReturn(context);
    
    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getOverridenVariables()).containsExactly(entry("declaredVar", new Position(0)));
}
 
Example #8
Source File: BaseScriptASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void changeBaseScriptTypeFromDeclaration(final DeclarationExpression de, final AnnotationNode node) {
    if (de.isMultipleAssignmentDeclaration()) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", de);
        return;
    }

    if (!(de.getRightExpression() instanceof EmptyExpression)) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with variable assignment.", de);
        return;
    }
    Expression value = node.getMember("value");
    if (value != null) {
        addError("Annotation " + MY_TYPE_NAME + " cannot have member 'value' if used on a declaration.", value);
        return;
    }

    ClassNode cNode = de.getDeclaringClass();
    ClassNode baseScriptType = de.getVariableExpression().getType().getPlainNodeReference();
    de.setRightExpression(new VariableExpression("this"));

    changeBaseScriptType(de, cNode, baseScriptType);
}
 
Example #9
Source File: EqualsAndHashCodeASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void createCanEqual(ClassNode cNode) {
    boolean hasExistingCanEqual = hasDeclaredMethod(cNode, "canEqual", 1);
    if (hasExistingCanEqual && hasDeclaredMethod(cNode, "_canEqual", 1)) return;

    final BlockStatement body = new BlockStatement();
    VariableExpression other = varX("other");
    body.addStatement(returnS(isInstanceOfX(other, GenericsUtils.nonGeneric(cNode))));
    MethodNode canEqual = addGeneratedMethod(cNode,
            hasExistingCanEqual ? "_canEqual" : "canEqual",
            hasExistingCanEqual ? ACC_PRIVATE : ACC_PUBLIC,
            ClassHelper.boolean_TYPE,
            params(param(OBJECT_TYPE, other.getName())),
            ClassNode.EMPTY_ARRAY,
            body);
    // don't null check this: prefer false to IllegalArgumentException
    NullCheckASTTransformation.markAsProcessed(canEqual);
}
 
Example #10
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    // if we are in the same block we check position, if it occurs after
    // current position we ignore it
    if (blocks.isEmpty()
            && expression.getLineNumber() >= 0 && expression.getColumnNumber() >= 0
            && path.getLineNumber() >= 0 && path.getColumnNumber() >= 0
            && (expression.getLineNumber() > path.getLineNumber()
            || (expression.getLineNumber() == path.getLineNumber() && expression.getColumnNumber() >= path.getColumnNumber()))) {
        return;
    }

    Expression leftExpression = expression.getLeftExpression();
    if (leftExpression instanceof VariableExpression) {
        if (expression.getOperation().isA(Types.EQUAL)) {
            VariableExpression variableExpression = (VariableExpression) leftExpression;
            if (variableExpression.getAccessedVariable() != null) {
                String name = variableExpression.getAccessedVariable().getName();
                if (!variables.containsKey(name)) {
                    variables.put(name, variableExpression.getAccessedVariable());
                }
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example #11
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_add_to_unknonwn_variables_a_variable_not_declared_and_not_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);

    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ReturnStatement(new VariableExpression("unkownVariable")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("unkownVariable"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer( groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getUnknownVaraibles()).containsExactly("unkownVariable");
}
 
Example #12
Source File: StaticTypesTypeChooser.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public ClassNode resolveType(final Expression exp, final ClassNode current) {
    Expression target = exp instanceof VariableExpression && !((VariableExpression) exp).isClosureSharedVariable() ? getTarget((VariableExpression) exp) : exp;

    ClassNode inferredType = target.getNodeMetaData(StaticTypesMarker.DECLARATION_INFERRED_TYPE);
    if (inferredType == null) {
        inferredType = target.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
    }
    if (inferredType != null && !ClassHelper.VOID_TYPE.equals(inferredType)) {
        return inferredType;
    }

    // AsmClassGenerator may create "this" expressions that the type checker knows nothing about
    if (AsmClassGenerator.isThisExpression(target)) {
        return current;
    }

    return super.resolveType(exp, current);
}
 
Example #13
Source File: FindMethodUsagesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMethodCallExpression(MethodCallExpression methodCall) {
    Expression expression = methodCall.getObjectExpression();

    if (expression instanceof VariableExpression) {
        VariableExpression variableExpression = ((VariableExpression) expression);
        Variable variable = variableExpression.getAccessedVariable();

        if (variable != null) {
            if (variable.isDynamicTyped()) {
                addDynamicVarUsages(methodCall, variable);
            } else {
                addStaticVarUsages(methodCall, variable);
            }
        } else {
            addThisUsages(methodCall);
        }

    } else if (expression instanceof ConstructorCallExpression) {
        addConstructorUsages(methodCall, (ConstructorCallExpression) expression);
    }
    super.visitMethodCallExpression(methodCall);
}
 
Example #14
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createConstructor(final ClassNode classNode) {
    Parameter[] params = new Parameter[]{
            new Parameter(MarkupTemplateEngine.MARKUPTEMPLATEENGINE_CLASSNODE, "engine"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "model"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "modelTypes"),
            new Parameter(TEMPLATECONFIG_CLASSNODE, "tplConfig")
    };
    List<Expression> vars = new LinkedList<Expression>();
    for (Parameter param : params) {
        vars.add(new VariableExpression(param));
    }
    ExpressionStatement body = new ExpressionStatement(
            new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(vars)));
    ConstructorNode ctor = new ConstructorNode(Opcodes.ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, body);
    classNode.addConstructor(ctor);
}
 
Example #15
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 #16
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformBinaryExpression(BinaryExpression be) {
    int type = be.getOperation().getType();
    boolean oldInLeftExpression;
    Expression right = transform(be.getRightExpression());
    be.setRightExpression(right);
    Expression left;
    if (type == Types.EQUAL && be.getLeftExpression() instanceof VariableExpression) {
        oldInLeftExpression = inLeftExpression;
        inLeftExpression = true;
        left = transform(be.getLeftExpression());
        inLeftExpression = oldInLeftExpression;
        if (left instanceof StaticMethodCallExpression) {
            StaticMethodCallExpression smce = (StaticMethodCallExpression) left;
            StaticMethodCallExpression result = new StaticMethodCallExpression(smce.getOwnerType(), smce.getMethod(), right);
            setSourcePosition(result, be);
            return result;
        }
    } else {
        left = transform(be.getLeftExpression());
    }
    be.setLeftExpression(left);
    return be;
}
 
Example #17
Source File: StaticVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression ve) {
    if (ve.getAccessedVariable() instanceof DynamicVariable && (ve.isInStaticContext() || inSpecialConstructorCall) && !inClosure) {
        // GROOVY-5687: interface constants not visible to implementing sub-class in static context
        if (methodNode != null && methodNode.isStatic()) {
            FieldNode fieldNode = getDeclaredOrInheritedField(methodNode.getDeclaringClass(), ve.getName());
            if (fieldNode != null && fieldNode.isStatic()) {
                return;
            }
        }
        addError("Apparent variable '" + ve.getName() + "' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:\n" +
                "You attempted to reference a variable in the binding or an instance variable from a static context.\n" +
                "You misspelled a classname or statically imported field. Please check the spelling.\n" +
                "You attempted to use a method '" + ve.getName() + "' but left out brackets in a place not allowed by the grammar.", ve);
    }
}
 
Example #18
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
    // if we are in the same block we check position, if it occurs after
    // current position we ignore it
    if (blocks.isEmpty()
            && expression.getLineNumber() >= 0 && expression.getColumnNumber() >= 0
            && path.getLineNumber() >= 0 && path.getColumnNumber() >= 0
            && (expression.getLineNumber() > path.getLineNumber()
            || (expression.getLineNumber() == path.getLineNumber() && expression.getColumnNumber() >= path.getColumnNumber()))) {
        return;
    }

    if (!expression.isMultipleAssignmentDeclaration()) {
        VariableExpression variableExpression = expression.getVariableExpression();
        if (variableExpression.getAccessedVariable() != null) {
            String name = variableExpression.getAccessedVariable().getName();
            variables.put(name, variableExpression.getAccessedVariable());
        }
    }
    // perhaps we could visit just declaration or do nothing
    super.visitDeclarationExpression(expression);
}
 
Example #19
Source File: TryCatchStatement.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void addResource(ExpressionStatement resourceStatement) {
    Expression resourceExpression = resourceStatement.getExpression();
    if (!(resourceExpression instanceof DeclarationExpression || resourceExpression instanceof VariableExpression)) {
        throw new GroovyBugError("resourceStatement should be a variable declaration statement or a variable");
    }

    resourceExpression.putNodeMetaData(IS_RESOURCE, Boolean.TRUE);

    resourceStatements.add(resourceStatement);
}
 
Example #20
Source File: ASTTransformer.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
private void changeBaseScriptTypeFromDeclaration(final DeclarationExpression de, final AnnotationNode node) {
    if (de.isMultipleAssignmentDeclaration()) {
        addError( "Annotation " + getType() + " not supported with multiple assignment notation.", de);
        return;
    }

    if (!(de.getRightExpression() instanceof EmptyExpression)) {
        addError( "Annotation " + getType() + " not supported with variable assignment.", de);
        return;
    }
    Expression value = node.getMember("value");
    if (value != null) {
        addError( "Annotation " + getType() + " cannot have member 'value' if used on a declaration.", value);
        return;
    }

    ClassNode cNode = de.getDeclaringClass();
    ClassNode baseScriptType = de.getVariableExpression().getType().getPlainNodeReference();
    if (baseScriptType.isScript()) {
        if (!(de.getRightExpression() instanceof EmptyExpression)) {
            addError( "Annotation " + getType() + " not supported with variable assignment.", de);
            return;
        }
        de.setRightExpression(new VariableExpression("this"));
    } else {
        if ( type == Type.MAVEN )
        {
            baseScriptType = MAVEN_BASE_SCRIPT_TYPE;
        }
        else
        {
            baseScriptType = GRADLE_BASE_SCRIPT_TYPE;
        }
    }

    changeBaseScriptType(de, cNode, baseScriptType);
}
 
Example #21
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void extractModelTypesFromStatement(final Statement code, final Map<String, ClassNode> model) {
    if (code instanceof BlockStatement) {
        BlockStatement block = (BlockStatement) code;
        for (Statement statement : block.getStatements()) {
            extractModelTypesFromStatement(statement, model);
        }
    } else if (code instanceof ExpressionStatement) {
        Expression expression = ((ExpressionStatement) code).getExpression();
        if (expression instanceof DeclarationExpression) {
            VariableExpression var = ((DeclarationExpression) expression).getVariableExpression();
            model.put(var.getName(), var.getOriginType());
        }
    }
}
 
Example #22
Source File: StaticCompilationTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Expression transform(Expression expr) {
    if (expr instanceof StaticMethodCallExpression) {
        return staticMethodCallExpressionTransformer.transformStaticMethodCallExpression((StaticMethodCallExpression) expr);
    }
    if (expr instanceof BinaryExpression) {
        return binaryExpressionTransformer.transformBinaryExpression((BinaryExpression)expr);
    }
    if (expr instanceof MethodCallExpression) {
        return methodCallExpressionTransformer.transformMethodCallExpression((MethodCallExpression) expr);
    }
    if (expr instanceof ClosureExpression) {
        return closureExpressionTransformer.transformClosureExpression((ClosureExpression) expr);
    }
    if (expr instanceof ConstructorCallExpression) {
        return constructorCallTransformer.transformConstructorCall((ConstructorCallExpression) expr);
    }
    if (expr instanceof BooleanExpression) {
        return booleanExpressionTransformer.transformBooleanExpression((BooleanExpression)expr);
    }
    if (expr instanceof VariableExpression) {
        return variableExpressionTransformer.transformVariableExpression((VariableExpression)expr);
    }
    if (expr instanceof RangeExpression) {
        return rangeExpressionTransformer.transformRangeExpression(((RangeExpression)expr));
    }
    if (expr instanceof ListExpression) {
        return listExpressionTransformer.transformListExpression((ListExpression) expr);
    }
    if (expr instanceof CastExpression) {
        return castExpressionTransformer.transformCastExpression(((CastExpression)expr));
    }
    return super.transform(expr);
}
 
Example #23
Source File: AutoNewLineTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Statement createNewLine(final ASTNode node) {
    MethodCallExpression mce = new MethodCallExpression(
            new VariableExpression("this"),
            "newLine",
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setImplicitThis(true);
    mce.setSourcePosition(node);
    ExpressionStatement stmt = new ExpressionStatement(mce);
    stmt.setSourcePosition(node);
    return stmt;
}
 
Example #24
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void recordFinalVars(Expression leftExpression) {
    if (leftExpression instanceof VariableExpression) {
        VariableExpression var = (VariableExpression) leftExpression;
        if (Modifier.isFinal(var.getModifiers())) {
            declaredFinalVariables.add(var);
        }
    } else if (leftExpression instanceof TupleExpression) {
        TupleExpression te = (TupleExpression) leftExpression;
        for (Expression next : te.getExpressions()) {
            if (next instanceof Variable) {
                declaredFinalVariables.add((Variable) next);
            }
        }
    }
}
 
Example #25
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
public TraitReceiverTransformer(VariableExpression thisObject, SourceUnit unit, final ClassNode traitClass,
                                final ClassNode traitHelperClass, ClassNode fieldHelper, Collection<String> knownFields) {
    this.weaved = thisObject;
    this.unit = unit;
    this.traitClass = traitClass;
    this.traitHelperClass = traitHelperClass;
    this.fieldHelper = fieldHelper;
    this.knownFields = knownFields;
}
 
Example #26
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 #27
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void loadVariableWithReference(final VariableExpression var) {
    if (!var.isUseReferenceDirectly()) {
        var.visit(controller.getAcg());
    } else {
        ClosureWriter.loadReference(var.getName(), controller);
    }
}
 
Example #28
Source File: SharedVariableCollector.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    if (visited) {
        // we should not visit embedded closures recursively
        return;
    }
    visited = true;
    if (expression.isClosureSharedVariable()) closureSharedExpressions.add(expression);
    super.visitVariableExpression(expression);
}
 
Example #29
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);
}
 
Example #30
Source File: MapConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void doAddConstructor(final ClassNode cNode, final ConstructorNode constructorNode) {
    markAsGenerated(cNode, constructorNode);
    cNode.addConstructor(constructorNode);
    // GROOVY-5814: Immutable is not compatible with @CompileStatic
    Parameter argsParam = null;
    for (Parameter p : constructorNode.getParameters()) {
        if ("args".equals(p.getName())) {
            argsParam = p;
            break;
        }
    }
    if (argsParam != null) {
        final Parameter arg = argsParam;
        ClassCodeVisitorSupport variableExpressionFix = new ClassCodeVisitorSupport() {
            @Override
            protected SourceUnit getSourceUnit() {
                return cNode.getModule().getContext();
            }

            @Override
            public void visitVariableExpression(final VariableExpression expression) {
                super.visitVariableExpression(expression);
                if ("args".equals(expression.getName())) {
                    expression.setAccessedVariable(arg);
                }
            }
        };
        variableExpressionFix.visitConstructor(constructorNode);
    }
}