Skip to content

Instantly share code, notes, and snippets.

@paulk-asert
Created December 3, 2014 10:29
Show Gist options
  • Save paulk-asert/302a3fd361dba9bf0861 to your computer and use it in GitHub Desktop.
Save paulk-asert/302a3fd361dba9bf0861 to your computer and use it in GitHub Desktop.
import org.codehaus.groovy.ast.expr.*
incompatibleAssignment { lhsType, rhsType, expr ->
if (!(expr instanceof DeclarationExpression)) return
Expression orig = expr.rightExpression
def ce = new CastExpression(lhsType, orig)
ce.coerce = true
expr.setRightExpression(ce)
storeType(expr, lhsType)
handled = true
}
@melix
Copy link

melix commented Dec 3, 2014

Here is a version supporting list literals on LHS (very basic test) :

import org.codehaus.groovy.ast.ClassCodeExpressionTransformer
import org.codehaus.groovy.ast.expr.CastExpression
import org.codehaus.groovy.ast.expr.DeclarationExpression
import org.codehaus.groovy.ast.expr.Expression
import org.codehaus.groovy.ast.expr.ListExpression
import org.codehaus.groovy.control.SourceUnit

beforeVisitMethod { mn ->
    def replacer = new Replacer(context.source)
    replacer.visitMethod(mn)
}

incompatibleAssignment { lhsType, rhsType, expr ->
    if (!(expr instanceof DeclarationExpression)) return
    Expression orig = expr.rightExpression
    def ce = new CastExpression(lhsType, orig)
    ce.coerce = true
    expr.setRightExpression(ce)
    storeType(expr, lhsType)
    handled = true
}


class Replacer extends ClassCodeExpressionTransformer {
    private final SourceUnit unit

    Replacer(final SourceUnit unit) {
        this.unit = unit
    }

    @Override
    protected SourceUnit getSourceUnit() {
        unit
    }

    @Override
    Expression transform(final Expression expr) {
        if (!(expr instanceof DeclarationExpression)) return super.transform(expr)
        if (expr.rightExpression instanceof ListExpression) {
            def orig = expr.rightExpression
            def ce = new CastExpression(expr.leftExpression.type, orig)
            ce.coerce = true
            expr.rightExpression = ce
        }
        super.transform(expr)
    }
}

@paulk-asert
Copy link
Author

cool, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment