You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2019/04/04 04:57:24 UTC

[groovy] branch master updated (ebe8c51 -> e4cc76b)

This is an automated email from the ASF dual-hosted git repository.

paulk pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git.


    from ebe8c51  minor refactor: remove some codenarc violations (cont'd)
     new 5ca86e8  minor refactor: remove some codenarc violations (part 3)
     new e4cc76b  minor refactor: remove some codenarc violations (part 4)

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 config/codenarc/codenarc.groovy                    |   6 +-
 src/main/groovy/groovy/grape/GrapeIvy.groovy       |  12 +--
 .../ast/builder/AstSpecificationCompiler.groovy    |  92 +++++++++---------
 .../groovy/ast/builder/AstStringCompiler.groovy    |  10 +-
 .../codehaus/groovy/classgen/genArrayAccess.groovy |  37 +++----
 .../{genArrays.groovy => genArrayUtil.groovy}      |  22 ++---
 .../org/codehaus/groovy/classgen/genDgmMath.groovy |  43 +++++----
 .../groovy/classgen/genMathModification.groovy     | 106 ++++++++++-----------
 .../groovy/transform/ASTTestTransformation.groovy  |  17 ++--
 .../TimedInterruptibleASTTransformation.groovy     |  10 +-
 .../transform/tailrec/InWhileLoopWrapper.groovy    |   3 -
 .../tailrec/TailRecursiveASTTransformation.groovy  |  26 ++---
 .../tailrec/TernaryToIfStatementConverter.groovy   |   6 +-
 13 files changed, 199 insertions(+), 191 deletions(-)
 rename src/main/groovy/org/codehaus/groovy/classgen/{genArrays.groovy => genArrayUtil.groovy} (78%)


[groovy] 01/02: minor refactor: remove some codenarc violations (part 3)

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit 5ca86e8ca0cd07a8d280bad5a717a04756d16432
Author: Paul King <pa...@asert.com.au>
AuthorDate: Wed Apr 3 23:43:15 2019 +1000

    minor refactor: remove some codenarc violations (part 3)
---
 src/main/groovy/groovy/grape/GrapeIvy.groovy       | 12 +--
 .../ast/builder/AstSpecificationCompiler.groovy    | 92 +++++++++++-----------
 .../groovy/ast/builder/AstStringCompiler.groovy    | 10 +--
 .../TimedInterruptibleASTTransformation.groovy     | 10 +--
 .../transform/tailrec/InWhileLoopWrapper.groovy    |  3 -
 .../tailrec/TernaryToIfStatementConverter.groovy   |  6 +-
 6 files changed, 66 insertions(+), 67 deletions(-)

diff --git a/src/main/groovy/groovy/grape/GrapeIvy.groovy b/src/main/groovy/groovy/grape/GrapeIvy.groovy
index 3e11a9e..be969b9 100644
--- a/src/main/groovy/groovy/grape/GrapeIvy.groovy
+++ b/src/main/groovy/groovy/grape/GrapeIvy.groovy
@@ -445,11 +445,11 @@ class GrapeIvy implements GrapeEngine {
         }
 
         // resolve grab and dependencies
-        ResolveOptions resolveOptions = new ResolveOptions()
-                .setConfs(GrapeIvy.DEF_CONFIG as String[])
-                .setOutputReport(false)
-                .setValidate((boolean) (args.containsKey('validate') ? args.validate : false))
-
+        ResolveOptions resolveOptions = new ResolveOptions().tap {
+            confs = DEF_CONFIG as String[]
+            outputReport = false
+            validate = (boolean) (args.containsKey('validate') ? args.validate : false)
+        }
         ivyInstance.settings.defaultResolver = args.autoDownload ? 'downloadGrapes' : 'cachedGrapes'
         if (args.disableChecksums) {
             ivyInstance.settings.setVariable('ivy.checksums', '')
@@ -714,7 +714,7 @@ class GrapeIvy implements GrapeEngine {
                         module : grabbed.mrid.name,
                         version: grabbed.mrid.revision
                 ]
-                if (grabbed.conf != GrapeIvy.DEF_CONFIG) {
+                if (grabbed.conf != DEF_CONFIG) {
                     dep.conf = grabbed.conf
                 }
                 if (grabbed.changing) {
diff --git a/src/main/groovy/org/codehaus/groovy/ast/builder/AstSpecificationCompiler.groovy b/src/main/groovy/org/codehaus/groovy/ast/builder/AstSpecificationCompiler.groovy
index b450a09..fdc8a22 100644
--- a/src/main/groovy/org/codehaus/groovy/ast/builder/AstSpecificationCompiler.groovy
+++ b/src/main/groovy/org/codehaus/groovy/ast/builder/AstSpecificationCompiler.groovy
@@ -45,7 +45,6 @@ import org.codehaus.groovy.ast.expr.CastExpression
 import org.codehaus.groovy.ast.expr.ClassExpression
 import org.codehaus.groovy.ast.expr.ClosureExpression
 import org.codehaus.groovy.ast.expr.ClosureListExpression
-import org.codehaus.groovy.ast.expr.ConstantExpression
 import org.codehaus.groovy.ast.expr.ConstructorCallExpression
 import org.codehaus.groovy.ast.expr.DeclarationExpression
 import org.codehaus.groovy.ast.expr.ElvisOperatorExpression
@@ -72,7 +71,6 @@ import org.codehaus.groovy.ast.expr.UnaryMinusExpression
 import org.codehaus.groovy.ast.expr.UnaryPlusExpression
 import org.codehaus.groovy.ast.expr.VariableExpression
 import org.codehaus.groovy.ast.stmt.AssertStatement
-import org.codehaus.groovy.ast.stmt.BlockStatement
 import org.codehaus.groovy.ast.stmt.BreakStatement
 import org.codehaus.groovy.ast.stmt.CaseStatement
 import org.codehaus.groovy.ast.stmt.CatchStatement
@@ -92,6 +90,10 @@ import org.codehaus.groovy.runtime.MethodClosure
 import org.codehaus.groovy.syntax.Token
 import org.codehaus.groovy.syntax.Types
 
+import static org.codehaus.groovy.ast.tools.GeneralUtils.block
+import static org.codehaus.groovy.ast.tools.GeneralUtils.constX
+import static org.codehaus.groovy.ast.tools.GeneralUtils.param
+
 /**
  * Handles parsing the properties from the closure into values that can be referenced.
  *
@@ -101,6 +103,7 @@ import org.codehaus.groovy.syntax.Types
  * Note: this class consists of many one-line method calls. A better implementation
  * might be to take a declarative approach and replace the one-liners with map entries. 
  */
+@SuppressWarnings('BuilderMethodWithSideEffects')
 class AstSpecificationCompiler implements GroovyInterceptable {
 
     private final List<ASTNode> expression = []
@@ -117,7 +120,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Gets the current generated expression.
      */
     List<ASTNode> getExpression() {
-        return expression
+        expression
     }
 
     /**
@@ -136,7 +139,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
 
         // enforce that the correct # arguments was passed
         if (spec.size() != expression.size()) {
-            throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression?.collect { it.class }}")
+            throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression*.class}")
         }
 
         // enforce types and collect result
@@ -144,7 +147,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
             def actualClass = expression[it].class
             def expectedClass = spec[it]
             if (!expectedClass.isAssignableFrom(actualClass)) {
-                throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression?.collect { it.class }}")
+                throw new IllegalArgumentException("$methodName could not be invoked. Expected to receive parameters $spec but found ${expression*.class}")
             }
             expression[it]
         }
@@ -489,7 +492,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Designates a list of AnnotationNodes.
      */
     void annotations(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<AnnotationNode>")
+        makeListOfNodes(argBlock, 'List<AnnotationNode>')
     }
 
 
@@ -497,28 +500,28 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Designates a list of MethodNodes.
      */
     void methods(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<MethodNode>")
+        makeListOfNodes(argBlock, 'List<MethodNode>')
     }
 
     /**
      * Designates a list of ConstructorNodes.
      */
     void constructors(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<ConstructorNode>")
+        makeListOfNodes(argBlock, 'List<ConstructorNode>')
     }
 
     /**
      * Designates a list of {@code PropertyNode}s.
      */
     void properties(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<PropertyNode>")
+        makeListOfNodes(argBlock, 'List<PropertyNode>')
     }
 
     /**
      * Designates a list of {@code FieldNode}s.
      */
     void fields(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<FieldNode>")
+        makeListOfNodes(argBlock, 'List<FieldNode>')
     }
 
     /**
@@ -526,7 +529,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
 
     void strings(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<ConstantExpression>")
+        makeListOfNodes(argBlock, 'List<ConstantExpression>')
     }
 
     /**
@@ -534,7 +537,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
 
     void values(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<Expression>")
+        makeListOfNodes(argBlock, 'List<Expression>')
     }
 
     /**
@@ -548,7 +551,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a ConstantExpression.
      */
     void constant(Object value) {
-        expression << new ConstantExpression(value)
+        expression << constX(value)
     }
 
     /**
@@ -666,6 +669,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
     /**
      * Creates an ExpressionStatement.
      */
+    @SuppressWarnings('ConfusingMethodName')
     void expression(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
         makeNode(ExpressionStatement, 'expression', [Expression], argBlock)
     }
@@ -681,21 +685,21 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a ClassNode[].
      */
     void interfaces(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<ClassNode>")
+        makeListOfNodes(argBlock, 'List<ClassNode>')
     }
 
     /**
      * Creates a MixinNode[].
      */
     void mixins(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<MixinNode>")
+        makeListOfNodes(argBlock, 'List<MixinNode>')
     }
 
     /**
      * Creates a GenericsTypes[].
      */
     void genericsTypes(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        makeListOfNodes(argBlock, "List<GenericsTypes>")
+        makeListOfNodes(argBlock, 'List<GenericsTypes>')
     }
 
     /**
@@ -716,8 +720,8 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a BlockStatement.
      */
     void block(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("BlockStatement", argBlock) {
-            return new BlockStatement(new ArrayList(expression), new VariableScope())
+        captureAndCreateNode('BlockStatement', argBlock) {
+            block(new VariableScope(), new ArrayList(expression))
         }
     }
 
@@ -731,13 +735,13 @@ class AstSpecificationCompiler implements GroovyInterceptable {
         //todo: add better error handling?
         if (argBlock) {
             args.each { name, type ->
-                captureAndCreateNode("Parameter", argBlock) {
-                    new Parameter(ClassHelper.make(type), name, expression[0])
+                captureAndCreateNode('Parameter', argBlock) {
+                    param(ClassHelper.make(type), name, expression[0])
                 }
             }
         } else {
             args.each { name, type ->
-                expression << (new Parameter(ClassHelper.make(type), name))
+                expression << (param(ClassHelper.make(type), name))
             }
         }
     }
@@ -746,7 +750,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates an ArrayExpression.
      */
     void array(Class type, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("ArrayExpression", argBlock) {
+        captureAndCreateNode('ArrayExpression', argBlock) {
             new ArrayExpression(ClassHelper.make(type), new ArrayList(expression))
         }
     }
@@ -756,7 +760,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
     void genericsType(Class type, @DelegatesTo(AstSpecificationCompiler) Closure argBlock = null) {
         if (argBlock) {
-            captureAndCreateNode("GenericsType", argBlock) {
+            captureAndCreateNode('GenericsType', argBlock) {
                 new GenericsType(ClassHelper.make(type), expression[0] as ClassNode[], expression[1])
             }
         } else {
@@ -782,7 +786,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a 2 element list of name and Annotation. Used with Annotation Members.
      */
     void member(String name, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("Annotation Member", argBlock) {
+        captureAndCreateNode('Annotation Member', argBlock) {
             [name, expression[0]]
         }
     }
@@ -804,7 +808,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
     void annotation(Class target, @DelegatesTo(AstSpecificationCompiler) Closure argBlock = null) {
         if (argBlock) {
             //todo: add better error handling
-            captureAndCreateNode("ArgumentListExpression", argBlock) {
+            captureAndCreateNode('ArgumentListExpression', argBlock) {
                 def node = new AnnotationNode(ClassHelper.make(target))
                 expression?.each {
                     node.addMember(it[0], it[1])
@@ -820,7 +824,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a MixinNode.
      */
     void mixin(String name, int modifiers, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("AttributeExpression", argBlock) {
+        captureAndCreateNode('AttributeExpression', argBlock) {
             if (expression.size() > 1) {
                 new MixinNode(name, modifiers, expression[0], new ArrayList(expression[1]) as ClassNode[])
             } else {
@@ -833,7 +837,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a ClassNode
      */
     void classNode(String name, int modifiers, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("ClassNode", argBlock) {
+        captureAndCreateNode('ClassNode', argBlock) {
             def result = new ClassNode(name, modifiers,
                     expression[0],
                     new ArrayList(expression[1]) as ClassNode[],
@@ -841,13 +845,13 @@ class AstSpecificationCompiler implements GroovyInterceptable {
             )
             while (expression.size() > 3) {
                 if (!List.isAssignableFrom(expression[3].getClass())) {
-                    throw new IllegalArgumentException("Expecting to find list of additional items instead found: " + expression[3].getClass())
+                    throw new IllegalArgumentException('Expecting to find list of additional items instead found: ' + expression[3].getClass())
                 }
                 if (expression[3].size() > 0) {
                     def clazz = expression[3][0].getClass()
                     switch (clazz) {
                         case GenericsType:
-                            result.setGenericsTypes(new ArrayList(expression[3]) as GenericsType[])
+                            result.genericsTypes = new ArrayList(expression[3]) as GenericsType[]
                             break
                         case MethodNode:
                             expression[3].each { result.addMethod(it) }
@@ -884,7 +888,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates an AssertStatement.
      */
     void assertStatement(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("AssertStatement", argBlock) {
+        captureAndCreateNode('AssertStatement', argBlock) {
             if (expression.size() < 2) {
                 new AssertStatement(*enforceConstraints('assertStatement', [BooleanExpression]))
             } else {
@@ -897,11 +901,11 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a TryCatchStatement.
      */
     void tryCatch(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("TryCatchStatement", argBlock) {
+        captureAndCreateNode('TryCatchStatement', argBlock) {
             def result = new TryCatchStatement(expression[0], expression[1])
             def catchStatements = expression.tail().tail()
             catchStatements.each { statement -> result.addCatch(statement) }
-            return result
+            result
         }
     }
 
@@ -916,7 +920,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a MethodNode.
      */
     void method(String name, int modifiers, Class returnType, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("MethodNode", argBlock) {
+        captureAndCreateNode('MethodNode', argBlock) {
             //todo: enforce contract
             def result = new MethodNode(name, modifiers, ClassHelper.make(returnType), expression[0], expression[1], expression[2])
             if (expression[3]) {
@@ -930,7 +934,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a token.
      */
     void token(String value) {
-        if (value == null) throw new IllegalArgumentException("Null: value")
+        if (value == null) throw new IllegalArgumentException('Null: value')
 
         def tokenID = Types.lookupKeyword(value)
         if (tokenID == Types.UNKNOWN) {
@@ -946,7 +950,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
     void range(Range range) {
         if (range == null) throw new IllegalArgumentException('Null: range')
-        expression << new RangeExpression(new ConstantExpression(range.getFrom()), new ConstantExpression(range.getTo()), true)
+        expression << new RangeExpression(constX(range.from), constX(range.to), true)
         //default is inclusive
     }
 
@@ -954,7 +958,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a SwitchStatement.
      */
     void switchStatement(@DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("SwitchStatement", argBlock) {
+        captureAndCreateNode('SwitchStatement', argBlock) {
             def switchExpression = expression.head()
             def caseStatements = expression.tail().tail()
             def defaultExpression = expression.tail().head()
@@ -967,9 +971,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
     void mapEntry(Map map) {
         map.entrySet().each {
-            expression << new MapEntryExpression(
-                    new ConstantExpression(it.key),
-                    new ConstantExpression(it.value))
+            expression << new MapEntryExpression(constX(it.key), constX(it.value))
         }
     }
 
@@ -981,7 +983,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a FieldNode.
      */
     void fieldNode(String name, int modifiers, Class type, Class owner, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("FieldNode", argBlock) {
+        captureAndCreateNode('FieldNode', argBlock) {
             def annotations = null
             if (expression.size() > 1) {
                 annotations = expression[1]
@@ -1003,7 +1005,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates an inner class.
      */
     void innerClass(String name, int modifiers, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("InnerClassNode", argBlock) {
+        captureAndCreateNode('InnerClassNode', argBlock) {
             //todo: enforce contract
             new InnerClassNode(
                     expression[0],
@@ -1020,7 +1022,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      */
     void propertyNode(String name, int modifiers, Class type, Class owner, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
         //todo: improve error handling?
-        captureAndCreateNode("PropertyNode", argBlock) {
+        captureAndCreateNode('PropertyNode', argBlock) {
             def annotations = null
             // check if the last expression looks like annotations
             if (List.isAssignableFrom(expression[-1].getClass())) {
@@ -1042,7 +1044,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a StaticMethodCallExpression.
      */
     void staticMethodCall(Class target, String name, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("StaticMethodCallExpression", argBlock) {
+        captureAndCreateNode('StaticMethodCallExpression', argBlock) {
             expression.add(0, name)
             expression.add(0, ClassHelper.make(target))
             new StaticMethodCallExpression(*enforceConstraints('staticMethodCall', [ClassNode, String, Expression]))
@@ -1053,7 +1055,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a StaticMethodCallExpression.
      */
     void staticMethodCall(MethodClosure target, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("StaticMethodCallExpression", argBlock) {
+        captureAndCreateNode('StaticMethodCallExpression', argBlock) {
             expression.add(0, target.method)
             expression.add(0, ClassHelper.makeWithoutCaching(target.owner.class, false))
             new StaticMethodCallExpression(*enforceConstraints('staticMethodCall', [ClassNode, String, Expression]))
@@ -1064,7 +1066,7 @@ class AstSpecificationCompiler implements GroovyInterceptable {
      * Creates a ConstructorNode.
      */
     void constructor(int modifiers, @DelegatesTo(AstSpecificationCompiler) Closure argBlock) {
-        captureAndCreateNode("ConstructorNode", argBlock) {
+        captureAndCreateNode('ConstructorNode', argBlock) {
             def annotations = null
             if (expression.size() > 3) {
                 annotations = expression[3]
diff --git a/src/main/groovy/org/codehaus/groovy/ast/builder/AstStringCompiler.groovy b/src/main/groovy/org/codehaus/groovy/ast/builder/AstStringCompiler.groovy
index 3947819..a3818de 100644
--- a/src/main/groovy/org/codehaus/groovy/ast/builder/AstStringCompiler.groovy
+++ b/src/main/groovy/org/codehaus/groovy/ast/builder/AstStringCompiler.groovy
@@ -47,14 +47,14 @@ class AstStringCompiler {
      */
     List<ASTNode> compile(String script, CompilePhase compilePhase, boolean statementsOnly) {
         final scriptClassName = makeScriptClassName()
-        GroovyCodeSource codeSource = new GroovyCodeSource(script, "${scriptClassName}.groovy", "/groovy/script")
+        GroovyCodeSource codeSource = new GroovyCodeSource(script, "${scriptClassName}.groovy", '/groovy/script')
         CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.codeSource, AccessController.doPrivileged({
             new GroovyClassLoader()
         } as PrivilegedAction<GroovyClassLoader>))
-        cu.addSource(codeSource.getName(), script)
-        cu.compile(compilePhase.getPhaseNumber())
+        cu.addSource(codeSource.name, script)
+        cu.compile(compilePhase.phaseNumber)
         // collect all the ASTNodes into the result, possibly ignoring the script body if desired
-        return (List<ASTNode>) cu.getAST().modules.inject([]) { List acc, ModuleNode node ->
+        (List<ASTNode>) cu.AST.modules.inject([]) { List acc, ModuleNode node ->
             if (node.statementBlock) acc.add(node.statementBlock)
             node.classes?.each {
                 if (!(statementsOnly && it.name == scriptClassName)) {
@@ -66,6 +66,6 @@ class AstStringCompiler {
     }
 
     private static String makeScriptClassName() {
-        return "Script${System.nanoTime()}"
+        "Script${System.nanoTime()}"
     }
 }
diff --git a/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
index 786fad9..02b7328 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/TimedInterruptibleASTTransformation.groovy
@@ -77,7 +77,7 @@ class TimedInterruptibleASTTransformation extends AbstractASTTransformation {
         init(nodes, source)
         AnnotationNode node = nodes[0]
         AnnotatedNode annotatedNode = nodes[1]
-        if (!MY_TYPE.equals(node.getClassNode())) {
+        if (!MY_TYPE.equals(node.classNode)) {
             internalError("Transformation called from wrong annotation: $node.classNode.name")
         }
 
@@ -87,13 +87,13 @@ class TimedInterruptibleASTTransformation extends AbstractASTTransformation {
         def maximum = getConstantAnnotationParameter(node, 'value', Long.TYPE, Long.MAX_VALUE)
         def thrown = AbstractInterruptibleASTTransformation.getClassAnnotationParameter(node, THROWN_EXCEPTION_TYPE, make(TimeoutException))
 
-        Expression unit = node.getMember('unit') ?: propX(classX(TimeUnit), "SECONDS")
+        Expression unit = node.getMember('unit') ?: propX(classX(TimeUnit), 'SECONDS')
 
         // should be limited to the current SourceUnit or propagated to the whole CompilationUnit
         // DO NOT inline visitor creation in code below. It has state that must not persist between calls
         if (applyToAllClasses) {
             // guard every class and method defined in this script
-            source.getAST()?.classes?.each { ClassNode it ->
+            source.AST?.classes?.each { ClassNode it ->
                 def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
                 visitor.visitClass(it)
             }
@@ -118,7 +118,7 @@ class TimedInterruptibleASTTransformation extends AbstractASTTransformation {
             visitor.visitClass annotatedNode.declaringClass
         } else {
             // only guard the script class
-            source.getAST()?.classes?.each { ClassNode it ->
+            source.AST?.classes?.each { ClassNode it ->
                 if (it.isScript()) {
                     def visitor = new TimedInterruptionVisitor(source, checkOnMethodStart, applyToAllClasses, applyToAllMembers, maximum, unit, thrown, node.hashCode())
                     visitor.visitClass(it)
@@ -232,7 +232,7 @@ class TimedInterruptibleASTTransformation extends AbstractASTTransformation {
                                     args(constX(maximum, true), unit)
                             )
                     )
-            );
+            )
             expireTimeField.synthetic = true
             startTimeField = node.addField(basename + '$startTime',
                     ACC_FINAL | ACC_PRIVATE,
diff --git a/src/main/groovy/org/codehaus/groovy/transform/tailrec/InWhileLoopWrapper.groovy b/src/main/groovy/org/codehaus/groovy/transform/tailrec/InWhileLoopWrapper.groovy
index fb66a89..20f02b5 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/tailrec/InWhileLoopWrapper.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/tailrec/InWhileLoopWrapper.groovy
@@ -21,10 +21,7 @@ package org.codehaus.groovy.transform.tailrec
 import groovy.transform.CompileStatic
 import org.codehaus.groovy.ast.ClassHelper
 import org.codehaus.groovy.ast.MethodNode
-import org.codehaus.groovy.ast.Parameter
 import org.codehaus.groovy.ast.VariableScope
-import org.codehaus.groovy.ast.expr.BooleanExpression
-import org.codehaus.groovy.ast.expr.ConstantExpression
 import org.codehaus.groovy.ast.stmt.BlockStatement
 import org.codehaus.groovy.ast.stmt.CatchStatement
 import org.codehaus.groovy.ast.stmt.ContinueStatement
diff --git a/src/main/groovy/org/codehaus/groovy/transform/tailrec/TernaryToIfStatementConverter.groovy b/src/main/groovy/org/codehaus/groovy/transform/tailrec/TernaryToIfStatementConverter.groovy
index 012a7c7..165650f 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/tailrec/TernaryToIfStatementConverter.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/tailrec/TernaryToIfStatementConverter.groovy
@@ -20,11 +20,11 @@ package org.codehaus.groovy.transform.tailrec
 
 import groovy.transform.CompileStatic
 import org.codehaus.groovy.ast.expr.TernaryExpression
-import org.codehaus.groovy.ast.stmt.IfStatement
 import org.codehaus.groovy.ast.stmt.ReturnStatement
 import org.codehaus.groovy.ast.stmt.Statement
 
 import static org.codehaus.groovy.ast.tools.GeneralUtils.ifElseS
+import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS
 
 /**
  * Since a ternary statement has more than one exit point tail-recursiveness testing cannot be easily done.
@@ -38,6 +38,6 @@ class TernaryToIfStatementConverter {
         if (!(statementWithInnerTernaryExpression.expression instanceof TernaryExpression))
             return statementWithInnerTernaryExpression
         TernaryExpression ternary = statementWithInnerTernaryExpression.expression as TernaryExpression
-        ifElseS(ternary.booleanExpression, new ReturnStatement(ternary.trueExpression), new ReturnStatement(ternary.falseExpression))
+        ifElseS(ternary.booleanExpression, returnS(ternary.trueExpression), returnS(ternary.falseExpression))
     }
-}
\ No newline at end of file
+}


[groovy] 02/02: minor refactor: remove some codenarc violations (part 4)

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit e4cc76b8db9ddefff65e710de96eb2e9c364d44c
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Apr 4 11:48:44 2019 +1000

    minor refactor: remove some codenarc violations (part 4)
---
 config/codenarc/codenarc.groovy                    |   6 +-
 .../codehaus/groovy/classgen/genArrayAccess.groovy |  37 +++----
 .../{genArrays.groovy => genArrayUtil.groovy}      |  22 ++---
 .../org/codehaus/groovy/classgen/genDgmMath.groovy |  43 +++++----
 .../groovy/classgen/genMathModification.groovy     | 106 ++++++++++-----------
 .../groovy/transform/ASTTestTransformation.groovy  |  17 ++--
 .../tailrec/TailRecursiveASTTransformation.groovy  |  26 ++---
 7 files changed, 133 insertions(+), 124 deletions(-)

diff --git a/config/codenarc/codenarc.groovy b/config/codenarc/codenarc.groovy
index 1d58fac..e9c7179 100644
--- a/config/codenarc/codenarc.groovy
+++ b/config/codenarc/codenarc.groovy
@@ -168,7 +168,10 @@ ruleset {
 
     ruleset('rulesets/logging.xml') {
         exclude 'SystemOutPrint'  // too many to worry about, review later
-        exclude 'SystemErrPrint'    // too many to worry about, review later
+        exclude 'SystemErrPrint'  // too many to worry about, review later
+        'Println' {
+            doNotApplyToFileNames='genArrayAccess.groovy,genArrayUtil.groovy,genDgmMath.groovy,genMathModification.groovy,'
+        }
     }
     ruleset('rulesets/braces.xml') {
         exclude 'ForStatementBraces' // for statements without braces seems acceptable in our coding standards
@@ -221,7 +224,6 @@ ruleset {
     }
     ruleset('rulesets/dry.xml') {
         exclude 'DuplicateNumberLiteral'    // too many to worry about, review later
-        exclude 'DuplicateStringLiteralRule'    // too many to worry about, review later
         exclude 'DuplicateStringLiteral'    // too many to worry about, review later
     }
     ruleset('rulesets/design.xml') {
diff --git a/src/main/groovy/org/codehaus/groovy/classgen/genArrayAccess.groovy b/src/main/groovy/org/codehaus/groovy/classgen/genArrayAccess.groovy
index 08cb68a..46521c1 100644
--- a/src/main/groovy/org/codehaus/groovy/classgen/genArrayAccess.groovy
+++ b/src/main/groovy/org/codehaus/groovy/classgen/genArrayAccess.groovy
@@ -18,15 +18,18 @@
  */
 package org.codehaus.groovy.classgen
 
+// TODO this generator template has drifted apart from the now modified generated classes
+// Is it worth keeping this template and/or getting it back up to date?
+
 println """
 package org.codehaus.groovy.runtime.dgmimpl;
 
 import groovy.lang.MetaClassImpl;
 import groovy.lang.MetaMethod;
-import org.codehaus.groovy.runtime.callsite.CallSite;
-import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite;
 import org.codehaus.groovy.reflection.CachedClass;
 import org.codehaus.groovy.reflection.ReflectionCache;
+import org.codehaus.groovy.runtime.callsite.CallSite;
+import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite;
 
 public class ArrayOperations {
   ${genInners()}
@@ -34,17 +37,17 @@ public class ArrayOperations {
 """
 
 def genInners () {
-    def res = ""
+    def res = ''
 
     final Map primitives = [
-            "boolean": "Boolean",
-            "byte": "Byte",
-            "char": "Character",
-            "short": "Short",
-            "int": "Integer",
-            "long": "Long",
-            "float": "Float",
-            "double": "Double"
+            'boolean': 'Boolean',
+            'byte': 'Byte',
+            'char': 'Character',
+            'short': 'Short',
+            'int': 'Integer',
+            'long': 'Long',
+            'float': 'Float',
+            'double': 'Double'
     ]
 
     primitives.each {primName, clsName ->
@@ -62,7 +65,7 @@ def genInners () {
 
             public Object invoke(Object object, Object[] args) {
                 final ${primName}[] objects = (${primName}[]) object;
-                return objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)];
+                return objects[normaliseIndex((Integer) args[0], objects.length)];
             }
 
             public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) {
@@ -72,14 +75,14 @@ def genInners () {
                     return new PojoMetaMethodSite(site, metaClass, metaMethod, params) {
                         public Object invoke(Object receiver, Object[] args) {
                             final ${primName}[] objects = (${primName}[]) receiver;
-                            return objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)];
+                            return objects[normaliseIndex((Integer) args[0], objects.length)];
                         }
 
                         public Object callBinop(Object receiver, Object arg) {
                             if ((receiver instanceof ${primName}[] && arg instanceof Integer)
                                     && checkMetaClass()) {
                                 final ${primName}[] objects = (${primName}[]) receiver;
-                                return objects[normaliseIndex(((Integer) arg).intValue(), objects.length)];
+                                return objects[normaliseIndex((Integer) arg, objects.length)];
                             }
                             else
                               return super.callBinop(receiver,arg);
@@ -87,7 +90,7 @@ def genInners () {
 
                         public Object invokeBinop(Object receiver, Object arg) {
                             final ${primName}[] objects = (${primName}[]) receiver;
-                            return objects[normaliseIndex(((Integer) arg).intValue(), objects.length)];
+                            return objects[normaliseIndex((Integer) arg, objects.length)];
                         }
                     };
             }
@@ -109,7 +112,7 @@ def genInners () {
 
             public Object invoke(Object object, Object[] args) {
                 final ${primName}[] objects = (${primName}[]) object;
-                final int index = normaliseIndex(((Integer) args[0]).intValue(), objects.length);
+                final int index = normaliseIndex((Integer) args[0], objects.length);
                 Object newValue = args[1];
                 if (!(newValue instanceof ${clsName})) {
                     Number n = (Number) newValue;
@@ -129,7 +132,7 @@ def genInners () {
                             if ((receiver instanceof ${primName}[] && args[0] instanceof Integer && args[1] instanceof ${clsName} )
                                     && checkMetaClass()) {
                                 final ${primName}[] objects = (${primName}[]) receiver;
-                                objects[normaliseIndex(((Integer) args[0]).intValue(), objects.length)] = ((${clsName})args[1]).${primName}Value();
+                                objects[normaliseIndex((Integer) args[0], objects.length)] = ((${clsName})args[1]).${primName}Value();
                                 return null;
                             }
                             else
diff --git a/src/main/groovy/org/codehaus/groovy/classgen/genArrays.groovy b/src/main/groovy/org/codehaus/groovy/classgen/genArrayUtil.groovy
similarity index 78%
rename from src/main/groovy/org/codehaus/groovy/classgen/genArrays.groovy
rename to src/main/groovy/org/codehaus/groovy/classgen/genArrayUtil.groovy
index 9bbe3cf..61891a9 100644
--- a/src/main/groovy/org/codehaus/groovy/classgen/genArrays.groovy
+++ b/src/main/groovy/org/codehaus/groovy/classgen/genArrayUtil.groovy
@@ -27,27 +27,27 @@ public class ArrayUtil {
 """
 
 def genMethods () {
-    def res = ""
+    def res = ''
     for (i in 1..250)
-      res += "\n\n" + genMethod (i)
+      res += '\n\n' + genMethod (i)
     res
 }
 
 def genMethod (int paramNum) {
-    def res = "public static Object [] createArray ("
+    def res = 'public static Object [] createArray ('
     for (k in 0..<paramNum) {
-        res += "Object arg" + k
+        res += 'Object arg' + k
         if (k != paramNum-1)
-          res += ", "
+          res += ', '
     }
-    res += ") {\n"
-    res += "return new Object [] {\n"
+    res += ') {\n'
+    res += 'return new Object [] {\n'
         for (k in 0..<paramNum) {
-            res += "arg" + k
+            res += 'arg' + k
             if (k != paramNum-1)
-              res += ", "
+              res += ', '
         }
-        res += "};\n"
-    res += "}"
+        res += '};\n'
+    res += '}'
     res
 }
diff --git a/src/main/groovy/org/codehaus/groovy/classgen/genDgmMath.groovy b/src/main/groovy/org/codehaus/groovy/classgen/genDgmMath.groovy
index 71bdd5f..c1fbafa 100644
--- a/src/main/groovy/org/codehaus/groovy/classgen/genDgmMath.groovy
+++ b/src/main/groovy/org/codehaus/groovy/classgen/genDgmMath.groovy
@@ -18,22 +18,22 @@
  */
 package org.codehaus.groovy.classgen
 
-def types = ["Integer", "Long", "Float", "Double"]
+def types = ['Integer', 'Long', 'Float', 'Double']
 
 def getMath (a,b) {
-    if (a == "Double" || b == "Double" || a == "Float" || b == "Float")
-      return "FloatingPointMath"
+    if (a == 'Double' || b == 'Double' || a == 'Float' || b == 'Float')
+      return 'FloatingPointMath'
 
-    if (a == "Long" || b == "Long")
-      return "LongMath"
+    if (a == 'Long' || b == 'Long')
+      return 'LongMath'
 
-    "IntegerMath"
+    'IntegerMath'
 }
 
-println """
+println '''
 public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) {
     NumberMath m = NumberMath.getMath((Number)receiver, (Number)args[0]);
-"""
+'''
 
 types.each {
     a ->
@@ -54,10 +54,10 @@ types.each {
             };
         """
     }
-    println "}"
+    println '}'
 }
 
-println """
+println '''
     return new NumberNumberCallSite (site, metaClass, metaMethod, params, (Number)receiver, (Number)args[0]){
         public final Object invoke(Object receiver, Object[] args) {
             return math.addImpl((Number)receiver,(Number)args[0]);
@@ -67,21 +67,26 @@ println """
             return math.addImpl((Number)receiver,(Number)arg);
         }
 }
-"""
+'''
 
 for (i in 2..256) {
     print "public Object invoke$i (Object receiver, "
-    for (j in 1..(i-1)) {
-        print "Object a$j, "
-    }
+    printParams(i)
     println "Object a$i) {"
+    print '  return invoke (receiver, new Object[] {'
+    printArgs(i)
+    println "a$i} );"
+    println '}'
+}
 
-    print "  return invoke (receiver, new Object[] {"
+private void printParams(int i) {
+    for (j in 1..(i - 1)) {
+        print "Object a$j, "
+    }
+}
 
-    for (j in 1..(i-1)) {
+private void printArgs(int i) {
+    for (j in 1..(i - 1)) {
         print "a$j, "
     }
-    println "a$i} );"
-
-    println "}"
 }
diff --git a/src/main/groovy/org/codehaus/groovy/classgen/genMathModification.groovy b/src/main/groovy/org/codehaus/groovy/classgen/genMathModification.groovy
index 10cc7eb..cf326dd 100644
--- a/src/main/groovy/org/codehaus/groovy/classgen/genMathModification.groovy
+++ b/src/main/groovy/org/codehaus/groovy/classgen/genMathModification.groovy
@@ -19,25 +19,25 @@
 package org.codehaus.groovy.classgen
 
 def ops = [
-        "plus",
-        "minus",
-        "multiply",
-        "div",
-        "or",
-        "and",
-        "xor",
-        "intdiv",
-        "mod",
-        "leftShift",
-        "rightShift",
-        "rightShiftUnsigned"
+        'plus',
+        'minus',
+        'multiply',
+        'div',
+        'or',
+        'and',
+        'xor',
+        'intdiv',
+        'mod',
+        'leftShift',
+        'rightShift',
+        'rightShiftUnsigned'
 ]
 
-def numbers = ["Byte":"byte", "Short":"short", "Integer":"int", "Long":"long", "Float":"float", "Double":"double"]
+def numbers = ['Byte':'byte', 'Short':'short', 'Integer':'int', 'Long':'long', 'Float':'float', 'Double':'double']
 
 ops.each { op ->
     numbers.each { wrappedType, type ->
-        println "public boolean ${type}_${op};";    
+        println "public boolean ${type}_${op};"
     }
 }
 
@@ -48,12 +48,12 @@ ops.each { op ->
                 ${type}_${op} = true;
             }"""
     }
-    println "if (klazz==Object.class) {"
+    println 'if (klazz==Object.class) {'
     numbers.each { wrappedType, type ->
         println "${type}_${op} = true;"
             }
-    println "}"
-    println "}"
+    println '}'
+    println '}'
 }
 
 ops.each { op ->
@@ -66,7 +66,7 @@ ops.each { op ->
                       return ${op}Slow(op1, op2);
                    }
                    else {
-                      return ${math.resType != type1 ? "((" + math.resType+ ")op1)" : "op1"} ${math[op]} ${math.resType != type2 ? "((" + math.resType+ ")op2)" : "op2"};
+                      return ${math.resType != type1 ? '((' + math.resType+ ')op1)' : 'op1'} ${math[op]} ${math.resType != type2 ? '((' + math.resType+ ')op2)' : 'op2'};
                    }
                 }"""
                 println """private static ${math.resType} ${op}Slow(${type1} op1,${type2} op2) {
@@ -78,56 +78,56 @@ ops.each { op ->
 }
 
 def isFloatingPoint(number) {
-    return number == "Double" || number == "Float";
+    number == 'Double' || number == 'Float'
 }
 
 def isLong(number) {
-    return number == "Long";
+    number == 'Long'
 }
 
 def getMath (left, right) {
     if (isFloatingPoint(left) || isFloatingPoint(right)) {
         return [
-                resType : "double",
+                resType : 'double',
 
-                plus : "+",
-                minus : "-",
-                multiply : "*",
-                div : "/",
-        ];
+                plus : '+',
+                minus : '-',
+                multiply : '*',
+                div : '/',
+        ]
     }
     if (isLong(left) || isLong(right)){
         return [
-                resType : "long",
+                resType : 'long',
 
-                plus : "+",
-                minus : "-",
-                multiply : "*",
-                div : "/",
-                or : "|",
-                and : "&",
-                xor : "^",
-                intdiv : "/",
-                mod : "%",
-                leftShift : "<<",
-                rightShift : ">>",
-                rightShiftUnsigned : ">>>"
+                plus : '+',
+                minus : '-',
+                multiply : '*',
+                div : '/',
+                or : '|',
+                and : '&',
+                xor : '^',
+                intdiv : '/',
+                mod : '%',
+                leftShift : '<<',
+                rightShift : '>>',
+                rightShiftUnsigned : '>>>'
         ]
     }
-    return [
-            resType : "int",
+    [
+            resType : 'int',
 
-            plus : "+",
-            minus : "-",
-            multiply : "*",
-            div : "/",
-            or : "|",
-            and : "&",
-            xor : "^",
-            intdiv : "/",
-            mod : "%",
-            leftShift : "<<",
-            rightShift : ">>",
-            rightShiftUnsigned : ">>>"
+            plus : '+',
+            minus : '-',
+            multiply : '*',
+            div : '/',
+            or : '|',
+            and : '&',
+            xor : '^',
+            intdiv : '/',
+            mod : '%',
+            leftShift : '<<',
+            rightShift : '>>',
+            rightShiftUnsigned : '>>>'
     ]
 }
diff --git a/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
index 8201d50..6982b86 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/ASTTestTransformation.groovy
@@ -64,14 +64,14 @@ class ASTTestTransformation extends AbstractASTTransformation implements Compila
         }
         member = annotationNode.getMember('value')
         if (member && !(member instanceof ClosureExpression)) {
-            throw new SyntaxException('ASTTest value must be a closure', member.getLineNumber(), member.getColumnNumber())
+            throw new SyntaxException('ASTTest value must be a closure', member.lineNumber, member.columnNumber)
         }
         if (!member && !annotationNode.getNodeMetaData(ASTTestTransformation)) {
-            throw new SyntaxException('Missing test expression', annotationNode.getLineNumber(), annotationNode.getColumnNumber())
+            throw new SyntaxException('Missing test expression', annotationNode.lineNumber, annotationNode.columnNumber)
         }
         // convert value into node metadata so that the expression doesn't mix up with other AST xforms like type checking
         annotationNode.putNodeMetaData(ASTTestTransformation, member)
-        annotationNode.getMembers().remove('value')
+        annotationNode.members.remove('value')
 
         def pcallback = compilationUnit.progressCallback
         def callback = new CompilationUnit.ProgressCallback() {
@@ -85,8 +85,8 @@ class ASTTestTransformation extends AbstractASTTransformation implements Compila
                     for (int i = testClosure.lineNumber; i <= testClosure.lastLineNumber; i++) {
                         sb.append(source.source.getLine(i, new Janitor())).append('\n')
                     }
-                    def testSource = sb.substring(testClosure.columnNumber, sb.length())
-                    testSource = testSource.substring(0, testSource.lastIndexOf('}'))
+                    def testSource = sb[testClosure.columnNumber..<sb.length()]
+                    testSource = testSource[0..<testSource.lastIndexOf('}')]
                     CompilerConfiguration config = new CompilerConfiguration()
                     def customizer = new ImportCustomizer()
                     config.addCompilationCustomizers(customizer)
@@ -124,8 +124,7 @@ class ASTTestTransformation extends AbstractASTTransformation implements Compila
             callback = pcallback
         }
 
-        compilationUnit.setProgressCallback(callback)
-
+        compilationUnit.progressCallback = callback
     }
 
     void setCompilationUnit(final CompilationUnit unit) {
@@ -152,8 +151,8 @@ class ASTTestTransformation extends AbstractASTTransformation implements Compila
                     if (column > 40) {
                         int start = column - 30 - 1
                         int end = (column + 10 > text.length() ? text.length() : column + 10 - 1)
-                        sample = '   ' + text.substring(start, end) + Utilities.eol() + '   ' +
-                                marker.substring(start, marker.length())
+                        sample = '   ' + text[start..<end] + Utilities.eol() + '   ' +
+                                marker[start..<marker.length()]
                     } else {
                         sample = '   ' + text + Utilities.eol() + '   ' + marker
                     }
diff --git a/src/main/groovy/org/codehaus/groovy/transform/tailrec/TailRecursiveASTTransformation.groovy b/src/main/groovy/org/codehaus/groovy/transform/tailrec/TailRecursiveASTTransformation.groovy
index 05a15e6..0b71062 100644
--- a/src/main/groovy/org/codehaus/groovy/transform/tailrec/TailRecursiveASTTransformation.groovy
+++ b/src/main/groovy/org/codehaus/groovy/transform/tailrec/TailRecursiveASTTransformation.groovy
@@ -53,9 +53,9 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
 
     private static final Class MY_CLASS = TailRecursive
     private static final ClassNode MY_TYPE = new ClassNode(MY_CLASS)
-    static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage()
-    private HasRecursiveCalls hasRecursiveCalls = new HasRecursiveCalls()
-    private TernaryToIfStatementConverter ternaryToIfStatement = new TernaryToIfStatementConverter()
+    static final String MY_TYPE_NAME = '@' + MY_TYPE.nameWithoutPackage
+    private final HasRecursiveCalls hasRecursiveCalls = new HasRecursiveCalls()
+    private final TernaryToIfStatementConverter ternaryToIfStatement = new TernaryToIfStatementConverter()
 
 
     @Override
@@ -65,7 +65,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
         MethodNode method = nodes[1] as MethodNode
 
         if (method.isAbstract()) {
-            addError("Annotation " + MY_TYPE_NAME + " cannot be used for abstract methods.", method)
+            addError("Annotation $MY_TYPE_NAME cannot be used for abstract methods.", method)
             return
         }
 
@@ -75,7 +75,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
                 if (annotationNode.classNode == MY_TYPE)
                     break
                 if (annotationNode.classNode == memoizedClassNode) {
-                    addError("Annotation " + MY_TYPE_NAME + " must be placed before annotation @Memoized.", annotationNode)
+                    addError("Annotation $MY_TYPE_NAME must be placed before annotation @Memoized.", annotationNode)
                     return
                 }
             }
@@ -83,7 +83,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
 
         if (!hasRecursiveMethodCalls(method)) {
             AnnotationNode annotationNode = method.getAnnotations(ClassHelper.make(TailRecursive))[0]
-            addError("No recursive calls detected. You must remove annotation " + MY_TYPE_NAME + ".", annotationNode)
+            addError("No recursive calls detected. You must remove annotation ${MY_TYPE_NAME}.", annotationNode)
             return
         }
 
@@ -93,7 +93,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
 
     private boolean hasAnnotation(MethodNode methodNode, ClassNode annotation) {
         List annots = methodNode.getAnnotations(annotation)
-        return (annots != null && annots.size() > 0)
+        annots != null && annots.size() > 0
     }
 
 
@@ -106,7 +106,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
     }
 
     private void transformVoidMethodToIteration(MethodNode method) {
-        addError("Void methods are not supported by @TailRecursive yet.", method)
+        addError('Void methods are not supported by @TailRecursive yet.', method)
     }
 
     private void transformNonVoidMethodToIteration(MethodNode method, SourceUnit source) {
@@ -133,7 +133,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
             if (!(node instanceof ReturnStatement)) {
                 return false
             }
-            return (((ReturnStatement) node).expression instanceof TernaryExpression)
+            ((ReturnStatement) node).expression instanceof TernaryExpression
         }
         Closure<Statement> replaceWithIfStatement = { ReturnStatement statement ->
             ternaryToIfStatement.convert(statement)
@@ -167,7 +167,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
             String iterationVariableName = iterationVariableName(paramName)
             nameAndTypeMapping[paramName] = [name: iterationVariableName, type: paramType]
         }
-        return nameAndTypeMapping
+        nameAndTypeMapping
     }
 
     // Public b/c there are tests for this method
@@ -179,7 +179,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
             String iterationVariableName = this.iterationVariableName(paramName)
             positionMapping[index] = [name: iterationVariableName, type: paramType]
         }
-        return positionMapping
+        positionMapping
     }
 
     private String iterationVariableName(String paramName) {
@@ -203,7 +203,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
             if (!(inner instanceof MethodCallExpression) && !(inner instanceof StaticMethodCallExpression)) {
                 return false
             }
-            return isRecursiveIn(inner, method)
+            isRecursiveIn(inner, method)
         }
         Closure<Statement> replaceWithContinueBlock = { ReturnStatement statement ->
             new ReturnStatementToIterationConverter().convert(statement, positionMapping)
@@ -224,7 +224,7 @@ class TailRecursiveASTTransformation extends AbstractASTTransformation {
             if (!(inner instanceof MethodCallExpression) && !(inner instanceof StaticMethodCallExpression)) {
                 return false
             }
-            return isRecursiveIn(inner, method)
+            isRecursiveIn(inner, method)
         }
         Closure<Statement> replaceWithThrowLoopException = { ReturnStatement statement ->
             new ReturnStatementToIterationConverter(recurStatement: AstHelper.recurByThrowStatement()).convert(statement, positionMapping)