You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2020/02/14 20:36:02 UTC

[groovy] branch GROOVY_3_0_X updated (30ef550 -> 3c5182c)

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

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


    from 30ef550  GROOVY-4694: Move AstBuilderTransformation Global xForm to separate module
     new c53c976  minor edits
     new 272eb89  minor edits
     new f149acd  add builder for DeclarationExpression
     new 70218ab  add builders for BytecodeExpression supporting closure/lambda
     new 48c55d4  reorder methods
     new 3c5182c  minor edits

The 6 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:
 .../groovy/ast/expr/PropertyExpression.java        |  89 +--
 .../codehaus/groovy/ast/expr/TupleExpression.java  |  66 +-
 .../codehaus/groovy/ast/tools/GeneralUtils.java    | 751 +++++++++++----------
 .../org/codehaus/groovy/classgen/Verifier.java     |  13 +-
 .../classgen/asm/BinaryExpressionHelper.java       | 259 ++++---
 ...icTypesBinaryExpressionMultiTypeDispatcher.java |   5 +-
 .../classgen/asm/sc/StaticTypesCallSiteWriter.java |  21 +-
 .../asm/sc/StaticTypesUnaryExpressionHelper.java   |  99 ++-
 .../transformers/ConstructorCallTransformer.java   |  36 +-
 .../groovy/transform/stc/STCAssignmentTest.groovy  |  15 -
 10 files changed, 650 insertions(+), 704 deletions(-)


[groovy] 05/06: reorder methods

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

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

commit 48c55d4e1b73505bd882e5a8b65572dde4fed635
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Feb 14 13:00:30 2020 -0600

    reorder methods
    
    (cherry picked from commit d0568bd473c0cec69e35ba545329c4051c44600e)
---
 .../codehaus/groovy/ast/tools/GeneralUtils.java    | 625 +++++++++++----------
 1 file changed, 316 insertions(+), 309 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
index 47b45cc..bf212d8 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -61,7 +61,6 @@ import org.codehaus.groovy.ast.stmt.Statement;
 import org.codehaus.groovy.ast.stmt.ThrowStatement;
 import org.codehaus.groovy.ast.stmt.TryCatchStatement;
 import org.codehaus.groovy.classgen.BytecodeExpression;
-import org.codehaus.groovy.classgen.Verifier;
 import org.codehaus.groovy.control.io.ReaderSource;
 import org.codehaus.groovy.runtime.GeneratedClosure;
 import org.codehaus.groovy.syntax.Token;
@@ -97,25 +96,25 @@ public class GeneralUtils {
     private static final Token PLUS = Token.newSymbol(Types.PLUS, -1, -1);
     private static final Token INDEX = Token.newSymbol("[", -1, -1);
 
-    public static BinaryExpression andX(Expression lhv, Expression rhv) {
+    public static BinaryExpression andX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, AND, rhv);
     }
 
-    public static ArgumentListExpression args(Expression... expressions) {
+    public static ArgumentListExpression args(final Expression... expressions) {
         List<Expression> args = new ArrayList<Expression>();
         Collections.addAll(args, expressions);
         return new ArgumentListExpression(args);
     }
 
-    public static ArgumentListExpression args(List<Expression> expressions) {
+    public static ArgumentListExpression args(final List<Expression> expressions) {
         return new ArgumentListExpression(expressions);
     }
 
-    public static ArgumentListExpression args(Parameter[] parameters) {
+    public static ArgumentListExpression args(final Parameter[] parameters) {
         return new ArgumentListExpression(parameters);
     }
 
-    public static ArgumentListExpression args(String... names) {
+    public static ArgumentListExpression args(final String... names) {
         List<Expression> vars = new ArrayList<Expression>();
         for (String name : names) {
             vars.add(varX(name));
@@ -123,43 +122,53 @@ public class GeneralUtils {
         return new ArgumentListExpression(vars);
     }
 
-    public static Statement assignS(Expression target, Expression value) {
+    public static Statement assignS(final Expression target, final Expression value) {
         return new ExpressionStatement(assignX(target, value));
     }
 
-    public static Expression assignX(Expression target, Expression value) {
+    public static Expression assignX(final Expression target, final Expression value) {
         return new BinaryExpression(target, ASSIGN, value);
     }
 
-    public static Expression attrX(Expression oe, Expression prop) {
+    public static Expression attrX(final Expression oe, final Expression prop) {
         return new AttributeExpression(oe, prop);
     }
 
-    public static BinaryExpression binX(Expression left, Token token, Expression right) {
+    public static BinaryExpression binX(final Expression left, final Token token, final Expression right) {
         return new BinaryExpression(left, token, right);
     }
 
-    public static BlockStatement block(VariableScope varScope, Statement... stmts) {
+    public static BlockStatement block(final VariableScope varScope, final Statement... stmts) {
         BlockStatement block = new BlockStatement();
         block.setVariableScope(varScope);
-        for (Statement stmt : stmts) block.addStatement(stmt);
+        for (Statement stmt : stmts) {
+            block.addStatement(stmt);
+        }
         return block;
     }
 
-    public static BlockStatement block(VariableScope varScope, List<Statement> stmts) {
+    public static BlockStatement block(final VariableScope varScope, final List<Statement> stmts) {
         BlockStatement block = new BlockStatement();
         block.setVariableScope(varScope);
-        for (Statement stmt : stmts) block.addStatement(stmt);
+        for (Statement stmt : stmts) {
+            block.addStatement(stmt);
+        }
         return block;
     }
 
-    public static BlockStatement block(Statement... stmts) {
+    public static BlockStatement block(final Statement... stmts) {
         BlockStatement block = new BlockStatement();
-        for (Statement stmt : stmts) block.addStatement(stmt);
+        for (Statement stmt : stmts) {
+            block.addStatement(stmt);
+        }
         return block;
     }
 
-    public static BytecodeExpression bytecodeX(Consumer<MethodVisitor> writer) {
+    public static BooleanExpression boolX(final Expression boolExpr) {
+        return new BooleanExpression(boolExpr);
+    }
+
+    public static BytecodeExpression bytecodeX(final Consumer<MethodVisitor> writer) {
         return new BytecodeExpression() {
             @Override
             public void visit(final MethodVisitor visitor) {
@@ -168,194 +177,108 @@ public class GeneralUtils {
         };
     }
 
-    public static BytecodeExpression bytecodeX(ClassNode type, Consumer<MethodVisitor> writer) {
+    public static BytecodeExpression bytecodeX(final ClassNode type, final Consumer<MethodVisitor> writer) {
         BytecodeExpression expression = bytecodeX(writer);
         expression.setType(type);
         return expression;
     }
 
-    public static MethodCallExpression callSuperX(String methodName, Expression args) {
+    public static MethodCallExpression callSuperX(final String methodName) {
+        return callSuperX(methodName, MethodCallExpression.NO_ARGUMENTS);
+    }
+
+    public static MethodCallExpression callSuperX(final String methodName, final Expression args) {
         return callX(varX("super"), methodName, args);
     }
 
-    public static MethodCallExpression callSuperX(String methodName) {
-        return callSuperX(methodName, MethodCallExpression.NO_ARGUMENTS);
+    public static MethodCallExpression callThisX(final String methodName) {
+        return callThisX(methodName, MethodCallExpression.NO_ARGUMENTS);
     }
 
-    public static MethodCallExpression callThisX(String methodName, Expression args) {
+    public static MethodCallExpression callThisX(final String methodName, final Expression args) {
         return callX(varX("this"), methodName, args);
     }
 
-    public static MethodCallExpression callThisX(String methodName) {
-        return callThisX(methodName, MethodCallExpression.NO_ARGUMENTS);
+    public static MethodCallExpression callX(final Expression receiver, final String methodName) {
+        return callX(receiver, methodName, MethodCallExpression.NO_ARGUMENTS);
     }
 
-    public static MethodCallExpression callX(Expression receiver, String methodName, Expression args) {
+    public static MethodCallExpression callX(final Expression receiver, final String methodName, final Expression args) {
         return new MethodCallExpression(receiver, methodName, args);
     }
 
-    public static MethodCallExpression callX(Expression receiver, Expression method, Expression args) {
+    public static MethodCallExpression callX(final Expression receiver, final Expression method, final Expression args) {
         return new MethodCallExpression(receiver, method, args);
     }
 
-    public static MethodCallExpression callX(Expression receiver, String methodName) {
+    public static StaticMethodCallExpression callX(final ClassNode receiver, final String methodName) {
         return callX(receiver, methodName, MethodCallExpression.NO_ARGUMENTS);
     }
 
-    public static StaticMethodCallExpression callX(ClassNode receiver, String methodName, Expression args) {
+    public static StaticMethodCallExpression callX(final ClassNode receiver, final String methodName, final Expression args) {
         return new StaticMethodCallExpression(receiver, methodName, args);
     }
 
-    public static StaticMethodCallExpression callX(ClassNode receiver, String methodName) {
-        return callX(receiver, methodName, MethodCallExpression.NO_ARGUMENTS);
-    }
-
-    public static CastExpression castX(ClassNode type, Expression expression) {
+    public static CastExpression castX(final ClassNode type, final Expression expression) {
         return new CastExpression(type, expression);
     }
 
-    public static BooleanExpression boolX(Expression boolExpr) {
-        return new BooleanExpression(boolExpr);
+    public static CastExpression castX(final ClassNode type, final Expression expression, final boolean ignoreAutoboxing) {
+        return new CastExpression(type, expression, ignoreAutoboxing);
     }
 
-    public static CastExpression castX(ClassNode type, Expression expression, boolean ignoreAutoboxing) {
-        return new CastExpression(type, expression, ignoreAutoboxing);
+    public static CatchStatement catchS(final Parameter variable, final Statement code) {
+        return new CatchStatement(variable, code);
     }
 
-    public static ClassExpression classX(ClassNode clazz) {
+    public static ClassExpression classX(final ClassNode clazz) {
         return new ClassExpression(clazz);
     }
 
-    public static ClassExpression classX(Class clazz) {
+    public static ClassExpression classX(final Class<?> clazz) {
         return classX(ClassHelper.make(clazz).getPlainNodeReference());
     }
 
-    public static ClosureExpression closureX(Parameter[] params, Statement code) {
+    public static ClosureExpression closureX(final Parameter[] params, final Statement code) {
         return new ClosureExpression(params, code);
     }
 
-    public static ClosureExpression closureX(Statement code) {
+    public static ClosureExpression closureX(final Statement code) {
         return closureX(Parameter.EMPTY_ARRAY, code);
     }
 
-    public static Parameter[] cloneParams(Parameter[] source) {
-        Parameter[] result = new Parameter[source.length];
-        for (int i = 0; i < source.length; i++) {
-            Parameter srcParam = source[i];
-            Parameter dstParam = new Parameter(srcParam.getOriginType(), srcParam.getName());
-            result[i] = dstParam;
-        }
-        return result;
-    }
-
     /**
-     * Build a binary expression that compares two values
+     * Builds a binary expression that compares two values.
+     *
      * @param lhv expression for the value to compare from
      * @param rhv expression for the value value to compare to
      * @return the expression comparing two values
      */
-    public static BinaryExpression cmpX(Expression lhv, Expression rhv) {
+    public static BinaryExpression cmpX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, CMP, rhv);
     }
 
-    public static ConstantExpression constX(Object val) {
+    public static ConstantExpression constX(final Object val) {
         return new ConstantExpression(val);
     }
 
-    public static ConstantExpression constX(Object val, boolean keepPrimitive) {
+    public static ConstantExpression constX(final Object val, final boolean keepPrimitive) {
         return new ConstantExpression(val, keepPrimitive);
     }
 
-    /**
-     * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
-     * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
-     * <p>
-     * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
-     */
-    public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, List<AnnotationNode> notCopied) {
-        copyAnnotatedNodeAnnotations(annotatedNode, copied, notCopied, true);
-    }
-
-    /**
-     * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
-     * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
-     * {@link groovy.transform.Generated} annotations will be copied if {@code includeGenerated} is true.
-     * <p>
-     * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
-     */
-    public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, List<AnnotationNode> notCopied, boolean includeGenerated) {
-        List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
-        for (AnnotationNode annotation : annotationList)  {
-
-            List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
-            if (annotations.isEmpty()) continue;
-
-            if (hasClosureMember(annotation)) {
-                notCopied.add(annotation);
-                continue;
-            }
-
-            if (!includeGenerated && annotation.getClassNode().getName().equals("groovy.transform.Generated")) {
-                continue;
-            }
-
-            AnnotationNode retentionPolicyAnnotation = annotations.get(0);
-            Expression valueExpression = retentionPolicyAnnotation.getMember("value");
-            if (!(valueExpression instanceof PropertyExpression)) continue;
-
-            PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
-            boolean processAnnotation =
-                    propertyExpression.getProperty() instanceof ConstantExpression &&
-                            (
-                                    "RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
-                                            "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
-                            );
-
-            if (processAnnotation)  {
-                AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
-                for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet())  {
-                    newAnnotation.addMember(member.getKey(), member.getValue());
-                }
-                newAnnotation.setSourcePosition(annotatedNode);
-
-                copied.add(newAnnotation);
-            }
-        }
-    }
-
-    public static Statement createConstructorStatementDefault(FieldNode fNode) {
-        final String name = fNode.getName();
-        final ClassNode fType = fNode.getType();
-        final Expression fieldExpr = propX(varX("this"), name);
-        Expression initExpr = fNode.getInitialValueExpression();
-        Statement assignInit;
-        if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression)initExpr).isNullExpression())) {
-            if (ClassHelper.isPrimitiveType(fType)) {
-                assignInit = EmptyStatement.INSTANCE;
-            } else {
-                assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
-            }
-        } else {
-            assignInit = assignS(fieldExpr, initExpr);
-        }
-        fNode.setInitialValueExpression(null);
-        Expression value = findArg(name);
-        return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
-    }
-
-    public static ConstructorCallExpression ctorX(ClassNode type, Expression args) {
+    public static ConstructorCallExpression ctorX(final ClassNode type, final Expression args) {
         return new ConstructorCallExpression(type, args);
     }
 
-    public static ConstructorCallExpression ctorX(ClassNode type) {
+    public static ConstructorCallExpression ctorX(final ClassNode type) {
         return new ConstructorCallExpression(type, ArgumentListExpression.EMPTY_ARGUMENTS);
     }
 
-    public static Statement ctorSuperS(Expression args) {
+    public static Statement ctorSuperS(final Expression args) {
         return stmt(ctorX(ClassNode.SUPER, args));
     }
 
-    public static Statement ctorThisS(Expression args) {
+    public static Statement ctorThisS(final Expression args) {
         return stmt(ctorX(ClassNode.THIS, args));
     }
 
@@ -367,35 +290,39 @@ public class GeneralUtils {
         return stmt(ctorX(ClassNode.THIS));
     }
 
-    public static Statement declS(Expression target, Expression init) {
+    public static Statement declS(final Expression target, final Expression init) {
         return stmt(declX(target, init));
     }
 
-    public static DeclarationExpression declX(Expression target, Expression init) {
+    public static DeclarationExpression declX(final Expression target, final Expression init) {
         return new DeclarationExpression(target, ASSIGN, init);
     }
 
-    public static BinaryExpression eqX(Expression lhv, Expression rhv) {
+    public static MapEntryExpression entryX(final Expression key, final Expression value) {
+        return new MapEntryExpression(key, value);
+    }
+
+    public static BinaryExpression eqX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, EQ, rhv);
     }
 
-    public static BooleanExpression equalsNullX(Expression argExpr) {
+    public static BooleanExpression equalsNullX(final Expression argExpr) {
         return new BooleanExpression(eqX(argExpr, new ConstantExpression(null)));
     }
 
-    public static FieldExpression fieldX(FieldNode fieldNode) {
+    public static FieldExpression fieldX(final FieldNode fieldNode) {
         return new FieldExpression(fieldNode);
     }
 
-    public static FieldExpression fieldX(ClassNode owner, String fieldName) {
+    public static FieldExpression fieldX(final ClassNode owner, final String fieldName) {
         return new FieldExpression(owner.getField(fieldName));
     }
 
-    public static Expression findArg(String argName) {
+    public static Expression findArg(final String argName) {
         return new PropertyExpression(new VariableExpression("args"), argName);
     }
 
-    public static List<MethodNode> getAllMethods(ClassNode type) {
+    public static List<MethodNode> getAllMethods(final ClassNode type) {
         ClassNode node = type;
         List<MethodNode> result = new ArrayList<MethodNode>();
         while (node != null) {
@@ -405,7 +332,7 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<PropertyNode> getAllProperties(ClassNode type) {
+    public static List<PropertyNode> getAllProperties(final ClassNode type) {
         ClassNode node = type;
         List<PropertyNode> result = new ArrayList<PropertyNode>();
         while (node != null) {
@@ -415,12 +342,8 @@ public class GeneralUtils {
         return result;
     }
 
-    public static String getGetterName(PropertyNode pNode) {
-        return "get" + Verifier.capitalize(pNode.getName());
-    }
-
-    public static List<FieldNode> getInstanceNonPropertyFields(ClassNode cNode) {
-        final List<FieldNode> result = new ArrayList<FieldNode>();
+    public static List<FieldNode> getInstanceNonPropertyFields(final ClassNode cNode) {
+        List<FieldNode> result = new ArrayList<FieldNode>();
         for (FieldNode fNode : cNode.getFields()) {
             if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
                 result.add(fNode);
@@ -429,7 +352,7 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<String> getInstanceNonPropertyFieldNames(ClassNode cNode) {
+    public static List<String> getInstanceNonPropertyFieldNames(final ClassNode cNode) {
         List<FieldNode> fList = getInstanceNonPropertyFields(cNode);
         List<String> result = new ArrayList<String>(fList.size());
         for (FieldNode fNode : fList) {
@@ -438,8 +361,8 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<PropertyNode> getInstanceProperties(ClassNode cNode) {
-        final List<PropertyNode> result = new ArrayList<PropertyNode>();
+    public static List<PropertyNode> getInstanceProperties(final ClassNode cNode) {
+        List<PropertyNode> result = new ArrayList<PropertyNode>();
         for (PropertyNode pNode : cNode.getProperties()) {
             if (!pNode.isStatic()) {
                 result.add(pNode);
@@ -448,7 +371,7 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<String> getInstancePropertyNames(ClassNode cNode) {
+    public static List<String> getInstancePropertyNames(final ClassNode cNode) {
         List<PropertyNode> pList = BeanUtils.getAllProperties(cNode, false, false, true);
         List<String> result = new ArrayList<String>(pList.size());
         for (PropertyNode pNode : pList) {
@@ -457,8 +380,8 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<FieldNode> getInstancePropertyFields(ClassNode cNode) {
-        final List<FieldNode> result = new ArrayList<FieldNode>();
+    public static List<FieldNode> getInstancePropertyFields(final ClassNode cNode) {
+        List<FieldNode> result = new ArrayList<FieldNode>();
         for (PropertyNode pNode : cNode.getProperties()) {
             if (!pNode.isStatic()) {
                 result.add(pNode.getField());
@@ -467,7 +390,7 @@ public class GeneralUtils {
         return result;
     }
 
-    public static Set<ClassNode> getInterfacesAndSuperInterfaces(ClassNode type) {
+    public static Set<ClassNode> getInterfacesAndSuperInterfaces(final ClassNode type) {
         Set<ClassNode> res = new LinkedHashSet<ClassNode>();
         if (type.isInterface()) {
             res.add(type);
@@ -481,8 +404,8 @@ public class GeneralUtils {
         return res;
     }
 
-    public static List<FieldNode> getSuperNonPropertyFields(ClassNode cNode) {
-        final List<FieldNode> result;
+    public static List<FieldNode> getSuperNonPropertyFields(final ClassNode cNode) {
+        List<FieldNode> result;
         if (cNode == ClassHelper.OBJECT_TYPE) {
             result = new ArrayList<FieldNode>();
         } else {
@@ -496,8 +419,8 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<FieldNode> getSuperPropertyFields(ClassNode cNode) {
-        final List<FieldNode> result;
+    public static List<FieldNode> getSuperPropertyFields(final ClassNode cNode) {
+        List<FieldNode> result;
         if (cNode == ClassHelper.OBJECT_TYPE) {
             result = new ArrayList<FieldNode>();
         } else {
@@ -511,18 +434,18 @@ public class GeneralUtils {
         return result;
     }
 
-    public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) {
+    public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode cNode, final boolean includeProperties, final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters, final boolean traverseSuperClasses, final boolean skipReadonly) {
         return getAllProperties(names, cNode, cNode, includeProperties, includeFields, includePseudoGetters, includePseudoSetters, traverseSuperClasses, skipReadonly);
     }
 
-    public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties, boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters, boolean traverseSuperClasses, boolean skipReadonly) {
+    public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties, final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters, final boolean traverseSuperClasses, final boolean skipReadonly) {
         return getAllProperties(names, origType, cNode, includeProperties, includeFields, includePseudoGetters, includePseudoSetters, traverseSuperClasses, skipReadonly, false, false, false);
     }
 
-    public static List<PropertyNode> getAllProperties(Set<String> names, ClassNode origType, ClassNode cNode, boolean includeProperties,
-                                                      boolean includeFields, boolean includePseudoGetters, boolean includePseudoSetters,
-                                                      boolean traverseSuperClasses, boolean skipReadonly, boolean reverse, boolean allNames, boolean includeStatic) {
-        final List<PropertyNode> result = new ArrayList<PropertyNode>();
+    public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties,
+                                                      final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters,
+                                                      final boolean traverseSuperClasses, final boolean skipReadonly, final boolean reverse, final boolean allNames, final boolean includeStatic) {
+        List<PropertyNode> result = new ArrayList<PropertyNode>();
         if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && !reverse) {
             result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
         }
@@ -564,61 +487,67 @@ public class GeneralUtils {
         return result;
     }
 
-    public static BinaryExpression hasClassX(Expression instance, ClassNode cNode) {
-        return eqX(classX(cNode), callX(instance, "getClass"));
+    /**
+     * This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
+     * being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
+     * instead of a field access.
+     * @param annotatedNode the class node where the property node is accessed from
+     * @param pNode the property being accessed
+     * @return a method call expression or a property expression
+     */
+    public static Expression getterThisX(final ClassNode annotatedNode, final PropertyNode pNode) {
+        ClassNode owner = pNode.getDeclaringClass();
+        if (annotatedNode.equals(owner)) {
+            return callThisX(getterName(annotatedNode, pNode));
+        }
+        return propX(new VariableExpression("this"), pNode.getName());
     }
 
-    private static boolean hasClosureMember(AnnotationNode annotation) {
-
-        Map<String, Expression> members = annotation.getMembers();
-        for (Map.Entry<String, Expression> member : members.entrySet())  {
-            if (member.getValue() instanceof ClosureExpression) return true;
-
-            if (member.getValue() instanceof ClassExpression)  {
-                ClassExpression classExpression = (ClassExpression) member.getValue();
-                Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
-                if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
-            }
+    /**
+     * This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
+     * being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
+     * instead of a field access.
+     * @param annotatedNode the class node where the property node is accessed from
+     * @param receiver the object having the property
+     * @param pNode the property being accessed
+     * @return a method call expression or a property expression
+     */
+    public static Expression getterX(final ClassNode annotatedNode, final Expression receiver, final PropertyNode pNode) {
+        ClassNode owner = pNode.getDeclaringClass();
+        if (annotatedNode.equals(owner)) {
+            return callX(receiver, getterName(annotatedNode, pNode));
         }
-
-        return false;
+        return propX(receiver, pNode.getName());
     }
 
-    public static boolean hasDeclaredMethod(ClassNode cNode, String name, int argsCount) {
-        List<MethodNode> ms = cNode.getDeclaredMethods(name);
-        for (MethodNode m : ms) {
-            Parameter[] paras = m.getParameters();
-            if (paras != null && paras.length == argsCount) {
-                return true;
-            }
-        }
-        return false;
+    public static BinaryExpression hasClassX(final Expression instance, final ClassNode cNode) {
+        return eqX(classX(cNode), callX(instance, "getClass"));
     }
 
-    public static BinaryExpression hasEqualFieldX(FieldNode fNode, Expression other) {
+    public static BinaryExpression hasEqualFieldX(final FieldNode fNode, final Expression other) {
         return eqX(varX(fNode), propX(other, fNode.getName()));
     }
 
-    public static BinaryExpression hasEqualPropertyX(ClassNode annotatedNode, PropertyNode pNode, VariableExpression other) {
+    public static BinaryExpression hasEqualPropertyX(final ClassNode annotatedNode, final PropertyNode pNode, final VariableExpression other) {
         return eqX(getterThisX(annotatedNode, pNode), getterX(other.getOriginType(), other, pNode));
     }
 
     @Deprecated
-    public static BinaryExpression hasEqualPropertyX(PropertyNode pNode, Expression other) {
+    public static BinaryExpression hasEqualPropertyX(final PropertyNode pNode, final Expression other) {
         String getterName = getGetterName(pNode);
         return eqX(callThisX(getterName), callX(other, getterName));
     }
 
-    public static BooleanExpression hasSameFieldX(FieldNode fNode, Expression other) {
+    public static BooleanExpression hasSameFieldX(final FieldNode fNode, final Expression other) {
         return sameX(varX(fNode), propX(other, fNode.getName()));
     }
 
-    public static BooleanExpression hasSamePropertyX(PropertyNode pNode, Expression other) {
+    public static BooleanExpression hasSamePropertyX(final PropertyNode pNode, final Expression other) {
         ClassNode cNode = pNode.getDeclaringClass();
         return sameX(getterThisX(cNode, pNode), getterX(cNode, other, pNode));
     }
 
-    public static Statement ifElseS(Expression cond, Statement thenStmt, Statement elseStmt) {
+    public static Statement ifElseS(final Expression cond, final Statement thenStmt, final Statement elseStmt) {
         return new IfStatement(
                 cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
                 thenStmt,
@@ -626,11 +555,11 @@ public class GeneralUtils {
         );
     }
 
-    public static Statement ifS(Expression cond, Expression trueExpr) {
+    public static Statement ifS(final Expression cond, final Expression trueExpr) {
         return ifS(cond, new ExpressionStatement(trueExpr));
     }
 
-    public static Statement ifS(Expression cond, Statement trueStmt) {
+    public static Statement ifS(final Expression cond, final Statement trueStmt) {
         return new IfStatement(
                 cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
                 trueStmt,
@@ -638,39 +567,35 @@ public class GeneralUtils {
         );
     }
 
-    public static Expression indexX(Expression target, Expression value) {
+    public static Expression indexX(final Expression target, final Expression value) {
         return new BinaryExpression(target, INDEX, value);
     }
 
-    public static BooleanExpression isInstanceOfX(Expression objectExpression, ClassNode cNode) {
+    public static BooleanExpression isInstanceOfX(final Expression objectExpression, final ClassNode cNode) {
         return new BooleanExpression(new BinaryExpression(objectExpression, INSTANCEOF, classX(cNode)));
     }
 
-    public static BooleanExpression isNullX(Expression expr) {
+    public static BooleanExpression isNullX(final Expression expr) {
         return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(null)));
     }
 
-    public static BooleanExpression isOneX(Expression expr) {
+    public static BooleanExpression isOneX(final Expression expr) {
         return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(1)));
     }
 
-    public static boolean isOrImplements(ClassNode type, ClassNode interfaceType) {
-        return type.equals(interfaceType) || type.implementsInterface(interfaceType);
-    }
-
-    public static BooleanExpression isTrueX(Expression argExpr) {
+    public static BooleanExpression isTrueX(final Expression argExpr) {
         return new BooleanExpression(new BinaryExpression(argExpr, EQ, new ConstantExpression(Boolean.TRUE)));
     }
 
-    public static BooleanExpression isZeroX(Expression expr) {
+    public static BooleanExpression isZeroX(final Expression expr) {
         return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(0)));
     }
 
-    public static ListExpression listX(List<Expression> args) {
+    public static ListExpression listX(final List<Expression> args) {
         return new ListExpression(args);
     }
 
-    public static ListExpression list2args(List args) {
+    public static ListExpression list2args(final List<? extends Object> args) {
         ListExpression result = new ListExpression();
         for (Object o : args) {
             result.addExpression(new ConstantExpression(o));
@@ -678,7 +603,7 @@ public class GeneralUtils {
         return result;
     }
 
-    public static ListExpression classList2args(List<String> args) {
+    public static ListExpression classList2args(final List<String> args) {
         ListExpression result = new ListExpression();
         for (Object o : args) {
             result.addExpression(new ClassExpression(ClassHelper.make(o.toString())));
@@ -686,72 +611,55 @@ public class GeneralUtils {
         return result;
     }
 
-    public static VariableExpression localVarX(String name) {
+    public static VariableExpression localVarX(final String name) {
         VariableExpression result = new VariableExpression(name);
         result.setAccessedVariable(result);
         return result;
     }
 
-    public static VariableExpression localVarX(String name, ClassNode type) {
+    public static VariableExpression localVarX(final String name, final ClassNode type) {
         VariableExpression result = new VariableExpression(name, type);
         result.setAccessedVariable(result);
         return result;
     }
 
-    public static BinaryExpression ltX(Expression lhv, Expression rhv) {
+    public static BinaryExpression ltX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, LT, rhv);
     }
 
-    public static MapExpression mapX(List<MapEntryExpression> expressions) {
+    public static MapExpression mapX(final List<MapEntryExpression> expressions) {
         return new MapExpression(expressions);
     }
 
-    public static MapEntryExpression entryX(Expression key, Expression value) {
-        return new MapEntryExpression(key, value);
+    public static BinaryExpression neX(final Expression lhv, final Expression rhv) {
+        return new BinaryExpression(lhv, NE, rhv);
     }
 
-    public static BinaryExpression notIdenticalX(Expression lhv, Expression rhv) {
+    public static BinaryExpression notIdenticalX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, NOT_IDENTICAL, rhv);
     }
 
-    /**
-     * @deprecated use MethodNodeUtils#methodDescriptorWithoutReturnType(MethodNode) instead
-     */
-    @Deprecated
-    public static String makeDescriptorWithoutReturnType(MethodNode mn) {
-        StringBuilder sb = new StringBuilder();
-        sb.append(mn.getName()).append(':');
-        for (Parameter p : mn.getParameters()) {
-            sb.append(p.getType()).append(',');
-        }
-        return sb.toString();
+    public static BooleanExpression notNullX(final Expression argExpr) {
+        return new BooleanExpression(new BinaryExpression(argExpr, NE, new ConstantExpression(null)));
     }
 
-    public static BinaryExpression neX(Expression lhv, Expression rhv) {
-        return new BinaryExpression(lhv, NE, rhv);
+    public static NotExpression notX(final Expression expr) {
+        return new NotExpression(expr instanceof BooleanExpression ? expr : new BooleanExpression(expr));
     }
 
     public static ConstantExpression nullX() {
         return new ConstantExpression(null);
     }
 
-    public static BooleanExpression notNullX(Expression argExpr) {
-        return new BooleanExpression(new BinaryExpression(argExpr, NE, new ConstantExpression(null)));
-    }
-
-    public static NotExpression notX(Expression expr) {
-        return new NotExpression(expr instanceof BooleanExpression ? expr : new BooleanExpression(expr));
-    }
-
-    public static BinaryExpression orX(Expression lhv, Expression rhv) {
+    public static BinaryExpression orX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, OR, rhv);
     }
 
-    public static Parameter param(ClassNode type, String name) {
+    public static Parameter param(final ClassNode type, final String name) {
         return param(type, name, null);
     }
 
-    public static Parameter param(ClassNode type, String name, Expression initialExpression) {
+    public static Parameter param(final ClassNode type, final String name, final Expression initialExpression) {
         Parameter param = new Parameter(type, name);
         if (initialExpression != null) {
             param.setInitialExpression(initialExpression);
@@ -759,103 +667,172 @@ public class GeneralUtils {
         return param;
     }
 
-    public static Parameter[] params(Parameter... params) {
+    public static Parameter[] params(final Parameter... params) {
         return params != null ? params : Parameter.EMPTY_ARRAY;
     }
 
-    public static BinaryExpression plusX(Expression lhv, Expression rhv) {
+    public static BinaryExpression plusX(final Expression lhv, final Expression rhv) {
         return new BinaryExpression(lhv, PLUS, rhv);
     }
 
-    public static PropertyExpression propX(Expression owner, String property) {
+    public static PropertyExpression propX(final Expression owner, final String property) {
         return new PropertyExpression(owner, property);
     }
 
-    public static PropertyExpression propX(Expression owner, Expression property) {
+    public static PropertyExpression propX(final Expression owner, final Expression property) {
         return new PropertyExpression(owner, property);
     }
 
-    public static PropertyExpression propX(Expression owner, Expression property, boolean safe) {
+    public static PropertyExpression propX(final Expression owner, final Expression property, final boolean safe) {
         return new PropertyExpression(owner, property, safe);
     }
 
-    public static PropertyExpression thisPropX(boolean implicit, String property) {
-        PropertyExpression pexp = propX(varX("this"), property);
-        pexp.setImplicitThis(implicit);
-        return pexp;
-    }
-
-    public static Statement returnS(Expression expr) {
+    public static Statement returnS(final Expression expr) {
         return new ReturnStatement(new ExpressionStatement(expr));
     }
 
-    public static Statement safeExpression(Expression fieldExpr, Expression expression) {
+    public static Statement safeExpression(final Expression fieldExpr, final Expression expression) {
         return new IfStatement(
                 equalsNullX(fieldExpr),
                 new ExpressionStatement(fieldExpr),
                 new ExpressionStatement(expression));
     }
 
-    public static BooleanExpression sameX(Expression self, Expression other) {
+    public static BooleanExpression sameX(final Expression self, final Expression other) {
         return new BooleanExpression(callX(self, "is", args(other)));
     }
 
-    public static Statement stmt(Expression expr) {
+    public static Statement stmt(final Expression expr) {
         return new ExpressionStatement(expr);
     }
 
-    public static TernaryExpression ternaryX(Expression cond, Expression trueExpr, Expression elseExpr) {
+    public static TernaryExpression ternaryX(final Expression cond, final Expression trueExpr, final Expression elseExpr) {
         return new TernaryExpression(
                 cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
                 trueExpr,
                 elseExpr);
     }
 
-    public static VariableExpression varX(String name) {
-        return new VariableExpression(name);
+    public static PropertyExpression thisPropX(final boolean implicit, final String property) {
+        PropertyExpression pexp = propX(varX("this"), property);
+        pexp.setImplicitThis(implicit);
+        return pexp;
     }
 
-    public static VariableExpression varX(Variable variable) {
-        return new VariableExpression(variable);
+    public static ThrowStatement throwS(final Expression expr) {
+        return new ThrowStatement(expr);
     }
 
-    public static VariableExpression varX(String name, ClassNode type) {
-        return new VariableExpression(name, type);
+    public static TryCatchStatement tryCatchS(final Statement tryStatement) {
+        return tryCatchS(tryStatement, EmptyStatement.INSTANCE);
     }
 
-    public static ThrowStatement throwS(Expression expr) {
-        return new ThrowStatement(expr);
+    public static TryCatchStatement tryCatchS(final Statement tryStatement, final Statement finallyStatement) {
+        return new TryCatchStatement(tryStatement, finallyStatement);
     }
 
-    public static CatchStatement catchS(Parameter variable, Statement code) {
-        return new CatchStatement(variable, code);
+    public static VariableExpression varX(final String name) {
+        return new VariableExpression(name);
     }
 
-    public static TryCatchStatement tryCatchS(Statement tryStatement) {
-        return tryCatchS(tryStatement, EmptyStatement.INSTANCE);
+    public static VariableExpression varX(final Variable variable) {
+        return new VariableExpression(variable);
     }
 
-    public static TryCatchStatement tryCatchS(Statement tryStatement, Statement finallyStatement) {
-        return new TryCatchStatement(tryStatement, finallyStatement);
+    public static VariableExpression varX(final String name, final ClassNode type) {
+        return new VariableExpression(name, type);
+    }
+
+    //--------------------------------------------------------------------------
+
+    public static Parameter[] cloneParams(final Parameter[] source) {
+        Parameter[] result = new Parameter[source.length];
+        for (int i = 0; i < source.length; i++) {
+            Parameter srcParam = source[i];
+            Parameter dstParam = new Parameter(srcParam.getOriginType(), srcParam.getName());
+            result[i] = dstParam;
+        }
+        return result;
     }
 
     /**
-     * This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
-     * being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
-     * instead of a field access.
-     * @param annotatedNode the class node where the property node is accessed from
-     * @param pNode the property being accessed
-     * @return a method call expression or a property expression
+     * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
+     * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
+     * <p>
+     * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
      */
-    public static Expression getterThisX(ClassNode annotatedNode, PropertyNode pNode) {
-        ClassNode owner = pNode.getDeclaringClass();
-        if (annotatedNode.equals(owner)) {
-            return callThisX(getterName(annotatedNode, pNode));
+    public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, final List<AnnotationNode> notCopied) {
+        copyAnnotatedNodeAnnotations(annotatedNode, copied, notCopied, true);
+    }
+
+    /**
+     * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
+     * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
+     * {@link groovy.transform.Generated} annotations will be copied if {@code includeGenerated} is true.
+     * <p>
+     * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
+     */
+    public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, final List<AnnotationNode> notCopied, final boolean includeGenerated) {
+        List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
+        for (AnnotationNode annotation : annotationList)  {
+
+            List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
+            if (annotations.isEmpty()) continue;
+
+            if (hasClosureMember(annotation)) {
+                notCopied.add(annotation);
+                continue;
+            }
+
+            if (!includeGenerated && annotation.getClassNode().getName().equals("groovy.transform.Generated")) {
+                continue;
+            }
+
+            AnnotationNode retentionPolicyAnnotation = annotations.get(0);
+            Expression valueExpression = retentionPolicyAnnotation.getMember("value");
+            if (!(valueExpression instanceof PropertyExpression)) continue;
+
+            PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
+            boolean processAnnotation =
+                    propertyExpression.getProperty() instanceof ConstantExpression &&
+                            (
+                                    "RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
+                                            "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
+                            );
+
+            if (processAnnotation)  {
+                AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
+                for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet())  {
+                    newAnnotation.addMember(member.getKey(), member.getValue());
+                }
+                newAnnotation.setSourcePosition(annotatedNode);
+
+                copied.add(newAnnotation);
+            }
         }
-        return propX(new VariableExpression("this"), pNode.getName());
     }
 
-    private static String getterName(ClassNode annotatedNode, PropertyNode pNode) {
+    public static Statement createConstructorStatementDefault(final FieldNode fNode) {
+        final String name = fNode.getName();
+        final ClassNode fType = fNode.getType();
+        final Expression fieldExpr = propX(varX("this"), name);
+        Expression initExpr = fNode.getInitialValueExpression();
+        Statement assignInit;
+        if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression)initExpr).isNullExpression())) {
+            if (ClassHelper.isPrimitiveType(fType)) {
+                assignInit = EmptyStatement.INSTANCE;
+            } else {
+                assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
+            }
+        } else {
+            assignInit = assignS(fieldExpr, initExpr);
+        }
+        fNode.setInitialValueExpression(null);
+        Expression value = findArg(name);
+        return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
+    }
+
+    private static String getterName(final ClassNode annotatedNode, final PropertyNode pNode) {
         String getterName = "get" + capitalize(pNode.getName());
         boolean existingExplicitGetter = annotatedNode.getMethod(getterName, Parameter.EMPTY_ARRAY) != null;
         if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType()) && !existingExplicitGetter) {
@@ -864,21 +841,12 @@ public class GeneralUtils {
         return getterName;
     }
 
-    /**
-     * This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
-     * being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
-     * instead of a field access.
-     * @param annotatedNode the class node where the property node is accessed from
-     * @param receiver the object having the property
-     * @param pNode the property being accessed
-     * @return a method call expression or a property expression
-     */
-    public static Expression getterX(ClassNode annotatedNode, Expression receiver, PropertyNode pNode) {
-        ClassNode owner = pNode.getDeclaringClass();
-        if (annotatedNode.equals(owner)) {
-            return callX(receiver, getterName(annotatedNode, pNode));
-        }
-        return propX(receiver, pNode.getName());
+    public static String getGetterName(final PropertyNode pNode) {
+        return "get" + capitalize(pNode.getName());
+    }
+
+    public static String getSetterName(final String name) {
+        return "set" + capitalize(name);
     }
 
     /**
@@ -891,7 +859,7 @@ public class GeneralUtils {
      * @throws java.lang.IllegalArgumentException when expression is null
      * @throws java.lang.Exception when closure can't be read from source
      */
-    public static String convertASTToSource(ReaderSource readerSource, ASTNode expression) throws Exception {
+    public static String convertASTToSource(final ReaderSource readerSource, final ASTNode expression) throws Exception {
         if (expression == null) throw new IllegalArgumentException("Null: expression");
 
         StringBuilder result = new StringBuilder();
@@ -918,7 +886,7 @@ public class GeneralUtils {
         return source;
     }
 
-    public static boolean copyStatementsWithSuperAdjustment(ClosureExpression pre, BlockStatement body) {
+    public static boolean copyStatementsWithSuperAdjustment(final ClosureExpression pre, final BlockStatement body) {
         Statement preCode = pre.getCode();
         boolean changed = false;
         if (preCode instanceof BlockStatement) {
@@ -945,25 +913,64 @@ public class GeneralUtils {
         return changed;
     }
 
-    public static String getSetterName(String name) {
-        return "set" + Verifier.capitalize(name);
+    private static boolean hasClosureMember(final AnnotationNode annotation) {
+        Map<String, Expression> members = annotation.getMembers();
+        for (Map.Entry<String, Expression> member : members.entrySet())  {
+            if (member.getValue() instanceof ClosureExpression) return true;
+
+            if (member.getValue() instanceof ClassExpression)  {
+                ClassExpression classExpression = (ClassExpression) member.getValue();
+                Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
+                if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
+            }
+        }
+
+        return false;
     }
 
-    public static boolean isDefaultVisibility(int modifiers) {
-        return (modifiers & (Modifier.PRIVATE | Modifier.PUBLIC | Modifier.PROTECTED)) == 0;
+    public static boolean hasDeclaredMethod(final ClassNode cNode, final String name, final int argsCount) {
+        List<MethodNode> ms = cNode.getDeclaredMethods(name);
+        for (MethodNode m : ms) {
+            Parameter[] paras = m.getParameters();
+            if (paras != null && paras.length == argsCount) {
+                return true;
+            }
+        }
+        return false;
     }
 
-    public static boolean inSamePackage(ClassNode first, ClassNode second) {
+    public static boolean inSamePackage(final ClassNode first, final ClassNode second) {
         PackageNode firstPackage = first.getPackage();
         PackageNode secondPackage = second.getPackage();
         return ((firstPackage == null && secondPackage == null) ||
                         firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
     }
 
-    public static boolean inSamePackage(Class first, Class second) {
+    public static boolean inSamePackage(final Class<?> first, final Class<?> second) {
         Package firstPackage = first.getPackage();
         Package secondPackage = second.getPackage();
         return ((firstPackage == null && secondPackage == null) ||
                         firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
     }
+
+    public static boolean isDefaultVisibility(final int modifiers) {
+        return (modifiers & (Modifier.PRIVATE | Modifier.PUBLIC | Modifier.PROTECTED)) == 0;
+    }
+
+    public static boolean isOrImplements(final ClassNode type, final ClassNode interfaceType) {
+        return type.equals(interfaceType) || type.implementsInterface(interfaceType);
+    }
+
+    /**
+     * @deprecated use MethodNodeUtils#methodDescriptorWithoutReturnType(MethodNode) instead
+     */
+    @Deprecated
+    public static String makeDescriptorWithoutReturnType(final MethodNode mn) {
+        StringBuilder sb = new StringBuilder();
+        sb.append(mn.getName()).append(':');
+        for (Parameter p : mn.getParameters()) {
+            sb.append(p.getType()).append(',');
+        }
+        return sb.toString();
+    }
 }


[groovy] 03/06: add builder for DeclarationExpression

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

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

commit f149acdf8d387262e13e27e3bf21156e65b68a0f
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Feb 14 12:08:39 2020 -0600

    add builder for DeclarationExpression
    
    (cherry picked from commit 3c054084545ec4fcde79dfb538e6cc7977c26d4c)
---
 src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java      | 6 +++++-
 .../org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java   | 7 ++++---
 .../asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java     | 5 ++---
 3 files changed, 11 insertions(+), 7 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
index 1685b1b..49b7163 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -350,7 +350,11 @@ public class GeneralUtils {
     }
 
     public static Statement declS(Expression target, Expression init) {
-        return new ExpressionStatement(new DeclarationExpression(target, ASSIGN, init));
+        return stmt(declX(target, init));
+    }
+
+    public static DeclarationExpression declX(Expression target, Expression init) {
+        return new DeclarationExpression(target, ASSIGN, init);
     }
 
     public static BinaryExpression eqX(Expression lhv, Expression rhv) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
index 22d6583..1f7f256 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
@@ -143,7 +143,7 @@ public class BinaryExpressionHelper {
 
     public void eval(final BinaryExpression expression) {
         switch (expression.getOperation().getType()) {
-        case EQUAL: // = assignment
+        case EQUAL: // = (aka assignment)
             evaluateEqual(expression, false);
             break;
 
@@ -720,7 +720,7 @@ public class BinaryExpressionHelper {
         VariableSlotLoader usesSubscript = loadWithSubscript(expression);
 
         // execute method
-        execMethodAndStoreForSubscriptOperator(op,method,expression,usesSubscript,orig);
+        execMethodAndStoreForSubscriptOperator(op, method, expression, usesSubscript, orig);
 
         // new value is already on stack, so nothing to do here
         if (usesSubscript != null) controller.getCompileStack().removeVar(usesSubscript.getIndex());
@@ -771,7 +771,7 @@ public class BinaryExpressionHelper {
             compileStack.removeVar(resultIdx);
 
         } else if (expression instanceof VariableExpression || expression instanceof PropertyExpression || expression instanceof FieldExpression) {
-            // here we handle a.b++ and a++
+            // here we handle a++ and a.b++
             controller.getOperandStack().dup();
             controller.getCompileStack().pushLHS(true);
             expression.visit(controller.getAcg());
@@ -794,6 +794,7 @@ public class BinaryExpressionHelper {
                 operandStack.push(ClassHelper.OBJECT_TYPE);
                 // change (receiver,callsite) to (callsite,receiver)
                 operandStack.swap();
+
                 setType(operandStack.getTopOperand());
 
                 // no need to keep any of those on the operand stack
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
index 3d1661a..e7961a7 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
@@ -34,7 +34,6 @@ import org.codehaus.groovy.ast.expr.MethodReferenceExpression;
 import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.expr.VariableExpression;
 import org.codehaus.groovy.ast.stmt.EmptyStatement;
-import org.codehaus.groovy.ast.stmt.ExpressionStatement;
 import org.codehaus.groovy.ast.stmt.ForStatement;
 import org.codehaus.groovy.ast.tools.WideningCategories;
 import org.codehaus.groovy.classgen.AsmClassGenerator;
@@ -73,7 +72,7 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.classX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX;
-import static org.codehaus.groovy.ast.tools.GeneralUtils.declS;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.declX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.nullX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.propX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
@@ -216,7 +215,7 @@ public class StaticTypesBinaryExpressionMultiTypeDispatcher extends BinaryExpres
         VariableExpression result = varX(this.getClass().getSimpleName() + "$spreadresult" + counter, ARRAYLIST_CLASSNODE);
         ConstructorCallExpression newArrayList = ctorX(ARRAYLIST_CLASSNODE);
         newArrayList.setNodeMetaData(DIRECT_METHOD_CALL_TARGET, ARRAYLIST_CONSTRUCTOR);
-        Expression decl = ((ExpressionStatement) declS(result, newArrayList)).getExpression();
+        Expression decl = declX(result, newArrayList);
         decl.visit(controller.getAcg());
         // if (receiver != null)
         receiver.visit(controller.getAcg());


[groovy] 02/06: minor edits

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

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

commit 272eb893d2149c5045349b080cbe7f6d76c9004f
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Feb 13 16:40:27 2020 -0600

    minor edits
    
    (cherry picked from commit 345e47fd6f9d3adb84db3385657c8758a423512d)
---
 .../codehaus/groovy/ast/tools/GeneralUtils.java    |   2 +-
 .../classgen/asm/BinaryExpressionHelper.java       | 254 +++++++++------------
 2 files changed, 113 insertions(+), 143 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
index 793769d..1685b1b 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -90,7 +90,7 @@ public class GeneralUtils {
     public static final Token AND = Token.newSymbol(Types.LOGICAL_AND, -1, -1);
     public static final Token OR = Token.newSymbol(Types.LOGICAL_OR, -1, -1);
     public static final Token CMP = Token.newSymbol(Types.COMPARE_TO, -1, -1);
-    private static final Token INSTANCEOF = Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1);
+    public static final Token INSTANCEOF = Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1);
     private static final Token PLUS = Token.newSymbol(Types.PLUS, -1, -1);
     private static final Token INDEX = Token.newSymbol("[", -1, -1);
 
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
index 78944d4..22d6583 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
@@ -39,15 +39,20 @@ import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.expr.TernaryExpression;
 import org.codehaus.groovy.ast.expr.TupleExpression;
 import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.tools.GeneralUtils;
 import org.codehaus.groovy.ast.tools.WideningCategories;
 import org.codehaus.groovy.classgen.AsmClassGenerator;
 import org.codehaus.groovy.classgen.BytecodeExpression;
 import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
 import org.codehaus.groovy.syntax.Token;
-import org.codehaus.groovy.syntax.Types;
 import org.objectweb.asm.Label;
 import org.objectweb.asm.MethodVisitor;
 
+import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.binX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;
+import static org.codehaus.groovy.syntax.Types.ASSIGN;
 import static org.codehaus.groovy.syntax.Types.BITWISE_AND;
 import static org.codehaus.groovy.syntax.Types.BITWISE_AND_EQUAL;
 import static org.codehaus.groovy.syntax.Types.BITWISE_OR;
@@ -82,12 +87,14 @@ import static org.codehaus.groovy.syntax.Types.LOGICAL_OR;
 import static org.codehaus.groovy.syntax.Types.MATCH_REGEX;
 import static org.codehaus.groovy.syntax.Types.MINUS;
 import static org.codehaus.groovy.syntax.Types.MINUS_EQUAL;
+import static org.codehaus.groovy.syntax.Types.MINUS_MINUS;
 import static org.codehaus.groovy.syntax.Types.MOD;
 import static org.codehaus.groovy.syntax.Types.MOD_EQUAL;
 import static org.codehaus.groovy.syntax.Types.MULTIPLY;
 import static org.codehaus.groovy.syntax.Types.MULTIPLY_EQUAL;
 import static org.codehaus.groovy.syntax.Types.PLUS;
 import static org.codehaus.groovy.syntax.Types.PLUS_EQUAL;
+import static org.codehaus.groovy.syntax.Types.PLUS_PLUS;
 import static org.codehaus.groovy.syntax.Types.POWER;
 import static org.codehaus.groovy.syntax.Types.POWER_EQUAL;
 import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT;
@@ -338,9 +345,7 @@ public class BinaryExpressionHelper {
         // -> (x, [], 5), =, 10
         // -> methodCall(x, "putAt", [5, 10])
         ArgumentListExpression ae = new ArgumentListExpression(index,rhsValueLoader);
-        controller.getInvocationWriter().makeCall(
-                parent, receiver, new ConstantExpression("putAt"),
-                ae, InvocationWriter.invokeMethod, safe, false, false);
+        controller.getInvocationWriter().makeCall(parent, receiver, constX("putAt"), ae, InvocationWriter.invokeMethod, safe, false, false);
         controller.getOperandStack().pop();
         // return value of assignment
         rhsValueLoader.visit(controller.getAcg());
@@ -348,13 +353,11 @@ public class BinaryExpressionHelper {
 
     public void evaluateElvisEqual(final BinaryExpression expression) {
         Token operation = expression.getOperation();
-        BinaryExpression elvisAssignmentExpression =
-                new BinaryExpression(
-                        expression.getLeftExpression(),
-                        Token.newSymbol(Types.EQUAL, operation.getStartLine(), operation.getStartColumn()),
-                        new ElvisOperatorExpression(expression.getLeftExpression(), expression.getRightExpression())
-                );
-
+        BinaryExpression elvisAssignmentExpression = binX(
+                expression.getLeftExpression(),
+                Token.newSymbol(ASSIGN, operation.getStartLine(), operation.getStartColumn()),
+                new ElvisOperatorExpression(expression.getLeftExpression(), expression.getRightExpression())
+        );
         this.evaluateEqual(elvisAssignmentExpression, false);
     }
 
@@ -362,14 +365,11 @@ public class BinaryExpressionHelper {
         AsmClassGenerator acg = controller.getAcg();
         CompileStack compileStack = controller.getCompileStack();
         OperandStack operandStack = controller.getOperandStack();
-        Expression rightExpression = expression.getRightExpression();
         Expression leftExpression = expression.getLeftExpression();
-        ClassNode lhsType = controller.getTypeChooser().resolveType(leftExpression, controller.getClassNode());
+        Expression rightExpression = expression.getRightExpression();
+        boolean directAssignment = defineVariable && !(leftExpression instanceof TupleExpression);
 
-        if (    defineVariable &&
-                rightExpression instanceof EmptyExpression &&
-                !(leftExpression instanceof TupleExpression) )
-        {
+        if (directAssignment && rightExpression instanceof EmptyExpression) {
             VariableExpression ve = (VariableExpression) leftExpression;
             BytecodeVariable var = compileStack.defineVariable(ve, controller.getTypeChooser().resolveType(ve, controller.getClassNode()), false);
             operandStack.loadOrStoreVariable(var, false);
@@ -377,22 +377,21 @@ public class BinaryExpressionHelper {
         }
 
         // let's evaluate the RHS and store the result
-        ClassNode rhsType;
+        ClassNode lhsType = controller.getTypeChooser().resolveType(leftExpression, controller.getClassNode());
         if (rightExpression instanceof ListExpression && lhsType.isArray()) {
             ListExpression list = (ListExpression) rightExpression;
             ArrayExpression array = new ArrayExpression(lhsType.getComponentType(), list.getExpressions());
             array.setSourcePosition(list);
             array.visit(acg);
         } else if (rightExpression instanceof EmptyExpression) {
-            rhsType = leftExpression.getType();
-            loadInitValue(rhsType);
+            loadInitValue(leftExpression.getType()); // TODO: lhsType?
         } else {
             rightExpression.visit(acg);
         }
-        rhsType = operandStack.getTopOperand();
 
-        boolean directAssignment = defineVariable && !(leftExpression instanceof TupleExpression);
+        ClassNode rhsType = operandStack.getTopOperand();
         int rhsValueId;
+
         if (directAssignment) {
             VariableExpression var = (VariableExpression) leftExpression;
             if (var.isClosureSharedVariable() && ClassHelper.isPrimitiveType(rhsType)) {
@@ -422,13 +421,13 @@ public class BinaryExpressionHelper {
         } else {
             rhsValueId = compileStack.defineTemporaryVariable("$rhs", rhsType, true);
         }
-        //TODO: if rhs is VariableSlotLoader already, then skip crating a new one
+        // TODO: if rhs is VariableSlotLoader already, then skip crating a new one
         BytecodeExpression rhsValueLoader = new VariableSlotLoader(rhsType,rhsValueId,operandStack);
 
         // assignment for subscript
         if (leftExpression instanceof BinaryExpression) {
             BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
-            if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
+            if (leftBinExpr.getOperation().getType() == LEFT_SQUARE_BRACKET) {
                 assignToArray(expression, leftBinExpr.getLeftExpression(), leftBinExpr.getRightExpression(), rhsValueLoader, leftBinExpr.isSafe());
             }
             compileStack.removeVar(rhsValueId);
@@ -437,8 +436,8 @@ public class BinaryExpressionHelper {
 
         compileStack.pushLHS(true);
 
-        // multiple declaration
         if (leftExpression instanceof TupleExpression) {
+            // multiple declaration
             TupleExpression tuple = (TupleExpression) leftExpression;
             int i = 0;
             for (Expression e : tuple.getExpressions()) {
@@ -447,7 +446,7 @@ public class BinaryExpressionHelper {
                         rhsValueLoader, "getAt",
                         new ArgumentListExpression(new ConstantExpression(i)));
                 call.visit(acg);
-                i++;
+                i += 1;
                 if (defineVariable) {
                     operandStack.doGroovyCast(var);
                     compileStack.defineVariable(var, true);
@@ -456,16 +455,14 @@ public class BinaryExpressionHelper {
                     acg.visitVariableExpression(var);
                 }
             }
-        }
-        // single declaration
-        else if (defineVariable) {
+        } else if (defineVariable) {
+            // single declaration
             rhsValueLoader.visit(acg);
             operandStack.remove(1);
             compileStack.popLHS();
             return;
-        }
-        // normal assignment
-        else {
+        } else {
+            // normal assignment
             int mark = operandStack.getStackLength();
             // to leave a copy of the rightExpression value on the stack after the assignment.
             rhsValueLoader.visit(acg);
@@ -473,7 +470,7 @@ public class BinaryExpressionHelper {
             ClassNode targetType = typeChooser.resolveType(leftExpression, controller.getClassNode());
             operandStack.doGroovyCast(targetType);
             leftExpression.visit(acg);
-            operandStack.remove(operandStack.getStackLength()-mark);
+            operandStack.remove(operandStack.getStackLength() - mark);
         }
         compileStack.popLHS();
 
@@ -493,21 +490,17 @@ public class BinaryExpressionHelper {
     }
 
     protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression expression) {
+        ClassNode classNode = controller.getClassNode();
         Expression leftExp = expression.getLeftExpression();
-        TypeChooser typeChooser = controller.getTypeChooser();
-        ClassNode cn = controller.getClassNode();
-        ClassNode leftType = typeChooser.resolveType(leftExp,cn);
         Expression rightExp = expression.getRightExpression();
-        ClassNode rightType = typeChooser.resolveType(rightExp,cn);
+        ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, classNode);
+        ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, classNode);
 
         boolean done = false;
-        if (    ClassHelper.isPrimitiveType(leftType) &&
-                ClassHelper.isPrimitiveType(rightType))
-        {
-            BinaryExpressionMultiTypeDispatcher helper = new BinaryExpressionMultiTypeDispatcher(getController());
+        if (ClassHelper.isPrimitiveType(leftType) && ClassHelper.isPrimitiveType(rightType)) {
+            BinaryExpressionMultiTypeDispatcher helper = new BinaryExpressionMultiTypeDispatcher(controller);
             done = helper.doPrimitiveCompare(leftType, rightType, expression);
         }
-
         if (!done) {
             AsmClassGenerator acg = controller.getAcg();
             OperandStack operandStack = controller.getOperandStack();
@@ -519,33 +512,32 @@ public class BinaryExpressionHelper {
 
             compareMethod.call(controller.getMethodVisitor());
             ClassNode resType = ClassHelper.boolean_TYPE;
-            if (compareMethod==findRegexMethod) {
+            if (compareMethod == findRegexMethod) {
                 resType = ClassHelper.OBJECT_TYPE;
             }
-            operandStack.replace(resType,2);
+            operandStack.replace(resType, 2);
         }
     }
 
     private void evaluateCompareTo(final BinaryExpression expression) {
-        Expression leftExpression = expression.getLeftExpression();
         AsmClassGenerator acg = controller.getAcg();
+        MethodVisitor mv = controller.getMethodVisitor();
         OperandStack operandStack = controller.getOperandStack();
 
-        leftExpression.visit(acg);
+        expression.getLeftExpression().visit(acg);
         operandStack.box();
 
         // if the right hand side is a boolean expression, we need to autobox
-        Expression rightExpression = expression.getRightExpression();
-        rightExpression.visit(acg);
+        expression.getRightExpression().visit(acg);
         operandStack.box();
 
-        compareToMethod.call(controller.getMethodVisitor());
-        operandStack.replace(ClassHelper.Integer_TYPE,2);
+        compareToMethod.call(mv);
+        operandStack.replace(ClassHelper.Integer_TYPE, 2);
     }
 
     private void evaluateLogicalAndExpression(final BinaryExpression expression) {
-        MethodVisitor mv = controller.getMethodVisitor();
         AsmClassGenerator acg = controller.getAcg();
+        MethodVisitor mv = controller.getMethodVisitor();
         OperandStack operandStack = controller.getOperandStack();
 
         expression.getLeftExpression().visit(acg);
@@ -554,7 +546,7 @@ public class BinaryExpressionHelper {
 
         expression.getRightExpression().visit(acg);
         operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
-        operandStack.jump(IFEQ,falseCase);
+        operandStack.jump(IFEQ, falseCase);
 
         ConstantExpression.PRIM_TRUE.visit(acg);
         Label trueCase = new Label();
@@ -568,12 +560,10 @@ public class BinaryExpressionHelper {
     }
 
     private void evaluateLogicalOrExpression(final BinaryExpression expression) {
-        MethodVisitor mv = controller.getMethodVisitor();
         AsmClassGenerator acg = controller.getAcg();
+        MethodVisitor mv = controller.getMethodVisitor();
         OperandStack operandStack = controller.getOperandStack();
 
-        Label end = new Label();
-
         expression.getLeftExpression().visit(acg);
         operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
         Label trueCase = operandStack.jump(IFNE);
@@ -584,6 +574,7 @@ public class BinaryExpressionHelper {
 
         mv.visitLabel(trueCase);
         ConstantExpression.PRIM_TRUE.visit(acg);
+        Label end = new Label();
         operandStack.jump(GOTO, end);
 
         mv.visitLabel(falseCase);
@@ -592,23 +583,20 @@ public class BinaryExpressionHelper {
         mv.visitLabel(end);
     }
 
-    protected void evaluateBinaryExpression(final String message, final BinaryExpression binExp) {
+    protected void evaluateBinaryExpression(final String message, final BinaryExpression expression) {
         CompileStack compileStack = controller.getCompileStack();
-
-        Expression receiver = binExp.getLeftExpression();
-        Expression arguments = binExp.getRightExpression();
-
         // ensure VariableArguments are read, not stored
         compileStack.pushLHS(false);
-        controller.getInvocationWriter().makeSingleArgumentCall(receiver, message, arguments, binExp.isSafe());
+        controller.getInvocationWriter().makeSingleArgumentCall(
+                expression.getLeftExpression(),
+                message,
+                expression.getRightExpression(),
+                expression.isSafe()
+        );
         compileStack.popLHS();
     }
 
     protected void evaluateArrayAssignmentWithOperator(final String method, final BinaryExpression expression, final BinaryExpression leftBinExpr) {
-        CompileStack compileStack    = getController().getCompileStack();
-        AsmClassGenerator acg             = getController().getAcg();
-        OperandStack os              = getController().getOperandStack();
-
         // e.g. x[a] += b
         // to avoid loading x and a twice we transform the expression to use
         // ExpressionAsVariableSlot
@@ -619,15 +607,18 @@ public class BinaryExpressionHelper {
         // -> subscript=a, receiver=x, receiver#putAt(subscript, ret=receiver#getAt(subscript)#plus(b)), ret
         ExpressionAsVariableSlot subscript = new ExpressionAsVariableSlot(controller, leftBinExpr.getRightExpression(), "subscript");
         ExpressionAsVariableSlot receiver  = new ExpressionAsVariableSlot(controller, leftBinExpr.getLeftExpression(), "receiver");
-        MethodCallExpression getAt = new MethodCallExpression(receiver, "getAt", new ArgumentListExpression(subscript));
-        MethodCallExpression operation = new MethodCallExpression(getAt, method, expression.getRightExpression());
+        MethodCallExpression getAt = callX(receiver, "getAt", args(subscript));
+        MethodCallExpression operation = callX(getAt, method, expression.getRightExpression());
         ExpressionAsVariableSlot ret = new ExpressionAsVariableSlot(controller, operation, "ret");
-        MethodCallExpression putAt = new MethodCallExpression(receiver, "putAt", new ArgumentListExpression(subscript, ret));
+        MethodCallExpression putAt = callX(receiver, "putAt", args(subscript, ret));
 
+        AsmClassGenerator acg = controller.getAcg();
         putAt.visit(acg);
+        OperandStack os = controller.getOperandStack();
         os.pop();
         os.load(ret.getType(), ret.getIndex());
 
+        CompileStack compileStack = controller.getCompileStack();
         compileStack.removeVar(ret.getIndex());
         compileStack.removeVar(subscript.getIndex());
         compileStack.removeVar(receiver.getIndex());
@@ -635,44 +626,33 @@ public class BinaryExpressionHelper {
 
     protected void evaluateBinaryExpressionWithAssignment(final String method, final BinaryExpression expression) {
         Expression leftExpression = expression.getLeftExpression();
-        AsmClassGenerator acg = controller.getAcg();
-        OperandStack operandStack = controller.getOperandStack();
-
         if (leftExpression instanceof BinaryExpression) {
-            BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
-            if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
-                evaluateArrayAssignmentWithOperator(method, expression, leftBinExpr);
+            BinaryExpression bexp = (BinaryExpression) leftExpression;
+            if (bexp.getOperation().getType() == LEFT_SQUARE_BRACKET) {
+                evaluateArrayAssignmentWithOperator(method, expression, bexp);
                 return;
             }
         }
 
         evaluateBinaryExpression(method, expression);
 
-        // br to leave a copy of rvalue on the stack. see also isPopRequired()
-        operandStack.dup();
-
+        // br to leave a copy of rvalue on the stack; see also isPopRequired()
+        controller.getOperandStack().dup();
         controller.getCompileStack().pushLHS(true);
-        leftExpression.visit(acg);
+        leftExpression.visit(controller.getAcg());
         controller.getCompileStack().popLHS();
     }
 
     private void evaluateInstanceof(final BinaryExpression expression) {
-        OperandStack operandStack = controller.getOperandStack();
-
         expression.getLeftExpression().visit(controller.getAcg());
-        operandStack.box();
+        controller.getOperandStack().box();
         Expression rightExp = expression.getRightExpression();
-        ClassNode classType;
-        if (rightExp instanceof ClassExpression) {
-            ClassExpression classExp = (ClassExpression) rightExp;
-            classType = classExp.getType();
-        } else {
-            throw new RuntimeException(
-                    "Right hand side of the instanceof keyword must be a class name, not: " + rightExp);
+        if (!(rightExp instanceof ClassExpression)) {
+            throw new RuntimeException("RHS of the instanceof keyword must be a class name, not: " + rightExp);
         }
-        String classInternalName = BytecodeHelper.getClassInternalName(classType);
+        String classInternalName = BytecodeHelper.getClassInternalName(rightExp.getType());
         controller.getMethodVisitor().visitTypeInsn(INSTANCEOF, classInternalName);
-        operandStack.replace(ClassHelper.boolean_TYPE);
+        controller.getOperandStack().replace(ClassHelper.boolean_TYPE);
     }
 
     private void evaluateNotInstanceof(final BinaryExpression expression) {
@@ -680,7 +660,7 @@ public class BinaryExpressionHelper {
                 new NotExpression(
                         new BinaryExpression(
                                 expression.getLeftExpression(),
-                                Token.newSymbol(KEYWORD_INSTANCEOF, -1, -1),
+                                GeneralUtils.INSTANCEOF,
                                 expression.getRightExpression()
                         )
                 )
@@ -689,7 +669,7 @@ public class BinaryExpressionHelper {
 
     private void evaluatePostfixMethod(final int op, final String method, final Expression expression, final Expression orig) {
         CompileStack compileStack = controller.getCompileStack();
-        final OperandStack operandStack = controller.getOperandStack();
+        OperandStack operandStack = controller.getOperandStack();
 
         // load Expressions
         VariableSlotLoader usesSubscript = loadWithSubscript(expression);
@@ -699,13 +679,13 @@ public class BinaryExpressionHelper {
         ClassNode expressionType = operandStack.getTopOperand();
         int tempIdx = compileStack.defineTemporaryVariable("postfix_" + method, expressionType, true);
 
-        // execute Method
+        // execute method
         execMethodAndStoreForSubscriptOperator(op, method, expression, usesSubscript, orig);
 
         // remove the result of the method call
         operandStack.pop();
 
-        //reload saved value
+        // reload saved value
         operandStack.load(expressionType, tempIdx);
         compileStack.removeVar(tempIdx);
         if (usesSubscript != null) compileStack.removeVar(usesSubscript.getIndex());
@@ -714,10 +694,10 @@ public class BinaryExpressionHelper {
     public void evaluatePostfixMethod(final PostfixExpression expression) {
         int op = expression.getOperation().getType();
         switch (op) {
-            case Types.PLUS_PLUS:
+            case PLUS_PLUS:
                 evaluatePostfixMethod(op, "next", expression.getExpression(), expression);
                 break;
-            case Types.MINUS_MINUS:
+            case MINUS_MINUS:
                 evaluatePostfixMethod(op, "previous", expression.getExpression(), expression);
                 break;
         }
@@ -726,79 +706,73 @@ public class BinaryExpressionHelper {
     public void evaluatePrefixMethod(final PrefixExpression expression) {
         int type = expression.getOperation().getType();
         switch (type) {
-            case Types.PLUS_PLUS:
+            case PLUS_PLUS:
                 evaluatePrefixMethod(type, "next", expression.getExpression(), expression);
                 break;
-            case Types.MINUS_MINUS:
+            case MINUS_MINUS:
                 evaluatePrefixMethod(type, "previous", expression.getExpression(), expression);
                 break;
         }
     }
 
     private void evaluatePrefixMethod(final int op, final String method, final Expression expression, final Expression orig) {
-        // load Expressions
+        // load expressions
         VariableSlotLoader usesSubscript = loadWithSubscript(expression);
 
-        // execute Method
+        // execute method
         execMethodAndStoreForSubscriptOperator(op,method,expression,usesSubscript,orig);
 
         // new value is already on stack, so nothing to do here
-        if (usesSubscript!=null) controller.getCompileStack().removeVar(usesSubscript.getIndex());
+        if (usesSubscript != null) controller.getCompileStack().removeVar(usesSubscript.getIndex());
     }
 
     private VariableSlotLoader loadWithSubscript(final Expression expression) {
-        final OperandStack operandStack = controller.getOperandStack();
-        // if we have a BinaryExpression, let us check if it is with
-        // subscription
+        AsmClassGenerator acg = controller.getAcg();
+        // if we have a BinaryExpression, check if it is with subscription
         if (expression instanceof BinaryExpression) {
-            BinaryExpression be = (BinaryExpression) expression;
-            if (be.getOperation().getType()== Types.LEFT_SQUARE_BRACKET) {
+            BinaryExpression bexp = (BinaryExpression) expression;
+            if (bexp.getOperation().getType() == LEFT_SQUARE_BRACKET) {
                 // right expression is the subscript expression
                 // we store the result of the subscription on the stack
-                Expression subscript = be.getRightExpression();
-                subscript.visit(controller.getAcg());
+                Expression subscript = bexp.getRightExpression();
+                subscript.visit(acg);
+                OperandStack operandStack = controller.getOperandStack();
                 ClassNode subscriptType = operandStack.getTopOperand();
                 int id = controller.getCompileStack().defineTemporaryVariable("$subscript", subscriptType, true);
                 VariableSlotLoader subscriptExpression = new VariableSlotLoader(subscriptType, id, operandStack);
-                // do modified visit
-                BinaryExpression newBe = new BinaryExpression(be.getLeftExpression(), be.getOperation(), subscriptExpression);
-                newBe.copyNodeMetaData(be);
-                newBe.setSourcePosition(be);
-                newBe.visit(controller.getAcg());
+                BinaryExpression rewrite = binX(bexp.getLeftExpression(), bexp.getOperation(), subscriptExpression);
+                rewrite.copyNodeMetaData(bexp);
+                rewrite.setSourcePosition(bexp);
+                rewrite.visit(acg);
                 return subscriptExpression;
             }
         }
 
         // normal loading of expression
-        expression.visit(controller.getAcg());
+        expression.visit(acg);
         return null;
     }
 
     private void execMethodAndStoreForSubscriptOperator(final int op, String method, final Expression expression, final VariableSlotLoader usesSubscript, final Expression orig) {
-        final OperandStack operandStack = controller.getOperandStack();
-        writePostOrPrefixMethod(op,method,expression,orig);
+        writePostOrPrefixMethod(op, method, expression, orig);
 
         // we need special code for arrays to store the result (like for a[1]++)
-        if (usesSubscript!=null) {
-            CompileStack compileStack = controller.getCompileStack();
+        if (usesSubscript != null) {
             BinaryExpression be = (BinaryExpression) expression;
-
+            CompileStack compileStack = controller.getCompileStack();
+            OperandStack operandStack = controller.getOperandStack();
             ClassNode methodResultType = operandStack.getTopOperand();
-            final int resultIdx = compileStack.defineTemporaryVariable("postfix_" + method, methodResultType, true);
+            int resultIdx = compileStack.defineTemporaryVariable("postfix_" + method, methodResultType, true);
             BytecodeExpression methodResultLoader = new VariableSlotLoader(methodResultType, resultIdx, operandStack);
 
-            // execute the assignment, this will leave the right side
-            // (here the method call result) on the stack
+            // execute the assignment, this will leave the right side (here the method call result) on the stack
             assignToArray(be, be.getLeftExpression(), usesSubscript, methodResultLoader, be.isSafe());
 
             compileStack.removeVar(resultIdx);
-        }
-        // here we handle a.b++ and a++
-        else if (expression instanceof VariableExpression ||
-            expression instanceof FieldExpression ||
-            expression instanceof PropertyExpression)
-        {
-            operandStack.dup();
+
+        } else if (expression instanceof VariableExpression || expression instanceof PropertyExpression || expression instanceof FieldExpression) {
+            // here we handle a.b++ and a++
+            controller.getOperandStack().dup();
             controller.getCompileStack().pushLHS(true);
             expression.visit(controller.getAcg());
             controller.getCompileStack().popLHS();
@@ -807,14 +781,13 @@ public class BinaryExpressionHelper {
     }
 
     protected void writePostOrPrefixMethod(final int op, final String method, final Expression expression, final Expression orig) {
-        final OperandStack operandStack = controller.getOperandStack();
-        // at this point the receiver will be already on the stack.
+        // at this point the receiver will be already on the stack
         // in a[1]++ the method will be "++" aka "next" and the receiver a[1]
-
-        ClassNode BEType = controller.getTypeChooser().resolveType(expression, controller.getClassNode());
-        Expression callSiteReceiverSwap = new BytecodeExpression(BEType) {
+        ClassNode exprType = controller.getTypeChooser().resolveType(expression, controller.getClassNode());
+        Expression callSiteReceiverSwap = new BytecodeExpression(exprType) {
             @Override
             public void visit(MethodVisitor mv) {
+                OperandStack operandStack = controller.getOperandStack();
                 // CallSite is normally not showing up on the
                 // operandStack, so we place a dummy here with same
                 // slot length.
@@ -842,7 +815,6 @@ public class BinaryExpressionHelper {
                 false, false, false, false);
         // now rhs is completely done and we need only to store. In a[1]++ this
         // would be a.getAt(1).next() for the rhs, "lhs" code is a.putAt(1, rhs)
-
     }
 
     private void evaluateElvisOperatorExpression(final ElvisOperatorExpression expression) {
@@ -880,7 +852,7 @@ public class BinaryExpressionHelper {
             truePartType = ClassHelper.getWrapper(truePartType);
         }
         int retValueId = compileStack.defineTemporaryVariable("$t", truePartType, true);
-        operandStack.castToBool(mark,true);
+        operandStack.castToBool(mark, true);
 
         Label l0 = operandStack.jump(IFEQ);
         // true part: load $t and cast to S
@@ -897,14 +869,13 @@ public class BinaryExpressionHelper {
         // finish and cleanup
         mv.visitLabel(l1);
         compileStack.removeVar(retValueId);
-        controller.getOperandStack().replace(common, 2);
-
+        operandStack.replace(common, 2);
     }
 
     private void evaluateNormalTernary(final TernaryExpression expression) {
         MethodVisitor mv = controller.getMethodVisitor();
-        OperandStack operandStack = controller.getOperandStack();
         TypeChooser typeChooser = controller.getTypeChooser();
+        OperandStack operandStack = controller.getOperandStack();
 
         Expression boolPart = expression.getBooleanExpression();
         Expression truePart = expression.getTrueExpression();
@@ -923,7 +894,7 @@ public class BinaryExpressionHelper {
         // load b and convert to boolean
         int mark = operandStack.getStackLength();
         boolPart.visit(controller.getAcg());
-        operandStack.castToBool(mark,true);
+        operandStack.castToBool(mark, true);
 
         Label l0 = operandStack.jump(IFEQ);
         // true part: load x and cast to S
@@ -939,8 +910,7 @@ public class BinaryExpressionHelper {
 
         // finish and cleanup
         mv.visitLabel(l1);
-        controller.getOperandStack().replace(common, 2);
-
+        operandStack.replace(common, 2);
     }
 
     public void evaluateTernary(final TernaryExpression expression) {


[groovy] 04/06: add builders for BytecodeExpression supporting closure/lambda

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

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

commit 70218abc6f8f11028830a9bfe6e1fd065e6219a3
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Feb 14 12:19:08 2020 -0600

    add builders for BytecodeExpression supporting closure/lambda
    
    (cherry picked from commit 158ebffaf8e682ce4a7e6c8e2bc4f393b5824a4c)
---
 .../codehaus/groovy/ast/tools/GeneralUtils.java    | 22 +++++
 .../org/codehaus/groovy/classgen/Verifier.java     | 13 ++-
 .../classgen/asm/sc/StaticTypesCallSiteWriter.java | 21 ++---
 .../asm/sc/StaticTypesUnaryExpressionHelper.java   | 99 ++++++++++------------
 .../transformers/ConstructorCallTransformer.java   | 36 ++++----
 5 files changed, 98 insertions(+), 93 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
index 49b7163..47b45cc 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -60,12 +60,14 @@ import org.codehaus.groovy.ast.stmt.ReturnStatement;
 import org.codehaus.groovy.ast.stmt.Statement;
 import org.codehaus.groovy.ast.stmt.ThrowStatement;
 import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.classgen.BytecodeExpression;
 import org.codehaus.groovy.classgen.Verifier;
 import org.codehaus.groovy.control.io.ReaderSource;
 import org.codehaus.groovy.runtime.GeneratedClosure;
 import org.codehaus.groovy.syntax.Token;
 import org.codehaus.groovy.syntax.Types;
 import org.codehaus.groovy.transform.AbstractASTTransformation;
+import org.objectweb.asm.MethodVisitor;
 
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
@@ -74,6 +76,7 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Consumer;
 
 import static org.apache.groovy.util.BeanUtils.capitalize;
 import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_IDENTICAL;
@@ -156,6 +159,21 @@ public class GeneralUtils {
         return block;
     }
 
+    public static BytecodeExpression bytecodeX(Consumer<MethodVisitor> writer) {
+        return new BytecodeExpression() {
+            @Override
+            public void visit(final MethodVisitor visitor) {
+                writer.accept(visitor);
+            }
+        };
+    }
+
+    public static BytecodeExpression bytecodeX(ClassNode type, Consumer<MethodVisitor> writer) {
+        BytecodeExpression expression = bytecodeX(writer);
+        expression.setType(type);
+        return expression;
+    }
+
     public static MethodCallExpression callSuperX(String methodName, Expression args) {
         return callX(varX("super"), methodName, args);
     }
@@ -757,6 +775,10 @@ public class GeneralUtils {
         return new PropertyExpression(owner, property);
     }
 
+    public static PropertyExpression propX(Expression owner, Expression property, boolean safe) {
+        return new PropertyExpression(owner, property, safe);
+    }
+
     public static PropertyExpression thisPropX(boolean implicit, String property) {
         PropertyExpression pexp = propX(varX("this"), property);
         pexp.setImplicitThis(implicit);
diff --git a/src/main/java/org/codehaus/groovy/classgen/Verifier.java b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
index 6b24a15..4310bfb 100644
--- a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
@@ -93,6 +93,7 @@ import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.markAsGenerated;
 import static org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants;
 import static org.apache.groovy.ast.tools.MethodNodeUtils.getPropertyName;
 import static org.apache.groovy.ast.tools.MethodNodeUtils.methodDescriptorWithoutReturnType;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.callThisX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.declS;
@@ -162,13 +163,11 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
         final String classInternalName = BytecodeHelper.getClassInternalName(node);
         metaClassField =
                 node.addField("metaClass", ACC_PRIVATE | ACC_TRANSIENT | ACC_SYNTHETIC, ClassHelper.METACLASS_TYPE,
-                        new BytecodeExpression(ClassHelper.METACLASS_TYPE) {
-                            @Override
-                            public void visit(MethodVisitor mv) {
-                                mv.visitVarInsn(ALOAD, 0);
-                                mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "$getStaticMetaClass", "()Lgroovy/lang/MetaClass;", false);
-                            }
-                        });
+                        bytecodeX(ClassHelper.METACLASS_TYPE, mv -> {
+                            mv.visitVarInsn(ALOAD, 0);
+                            mv.visitMethodInsn(INVOKEVIRTUAL, classInternalName, "$getStaticMetaClass", "()Lgroovy/lang/MetaClass;", false);
+                        })
+                );
         metaClassField.setSynthetic(true);
         return metaClassField;
     }
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
index 5c19e6c..313ee38 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java
@@ -77,6 +77,7 @@ import static org.codehaus.groovy.ast.ClassHelper.getWrapper;
 import static org.codehaus.groovy.ast.ClassHelper.int_TYPE;
 import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveType;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.callThisX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
@@ -350,13 +351,10 @@ public class StaticTypesCallSiteWriter extends CallSiteWriter implements Opcodes
         Label l4 = new Label();
         mv.visitLabel(l4);
         mv.visitVarInsn(ALOAD, var);
-        final ClassNode finalComponentType = componentType;
-        PropertyExpression pexp = propX(new BytecodeExpression(finalComponentType) {
-            @Override
-            public void visit(final MethodVisitor mv) {
-                mv.visitVarInsn(ALOAD, next);
-            }
-        }, propertyName);
+        PropertyExpression pexp = propX(
+                bytecodeX(componentType, v -> v.visitVarInsn(ALOAD, next)),
+                propertyName
+        );
         pexp.visit(controller.getAcg());
         controller.getOperandStack().box();
         controller.getOperandStack().remove(1);
@@ -430,13 +428,8 @@ public class StaticTypesCallSiteWriter extends CallSiteWriter implements Opcodes
                 if (currentCall != null && currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) != null) {
                     property = currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
                     String[] props = property.split("\\.");
-                    BytecodeExpression thisLoader = new BytecodeExpression(CLOSURE_TYPE) {
-                        @Override
-                        public void visit(final MethodVisitor mv) {
-                            mv.visitVarInsn(ALOAD, 0); // load this
-                        }
-                    };
-                    PropertyExpression pexp = new PropertyExpression(thisLoader, constX(props[0]), safe);
+                    BytecodeExpression thisLoader = bytecodeX(CLOSURE_TYPE, mv -> mv.visitVarInsn(ALOAD, 0));
+                    PropertyExpression pexp = propX(thisLoader, constX(props[0]), safe);
                     for (int i = 1, n = props.length; i < n; i += 1) {
                         pexp.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, CLOSURE_TYPE);
                         pexp = propX(pexp, props[i]);
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesUnaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesUnaryExpressionHelper.java
index c02e0e2..51a8ed4 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesUnaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesUnaryExpressionHelper.java
@@ -30,7 +30,6 @@ import org.codehaus.groovy.classgen.asm.TypeChooser;
 import org.codehaus.groovy.classgen.asm.UnaryExpressionHelper;
 import org.codehaus.groovy.classgen.asm.WriterController;
 import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodVisitor;
 import org.objectweb.asm.Opcodes;
 
 import static org.codehaus.groovy.ast.ClassHelper.boolean_TYPE;
@@ -42,6 +41,7 @@ import static org.codehaus.groovy.ast.ClassHelper.int_TYPE;
 import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveType;
 import static org.codehaus.groovy.ast.ClassHelper.long_TYPE;
 import static org.codehaus.groovy.ast.ClassHelper.short_TYPE;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
 
 /**
  * An unary expression helper which generates optimized bytecode depending on
@@ -63,27 +63,24 @@ public class StaticTypesUnaryExpressionHelper extends UnaryExpressionHelper impl
     public void writeBitwiseNegate(final BitwiseNegationExpression expression) {
         expression.getExpression().visit(controller.getAcg());
         if (isPrimitiveOnTop()) {
-            final ClassNode top = getTopOperand();
-            if (top==int_TYPE || top==short_TYPE || top==byte_TYPE || top==char_TYPE || top==long_TYPE) {
-                BytecodeExpression bytecodeExpression = new BytecodeExpression() {
-                    @Override
-                    public void visit(final MethodVisitor mv) {
-                        if (long_TYPE==top) {
-                            mv.visitLdcInsn(-1);
-                            mv.visitInsn(LXOR);
-                        } else {
-                            mv.visitInsn(ICONST_M1);
-                            mv.visitInsn(IXOR);
-                            if (byte_TYPE==top) {
-                                mv.visitInsn(I2B);
-                            } else if (char_TYPE==top) {
-                                mv.visitInsn(I2C);
-                            } else if (short_TYPE==top) {
-                                mv.visitInsn(I2S);
-                            }
+            ClassNode top = getTopOperand();
+            if (top == int_TYPE || top == short_TYPE || top == byte_TYPE || top == char_TYPE || top == long_TYPE) {
+                BytecodeExpression bytecodeExpression = bytecodeX(mv -> {
+                    if (long_TYPE == top) {
+                        mv.visitLdcInsn(-1);
+                        mv.visitInsn(LXOR);
+                    } else {
+                        mv.visitInsn(ICONST_M1);
+                        mv.visitInsn(IXOR);
+                        if (byte_TYPE == top) {
+                            mv.visitInsn(I2B);
+                        } else if (char_TYPE == top) {
+                            mv.visitInsn(I2C);
+                        } else if (short_TYPE == top) {
+                            mv.visitInsn(I2S);
                         }
                     }
-                };
+                });
                 bytecodeExpression.visit(controller.getAcg());
                 controller.getOperandStack().remove(1);
                 return;
@@ -100,19 +97,16 @@ public class StaticTypesUnaryExpressionHelper extends UnaryExpressionHelper impl
         if (typeChooser.resolveType(subExpression, classNode) == boolean_TYPE) {
             subExpression.visit(controller.getAcg());
             controller.getOperandStack().doGroovyCast(boolean_TYPE);
-            BytecodeExpression bytecodeExpression = new BytecodeExpression() {
-                @Override
-                public void visit(final MethodVisitor mv) {
-                    Label ne = new Label();
-                    mv.visitJumpInsn(IFNE, ne);
-                    mv.visitInsn(ICONST_1);
-                    Label out = new Label();
-                    mv.visitJumpInsn(GOTO, out);
-                    mv.visitLabel(ne);
-                    mv.visitInsn(ICONST_0);
-                    mv.visitLabel(out);
-                }
-            };
+            BytecodeExpression bytecodeExpression = bytecodeX(mv -> {
+                Label ne = new Label();
+                mv.visitJumpInsn(IFNE, ne);
+                mv.visitInsn(ICONST_1);
+                Label out = new Label();
+                mv.visitJumpInsn(GOTO, out);
+                mv.visitLabel(ne);
+                mv.visitInsn(ICONST_0);
+                mv.visitLabel(out);
+            });
             bytecodeExpression.visit(controller.getAcg());
             controller.getOperandStack().remove(1);
             return;
@@ -124,29 +118,26 @@ public class StaticTypesUnaryExpressionHelper extends UnaryExpressionHelper impl
     public void writeUnaryMinus(final UnaryMinusExpression expression) {
         expression.getExpression().visit(controller.getAcg());
         if (isPrimitiveOnTop()) {
-            final ClassNode top = getTopOperand();
-            if (top!=boolean_TYPE) {
-                BytecodeExpression bytecodeExpression = new BytecodeExpression() {
-                    @Override
-                    public void visit(final MethodVisitor mv) {
-                        if (int_TYPE == top || short_TYPE == top || byte_TYPE==top || char_TYPE==top) {
-                            mv.visitInsn(INEG);
-                            if (byte_TYPE==top) {
-                                mv.visitInsn(I2B);
-                            } else if (char_TYPE==top) {
-                                mv.visitInsn(I2C);
-                            } else if (short_TYPE==top) {
-                                mv.visitInsn(I2S);
-                            }
-                        } else if (long_TYPE == top) {
-                            mv.visitInsn(LNEG);
-                        } else if (float_TYPE == top) {
-                            mv.visitInsn(FNEG);
-                        } else if (double_TYPE == top) {
-                            mv.visitInsn(DNEG);
+            ClassNode top = getTopOperand();
+            if (top != boolean_TYPE) {
+                BytecodeExpression bytecodeExpression = bytecodeX(mv -> {
+                    if (int_TYPE == top || short_TYPE == top || byte_TYPE == top || char_TYPE == top) {
+                        mv.visitInsn(INEG);
+                        if (byte_TYPE == top) {
+                            mv.visitInsn(I2B);
+                        } else if (char_TYPE == top) {
+                            mv.visitInsn(I2C);
+                        } else if (short_TYPE == top) {
+                            mv.visitInsn(I2S);
                         }
+                    } else if (long_TYPE == top) {
+                        mv.visitInsn(LNEG);
+                    } else if (float_TYPE == top) {
+                        mv.visitInsn(FNEG);
+                    } else if (double_TYPE == top) {
+                        mv.visitInsn(DNEG);
                     }
-                };
+                });
                 bytecodeExpression.visit(controller.getAcg());
                 controller.getOperandStack().remove(1);
                 return;
diff --git a/src/main/java/org/codehaus/groovy/transform/sc/transformers/ConstructorCallTransformer.java b/src/main/java/org/codehaus/groovy/transform/sc/transformers/ConstructorCallTransformer.java
index 9c269ea..d4f31e4 100644
--- a/src/main/java/org/codehaus/groovy/transform/sc/transformers/ConstructorCallTransformer.java
+++ b/src/main/java/org/codehaus/groovy/transform/sc/transformers/ConstructorCallTransformer.java
@@ -29,7 +29,6 @@ import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
 import org.codehaus.groovy.ast.expr.Expression;
 import org.codehaus.groovy.ast.expr.MapEntryExpression;
 import org.codehaus.groovy.ast.expr.MapExpression;
-import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.expr.TupleExpression;
 import org.codehaus.groovy.classgen.AsmClassGenerator;
 import org.codehaus.groovy.classgen.BytecodeExpression;
@@ -45,12 +44,15 @@ import org.objectweb.asm.Opcodes;
 
 import java.util.List;
 
+import static org.codehaus.groovy.ast.tools.GeneralUtils.binX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.propX;
 import static org.codehaus.groovy.transform.stc.StaticTypesMarker.DIRECT_METHOD_CALL_TARGET;
 
 public class ConstructorCallTransformer {
     private final StaticCompilationTransformer staticCompilationTransformer;
 
-    public ConstructorCallTransformer(StaticCompilationTransformer staticCompilationTransformer) {
+    public ConstructorCallTransformer(final StaticCompilationTransformer staticCompilationTransformer) {
         this.staticCompilationTransformer = staticCompilationTransformer;
     }
 
@@ -116,8 +118,9 @@ public class ConstructorCallTransformer {
             this.originalCall = originalCall;
             this.setSourcePosition(originalCall);
             this.copyNodeMetaData(originalCall);
-            List<Expression> originalExpressions = originalCall.getArguments() instanceof TupleExpression ?
-                    ((TupleExpression)originalCall.getArguments()).getExpressions() : null;
+            List<Expression> originalExpressions = originalCall.getArguments() instanceof TupleExpression
+                    ? ((TupleExpression) originalCall.getArguments()).getExpressions()
+                    : null;
             this.innerClassCall = originalExpressions != null && originalExpressions.size() == 2;
         }
 
@@ -133,12 +136,12 @@ public class ConstructorCallTransformer {
 
         @Override
         public void visit(final MethodVisitor mv) {
-            final WriterController controller = acg.getController();
-            final OperandStack operandStack = controller.getOperandStack();
-            final CompileStack compileStack = controller.getCompileStack();
+            WriterController controller = acg.getController();
+            CompileStack compileStack = controller.getCompileStack();
+            OperandStack operandStack = controller.getOperandStack();
 
             // create a temporary variable to store the constructed object
-            final int tmpObj = compileStack.defineTemporaryVariable("tmpObj", declaringClass, false);
+            int tmpObj = compileStack.defineTemporaryVariable("tmpObj", declaringClass, false);
             String classInternalName = BytecodeHelper.getClassInternalName(declaringClass);
             mv.visitTypeInsn(NEW, classInternalName);
             mv.visitInsn(DUP);
@@ -147,7 +150,7 @@ public class ConstructorCallTransformer {
                 // load "this"
                 mv.visitVarInsn(ALOAD, 0);
                 InnerClassNode icn = (InnerClassNode) declaringClass.redirect();
-                Parameter[] params = { new Parameter(icn.getOuterClass(), "$p$") };
+                Parameter[] params = {new Parameter(icn.getOuterClass(), "$p$")};
                 desc = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, params);
             }
             mv.visitMethodInsn(INVOKESPECIAL, classInternalName, "<init>", desc, false);
@@ -155,17 +158,14 @@ public class ConstructorCallTransformer {
 
             // load every field
             for (MapEntryExpression entryExpression : map.getMapEntryExpressions()) {
-                int line = entryExpression.getLineNumber();
-                int col = entryExpression.getColumnNumber();
                 Expression keyExpression = staticCompilationTransformer.transform(entryExpression.getKeyExpression());
                 Expression valueExpression = staticCompilationTransformer.transform(entryExpression.getValueExpression());
-                BinaryExpression bexp = new BinaryExpression(new PropertyExpression(new BytecodeExpression(declaringClass) {
-                            @Override
-                            public void visit(final MethodVisitor mv) {
-                                mv.visitVarInsn(ALOAD, tmpObj);
-                            }
-                        }, keyExpression),
-                        Token.newSymbol("=", line, col),
+                BinaryExpression bexp = binX(
+                        propX(
+                                bytecodeX(declaringClass, v -> v.visitVarInsn(ALOAD, tmpObj)),
+                                keyExpression
+                        ),
+                        Token.newSymbol("=", entryExpression.getLineNumber(), entryExpression.getColumnNumber()),
                         valueExpression
                 );
                 bexp.setSourcePosition(entryExpression);


[groovy] 06/06: minor edits

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

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

commit 3c5182c5b088441c0b27350e23880e17ee6d17e3
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Feb 14 13:35:06 2020 -0600

    minor edits
    
    (cherry picked from commit ff7b13e9ef3fbde05dda4f12f63adece71b04bba)
---
 .../groovy/ast/expr/PropertyExpression.java        |  89 ++++++-----
 .../codehaus/groovy/ast/expr/TupleExpression.java  |  66 ++++----
 .../codehaus/groovy/ast/tools/GeneralUtils.java    | 178 +++++++++------------
 3 files changed, 154 insertions(+), 179 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/expr/PropertyExpression.java b/src/main/java/org/codehaus/groovy/ast/expr/PropertyExpression.java
index bfc6638..7bfaf84 100644
--- a/src/main/java/org/codehaus/groovy/ast/expr/PropertyExpression.java
+++ b/src/main/java/org/codehaus/groovy/ast/expr/PropertyExpression.java
@@ -27,44 +27,38 @@ public class PropertyExpression extends Expression {
 
     private Expression objectExpression;
     private final Expression property;
-    private boolean spreadSafe = false;
-    private boolean safe = false;
-    private boolean isStatic = false;
+    private boolean safe;
+    private boolean spreadSafe;
+    private boolean isStatic;
+    private boolean implicitThis;
 
-    private boolean implicitThis = false;
-
-    public boolean isStatic() {
-        return isStatic;
+    public PropertyExpression(final Expression objectExpression, final String propertyName) {
+        this(objectExpression, new ConstantExpression(propertyName), false);
     }
 
-    public PropertyExpression(Expression objectExpression, String property) {
-        this(objectExpression, new ConstantExpression(property), false);
-    }
-    
-    public PropertyExpression(Expression objectExpression, Expression property) {
+    public PropertyExpression(final Expression objectExpression, final Expression property) {
         this(objectExpression, property, false);
     }
 
-    public PropertyExpression(Expression objectExpression, Expression property, boolean safe) {
+    public PropertyExpression(final Expression objectExpression, final Expression property, final boolean safe) {
         this.objectExpression = objectExpression;
         this.property = property;
         this.safe = safe;
     }
 
-    public void visit(GroovyCodeVisitor visitor) {
+    public void visit(final GroovyCodeVisitor visitor) {
         visitor.visitPropertyExpression(this);
     }
 
-    public boolean isDynamic() {
-        return true;
-    }
-
-    public Expression transformExpression(ExpressionTransformer transformer) {
-        PropertyExpression ret = new PropertyExpression(transformer.transform(objectExpression),
-                transformer.transform(property), safe);
+    public Expression transformExpression(final ExpressionTransformer transformer) {
+        PropertyExpression ret = new PropertyExpression(
+                transformer.transform(objectExpression),
+                transformer.transform(property),
+                safe
+        );
+        ret.setImplicitThis(implicitThis);
         ret.setSpreadSafe(spreadSafe);
         ret.setStatic(isStatic);
-        ret.setImplicitThis(implicitThis);
         ret.setSourcePosition(this);
         ret.copyNodeMetaData(this);
         return ret;
@@ -74,17 +68,16 @@ public class PropertyExpression extends Expression {
         return objectExpression;
     }
 
-    public void setObjectExpression(Expression exp) {
-        objectExpression=exp;
-    }    
-    
+    public void setObjectExpression(final Expression objectExpression) {
+        this.objectExpression = objectExpression;
+    }
+
     public Expression getProperty() {
         return property;
     }
-    
+
     public String getPropertyAsString() {
-        if (property==null) return null;
-        if (! (property instanceof ConstantExpression)) return null;
+        if (!(property instanceof ConstantExpression)) return null;
         ConstantExpression constant = (ConstantExpression) property;
         return constant.getText();
     }
@@ -97,9 +90,21 @@ public class PropertyExpression extends Expression {
         return object + spread + safe + "." + text;
     }
 
+    public boolean isDynamic() {
+        return true;
+    }
+
+    public boolean isImplicitThis() {
+        return implicitThis;
+    }
+
+    public void setImplicitThis(final boolean implicitThis) {
+        this.implicitThis  = implicitThis;
+    }
+
     /**
-     * @return is this a safe navigation, i.e. if true then if the source object is null
-     * then this navigation will return null
+     * @return is this a safe navigation, i.e. if true then if the source object
+     * is null then this navigation will return null
      */
     public boolean isSafe() {
         return safe;
@@ -109,23 +114,19 @@ public class PropertyExpression extends Expression {
         return spreadSafe;
     }
 
-    public void setSpreadSafe(boolean value) {
-        spreadSafe = value;
+    public void setSpreadSafe(final boolean spreadSafe) {
+        this.spreadSafe = spreadSafe;
     }
 
-    public String toString() {
-        return super.toString() + "[object: " + objectExpression + " property: " + property + "]";
+    public boolean isStatic() {
+        return isStatic;
     }
 
-    public void setStatic(boolean aStatic) {
-        this.isStatic = aStatic;
-    }
-    
-    public boolean isImplicitThis(){
-        return implicitThis;
+    public void setStatic(final boolean isStatic) {
+        this.isStatic = isStatic;
     }
-    
-    public void setImplicitThis(boolean it) {
-        implicitThis  = it;
+
+    public String toString() {
+        return super.toString() + "[object: " + objectExpression + " property: " + property + "]";
     }
 }
diff --git a/src/main/java/org/codehaus/groovy/ast/expr/TupleExpression.java b/src/main/java/org/codehaus/groovy/ast/expr/TupleExpression.java
index 022b7ae..62c5d0b 100644
--- a/src/main/java/org/codehaus/groovy/ast/expr/TupleExpression.java
+++ b/src/main/java/org/codehaus/groovy/ast/expr/TupleExpression.java
@@ -21,87 +21,89 @@ package org.codehaus.groovy.ast.expr;
 import org.codehaus.groovy.ast.GroovyCodeVisitor;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 
-/**
- * Represents a tuple expression {1, 2, 3} which creates an immutable List
- */
 public class TupleExpression extends Expression implements Iterable<Expression> {
+
     private final List<Expression> expressions;
 
     public TupleExpression() {
         this(0);
     }
 
-    public TupleExpression(Expression expr) {
+    public TupleExpression(final Expression expr) {
         this(1);
         addExpression(expr);
     }
 
-    public TupleExpression(Expression expr1, Expression expr2) {
+    public TupleExpression(final Expression expr1, final Expression expr2) {
         this(2);
         addExpression(expr1);
         addExpression(expr2);
     }
 
-    public TupleExpression(Expression expr1, Expression expr2, Expression expr3) {
+    public TupleExpression(final Expression expr1, final Expression expr2, final Expression expr3) {
         this(3);
         addExpression(expr1);
         addExpression(expr2);
         addExpression(expr3);
     }
-    
-    public TupleExpression(int length) {
-        this.expressions = new ArrayList<Expression>(length);
+
+    public TupleExpression(final int capacity) {
+        this.expressions = new ArrayList<>(capacity);
     }
-    
-    public TupleExpression(List<Expression> expressions) {
+
+    public TupleExpression(final List<Expression> expressions) {
         this.expressions = expressions;
     }
-    
-    public TupleExpression(Expression[] expressionArray) {
-        this();
-        expressions.addAll(Arrays.asList(expressionArray));
+
+    public TupleExpression(final Expression[] expressionArray) {
+        this(expressionArray.length);
+        for (Expression e : expressionArray) expressions.add(e);
     }
 
-    public TupleExpression addExpression(Expression expression) {
+    public TupleExpression addExpression(final Expression expression) {
         expressions.add(expression);
         return this;
     }
-    
+
+    public Expression getExpression(final int i) {
+        return expressions.get(i);
+    }
+
     public List<Expression> getExpressions() {
         return expressions;
+        // TODO: return Collections.unmodifiableList(expressions);
+        // see also org.codehaus.groovy.ast.expr.MethodCallExpression.NO_ARGUMENTS
     }
 
-    public void visit(GroovyCodeVisitor visitor) {
+    public Iterator<Expression> iterator() {
+        // TODO: return getExpressions().iterator();
+        return Collections.unmodifiableList(expressions).iterator();
+    }
+
+    public void visit(final GroovyCodeVisitor visitor) {
         visitor.visitTupleExpression(this);
     }
 
-    public Expression transformExpression(ExpressionTransformer transformer) {
-        Expression ret = new TupleExpression(transformExpressions(getExpressions(), transformer)); 
+    public Expression transformExpression(final ExpressionTransformer transformer) {
+        Expression ret = new TupleExpression(transformExpressions(getExpressions(), transformer));
         ret.setSourcePosition(this);
         ret.copyNodeMetaData(this);
         return ret;
     }
 
-    public Expression getExpression(int i) {
-        return expressions.get(i);
-    }
-
     public String getText() {
         StringBuilder buffer = new StringBuilder("(");
         boolean first = true;
-        for (Expression expression : expressions) {
+        for (Expression expression : getExpressions()) {
             if (first) {
                 first = false;
-            }
-            else {
+            } else {
                 buffer.append(", ");
             }
-            
             buffer.append(expression.getText());
         }
         buffer.append(")");
@@ -109,10 +111,6 @@ public class TupleExpression extends Expression implements Iterable<Expression>
     }
 
     public String toString() {
-        return super.toString() + expressions;
-    }
-
-    public Iterator<Expression> iterator() {
-        return Collections.unmodifiableList(expressions).iterator();
+        return super.toString() + getExpressions();
     }
 }
diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
index bf212d8..0d850ce 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -70,6 +70,7 @@ import org.objectweb.asm.MethodVisitor;
 
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -78,7 +79,6 @@ import java.util.Set;
 import java.util.function.Consumer;
 
 import static org.apache.groovy.util.BeanUtils.capitalize;
-import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_IDENTICAL;
 
 /**
  * Handy methods when working with the Groovy AST
@@ -87,7 +87,7 @@ public class GeneralUtils {
     public static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1);
     public static final Token EQ = Token.newSymbol(Types.COMPARE_EQUAL, -1, -1);
     public static final Token NE = Token.newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1);
-    public static final Token NOT_IDENTICAL = Token.newSymbol(COMPARE_NOT_IDENTICAL, -1, -1);
+    public static final Token NOT_IDENTICAL = Token.newSymbol(Types.COMPARE_NOT_IDENTICAL, -1, -1);
     public static final Token LT = Token.newSymbol(Types.COMPARE_LESS_THAN, -1, -1);
     public static final Token AND = Token.newSymbol(Types.LOGICAL_AND, -1, -1);
     public static final Token OR = Token.newSymbol(Types.LOGICAL_OR, -1, -1);
@@ -97,37 +97,33 @@ public class GeneralUtils {
     private static final Token INDEX = Token.newSymbol("[", -1, -1);
 
     public static BinaryExpression andX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, AND, rhv);
+        return binX(lhv, AND, rhv);
     }
 
     public static ArgumentListExpression args(final Expression... expressions) {
-        List<Expression> args = new ArrayList<Expression>();
-        Collections.addAll(args, expressions);
-        return new ArgumentListExpression(args);
+        List<Expression> list = new ArrayList<>(expressions.length);
+        Collections.addAll(list, expressions);
+        return args(list);
     }
 
     public static ArgumentListExpression args(final List<Expression> expressions) {
         return new ArgumentListExpression(expressions);
     }
 
-    public static ArgumentListExpression args(final Parameter[] parameters) {
+    public static ArgumentListExpression args(final Parameter... parameters) {
         return new ArgumentListExpression(parameters);
     }
 
     public static ArgumentListExpression args(final String... names) {
-        List<Expression> vars = new ArrayList<Expression>();
-        for (String name : names) {
-            vars.add(varX(name));
-        }
-        return new ArgumentListExpression(vars);
+        return args(Arrays.stream(names).map(GeneralUtils::varX).toArray(Expression[]::new));
     }
 
     public static Statement assignS(final Expression target, final Expression value) {
-        return new ExpressionStatement(assignX(target, value));
+        return stmt(assignX(target, value));
     }
 
     public static Expression assignX(final Expression target, final Expression value) {
-        return new BinaryExpression(target, ASSIGN, value);
+        return binX(target, ASSIGN, value);
     }
 
     public static Expression attrX(final Expression oe, final Expression prop) {
@@ -138,18 +134,18 @@ public class GeneralUtils {
         return new BinaryExpression(left, token, right);
     }
 
-    public static BlockStatement block(final VariableScope varScope, final Statement... stmts) {
+    public static BlockStatement block(final VariableScope scope, final Statement... stmts) {
         BlockStatement block = new BlockStatement();
-        block.setVariableScope(varScope);
+        block.setVariableScope(scope);
         for (Statement stmt : stmts) {
             block.addStatement(stmt);
         }
         return block;
     }
 
-    public static BlockStatement block(final VariableScope varScope, final List<Statement> stmts) {
+    public static BlockStatement block(final VariableScope scope, final List<Statement> stmts) {
         BlockStatement block = new BlockStatement();
-        block.setVariableScope(varScope);
+        block.setVariableScope(scope);
         for (Statement stmt : stmts) {
             block.addStatement(stmt);
         }
@@ -164,8 +160,8 @@ public class GeneralUtils {
         return block;
     }
 
-    public static BooleanExpression boolX(final Expression boolExpr) {
-        return new BooleanExpression(boolExpr);
+    public static BooleanExpression boolX(final Expression expr) {
+        return new BooleanExpression(expr);
     }
 
     public static BytecodeExpression bytecodeX(final Consumer<MethodVisitor> writer) {
@@ -255,7 +251,7 @@ public class GeneralUtils {
      * @return the expression comparing two values
      */
     public static BinaryExpression cmpX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, CMP, rhv);
+        return binX(lhv, CMP, rhv);
     }
 
     public static ConstantExpression constX(final Object val) {
@@ -271,7 +267,7 @@ public class GeneralUtils {
     }
 
     public static ConstructorCallExpression ctorX(final ClassNode type) {
-        return new ConstructorCallExpression(type, ArgumentListExpression.EMPTY_ARGUMENTS);
+        return ctorX(type, ArgumentListExpression.EMPTY_ARGUMENTS);
     }
 
     public static Statement ctorSuperS(final Expression args) {
@@ -303,11 +299,11 @@ public class GeneralUtils {
     }
 
     public static BinaryExpression eqX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, EQ, rhv);
+        return binX(lhv, EQ, rhv);
     }
 
     public static BooleanExpression equalsNullX(final Expression argExpr) {
-        return new BooleanExpression(eqX(argExpr, new ConstantExpression(null)));
+        return boolX(eqX(argExpr, nullX()));
     }
 
     public static FieldExpression fieldX(final FieldNode fieldNode) {
@@ -319,12 +315,12 @@ public class GeneralUtils {
     }
 
     public static Expression findArg(final String argName) {
-        return new PropertyExpression(new VariableExpression("args"), argName);
+        return propX(varX("args"), argName);
     }
 
     public static List<MethodNode> getAllMethods(final ClassNode type) {
         ClassNode node = type;
-        List<MethodNode> result = new ArrayList<MethodNode>();
+        List<MethodNode> result = new ArrayList<>();
         while (node != null) {
             result.addAll(node.getMethods());
             node = node.getSuperClass();
@@ -334,7 +330,7 @@ public class GeneralUtils {
 
     public static List<PropertyNode> getAllProperties(final ClassNode type) {
         ClassNode node = type;
-        List<PropertyNode> result = new ArrayList<PropertyNode>();
+        List<PropertyNode> result = new ArrayList<>();
         while (node != null) {
             result.addAll(node.getProperties());
             node = node.getSuperClass();
@@ -343,7 +339,7 @@ public class GeneralUtils {
     }
 
     public static List<FieldNode> getInstanceNonPropertyFields(final ClassNode cNode) {
-        List<FieldNode> result = new ArrayList<FieldNode>();
+        List<FieldNode> result = new ArrayList<>();
         for (FieldNode fNode : cNode.getFields()) {
             if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
                 result.add(fNode);
@@ -354,7 +350,7 @@ public class GeneralUtils {
 
     public static List<String> getInstanceNonPropertyFieldNames(final ClassNode cNode) {
         List<FieldNode> fList = getInstanceNonPropertyFields(cNode);
-        List<String> result = new ArrayList<String>(fList.size());
+        List<String> result = new ArrayList<>(fList.size());
         for (FieldNode fNode : fList) {
             result.add(fNode.getName());
         }
@@ -362,7 +358,7 @@ public class GeneralUtils {
     }
 
     public static List<PropertyNode> getInstanceProperties(final ClassNode cNode) {
-        List<PropertyNode> result = new ArrayList<PropertyNode>();
+        List<PropertyNode> result = new ArrayList<>();
         for (PropertyNode pNode : cNode.getProperties()) {
             if (!pNode.isStatic()) {
                 result.add(pNode);
@@ -373,7 +369,7 @@ public class GeneralUtils {
 
     public static List<String> getInstancePropertyNames(final ClassNode cNode) {
         List<PropertyNode> pList = BeanUtils.getAllProperties(cNode, false, false, true);
-        List<String> result = new ArrayList<String>(pList.size());
+        List<String> result = new ArrayList<>(pList.size());
         for (PropertyNode pNode : pList) {
             result.add(pNode.getName());
         }
@@ -381,7 +377,7 @@ public class GeneralUtils {
     }
 
     public static List<FieldNode> getInstancePropertyFields(final ClassNode cNode) {
-        List<FieldNode> result = new ArrayList<FieldNode>();
+        List<FieldNode> result = new ArrayList<>();
         for (PropertyNode pNode : cNode.getProperties()) {
             if (!pNode.isStatic()) {
                 result.add(pNode.getField());
@@ -391,7 +387,7 @@ public class GeneralUtils {
     }
 
     public static Set<ClassNode> getInterfacesAndSuperInterfaces(final ClassNode type) {
-        Set<ClassNode> res = new LinkedHashSet<ClassNode>();
+        Set<ClassNode> res = new LinkedHashSet<>();
         if (type.isInterface()) {
             res.add(type);
             return res;
@@ -407,7 +403,7 @@ public class GeneralUtils {
     public static List<FieldNode> getSuperNonPropertyFields(final ClassNode cNode) {
         List<FieldNode> result;
         if (cNode == ClassHelper.OBJECT_TYPE) {
-            result = new ArrayList<FieldNode>();
+            result = new ArrayList<>();
         } else {
             result = getSuperNonPropertyFields(cNode.getSuperClass());
         }
@@ -422,7 +418,7 @@ public class GeneralUtils {
     public static List<FieldNode> getSuperPropertyFields(final ClassNode cNode) {
         List<FieldNode> result;
         if (cNode == ClassHelper.OBJECT_TYPE) {
-            result = new ArrayList<FieldNode>();
+            result = new ArrayList<>();
         } else {
             result = getSuperPropertyFields(cNode.getSuperClass());
         }
@@ -445,7 +441,7 @@ public class GeneralUtils {
     public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties,
                                                       final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters,
                                                       final boolean traverseSuperClasses, final boolean skipReadonly, final boolean reverse, final boolean allNames, final boolean includeStatic) {
-        List<PropertyNode> result = new ArrayList<PropertyNode>();
+        List<PropertyNode> result = new ArrayList<>();
         if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && !reverse) {
             result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
         }
@@ -500,7 +496,7 @@ public class GeneralUtils {
         if (annotatedNode.equals(owner)) {
             return callThisX(getterName(annotatedNode, pNode));
         }
-        return propX(new VariableExpression("this"), pNode.getName());
+        return propX(varX("this"), pNode.getName());
     }
 
     /**
@@ -549,46 +545,42 @@ public class GeneralUtils {
 
     public static Statement ifElseS(final Expression cond, final Statement thenStmt, final Statement elseStmt) {
         return new IfStatement(
-                cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
+                cond instanceof BooleanExpression ? (BooleanExpression) cond : boolX(cond),
                 thenStmt,
                 elseStmt
         );
     }
 
     public static Statement ifS(final Expression cond, final Expression trueExpr) {
-        return ifS(cond, new ExpressionStatement(trueExpr));
+        return ifElseS(cond, stmt(trueExpr), EmptyStatement.INSTANCE);
     }
 
     public static Statement ifS(final Expression cond, final Statement trueStmt) {
-        return new IfStatement(
-                cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
-                trueStmt,
-                EmptyStatement.INSTANCE
-        );
+        return ifElseS(cond, trueStmt, EmptyStatement.INSTANCE);
     }
 
     public static Expression indexX(final Expression target, final Expression value) {
-        return new BinaryExpression(target, INDEX, value);
+        return binX(target, INDEX, value);
     }
 
     public static BooleanExpression isInstanceOfX(final Expression objectExpression, final ClassNode cNode) {
-        return new BooleanExpression(new BinaryExpression(objectExpression, INSTANCEOF, classX(cNode)));
+        return boolX(binX(objectExpression, INSTANCEOF, classX(cNode)));
     }
 
     public static BooleanExpression isNullX(final Expression expr) {
-        return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(null)));
+        return boolX(binX(expr, EQ, nullX()));
     }
 
     public static BooleanExpression isOneX(final Expression expr) {
-        return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(1)));
+        return boolX(binX(expr, EQ, constX(1)));
     }
 
     public static BooleanExpression isTrueX(final Expression argExpr) {
-        return new BooleanExpression(new BinaryExpression(argExpr, EQ, new ConstantExpression(Boolean.TRUE)));
+        return boolX(binX(argExpr, EQ, constX(Boolean.TRUE)));
     }
 
     public static BooleanExpression isZeroX(final Expression expr) {
-        return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(0)));
+        return boolX(binX(expr, EQ, constX(0)));
     }
 
     public static ListExpression listX(final List<Expression> args) {
@@ -598,7 +590,7 @@ public class GeneralUtils {
     public static ListExpression list2args(final List<? extends Object> args) {
         ListExpression result = new ListExpression();
         for (Object o : args) {
-            result.addExpression(new ConstantExpression(o));
+            result.addExpression(constX(o));
         }
         return result;
     }
@@ -606,25 +598,25 @@ public class GeneralUtils {
     public static ListExpression classList2args(final List<String> args) {
         ListExpression result = new ListExpression();
         for (Object o : args) {
-            result.addExpression(new ClassExpression(ClassHelper.make(o.toString())));
+            result.addExpression(classX(ClassHelper.make(o.toString())));
         }
         return result;
     }
 
     public static VariableExpression localVarX(final String name) {
-        VariableExpression result = new VariableExpression(name);
+        VariableExpression result = varX(name);
         result.setAccessedVariable(result);
         return result;
     }
 
     public static VariableExpression localVarX(final String name, final ClassNode type) {
-        VariableExpression result = new VariableExpression(name, type);
+        VariableExpression result = varX(name, type);
         result.setAccessedVariable(result);
         return result;
     }
 
     public static BinaryExpression ltX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, LT, rhv);
+        return binX(lhv, LT, rhv);
     }
 
     public static MapExpression mapX(final List<MapEntryExpression> expressions) {
@@ -632,27 +624,27 @@ public class GeneralUtils {
     }
 
     public static BinaryExpression neX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, NE, rhv);
+        return binX(lhv, NE, rhv);
     }
 
     public static BinaryExpression notIdenticalX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, NOT_IDENTICAL, rhv);
+        return binX(lhv, NOT_IDENTICAL, rhv);
     }
 
     public static BooleanExpression notNullX(final Expression argExpr) {
-        return new BooleanExpression(new BinaryExpression(argExpr, NE, new ConstantExpression(null)));
+        return boolX(binX(argExpr, NE, nullX()));
     }
 
     public static NotExpression notX(final Expression expr) {
-        return new NotExpression(expr instanceof BooleanExpression ? expr : new BooleanExpression(expr));
+        return new NotExpression(expr instanceof BooleanExpression ? expr : boolX(expr));
     }
 
     public static ConstantExpression nullX() {
-        return new ConstantExpression(null);
+        return constX(null);
     }
 
     public static BinaryExpression orX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, OR, rhv);
+        return binX(lhv, OR, rhv);
     }
 
     public static Parameter param(final ClassNode type, final String name) {
@@ -668,11 +660,11 @@ public class GeneralUtils {
     }
 
     public static Parameter[] params(final Parameter... params) {
-        return params != null ? params : Parameter.EMPTY_ARRAY;
+        return (params != null ? params : Parameter.EMPTY_ARRAY);
     }
 
     public static BinaryExpression plusX(final Expression lhv, final Expression rhv) {
-        return new BinaryExpression(lhv, PLUS, rhv);
+        return binX(lhv, PLUS, rhv);
     }
 
     public static PropertyExpression propX(final Expression owner, final String property) {
@@ -692,14 +684,11 @@ public class GeneralUtils {
     }
 
     public static Statement safeExpression(final Expression fieldExpr, final Expression expression) {
-        return new IfStatement(
-                equalsNullX(fieldExpr),
-                new ExpressionStatement(fieldExpr),
-                new ExpressionStatement(expression));
+        return new IfStatement(equalsNullX(fieldExpr), stmt(fieldExpr), stmt(expression));
     }
 
     public static BooleanExpression sameX(final Expression self, final Expression other) {
-        return new BooleanExpression(callX(self, "is", args(other)));
+        return boolX(callX(self, "is", args(other)));
     }
 
     public static Statement stmt(final Expression expr) {
@@ -708,7 +697,7 @@ public class GeneralUtils {
 
     public static TernaryExpression ternaryX(final Expression cond, final Expression trueExpr, final Expression elseExpr) {
         return new TernaryExpression(
-                cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
+                cond instanceof BooleanExpression ? (BooleanExpression) cond : boolX(cond),
                 trueExpr,
                 elseExpr);
     }
@@ -745,14 +734,8 @@ public class GeneralUtils {
 
     //--------------------------------------------------------------------------
 
-    public static Parameter[] cloneParams(final Parameter[] source) {
-        Parameter[] result = new Parameter[source.length];
-        for (int i = 0; i < source.length; i++) {
-            Parameter srcParam = source[i];
-            Parameter dstParam = new Parameter(srcParam.getOriginType(), srcParam.getName());
-            result[i] = dstParam;
-        }
-        return result;
+    public static Parameter[] cloneParams(final Parameter[] parameters) {
+        return Arrays.stream(parameters).map(p -> param(p.getOriginType(), p.getName())).toArray(Parameter[]::new);
     }
 
     /**
@@ -775,7 +758,6 @@ public class GeneralUtils {
     public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, final List<AnnotationNode> notCopied, final boolean includeGenerated) {
         List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
         for (AnnotationNode annotation : annotationList)  {
-
             List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
             if (annotations.isEmpty()) continue;
 
@@ -793,13 +775,9 @@ public class GeneralUtils {
             if (!(valueExpression instanceof PropertyExpression)) continue;
 
             PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
-            boolean processAnnotation =
-                    propertyExpression.getProperty() instanceof ConstantExpression &&
-                            (
-                                    "RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
-                                            "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
-                            );
-
+            boolean processAnnotation = propertyExpression.getProperty() instanceof ConstantExpression
+                    && ("RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
+                        || "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()));
             if (processAnnotation)  {
                 AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
                 for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet())  {
@@ -818,7 +796,7 @@ public class GeneralUtils {
         final Expression fieldExpr = propX(varX("this"), name);
         Expression initExpr = fNode.getInitialValueExpression();
         Statement assignInit;
-        if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression)initExpr).isNullExpression())) {
+        if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
             if (ClassHelper.isPrimitiveType(fType)) {
                 assignInit = EmptyStatement.INSTANCE;
             } else {
@@ -833,9 +811,9 @@ public class GeneralUtils {
     }
 
     private static String getterName(final ClassNode annotatedNode, final PropertyNode pNode) {
-        String getterName = "get" + capitalize(pNode.getName());
-        boolean existingExplicitGetter = annotatedNode.getMethod(getterName, Parameter.EMPTY_ARRAY) != null;
-        if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType()) && !existingExplicitGetter) {
+        String getterName = getGetterName(pNode);
+        if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType())
+                && annotatedNode.getMethod(getterName, Parameter.EMPTY_ARRAY) == null) {
             getterName = "is" + capitalize(pNode.getName());
         }
         return getterName;
@@ -863,7 +841,7 @@ public class GeneralUtils {
         if (expression == null) throw new IllegalArgumentException("Null: expression");
 
         StringBuilder result = new StringBuilder();
-        for (int x = expression.getLineNumber(); x <= expression.getLastLineNumber(); x++) {
+        for (int x = expression.getLineNumber(), y = expression.getLastLineNumber(); x <= y; x += 1) {
             String line = readerSource.getLine(x, null);
             if (line == null) {
                 throw new Exception(
@@ -880,7 +858,6 @@ public class GeneralUtils {
             result.append(line).append('\n');
         }
 
-
         String source = result.toString().trim();
 
         return source;
@@ -892,7 +869,7 @@ public class GeneralUtils {
         if (preCode instanceof BlockStatement) {
             BlockStatement block = (BlockStatement) preCode;
             List<Statement> statements = block.getStatements();
-            for (int i = 0; i < statements.size(); i++) {
+            for (int i = 0, n = statements.size(); i < n; i += 1) {
                 Statement statement = statements.get(i);
                 // adjust the first statement if it's a super call
                 if (i == 0 && statement instanceof ExpressionStatement) {
@@ -924,15 +901,14 @@ public class GeneralUtils {
                 if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
             }
         }
-
         return false;
     }
 
     public static boolean hasDeclaredMethod(final ClassNode cNode, final String name, final int argsCount) {
-        List<MethodNode> ms = cNode.getDeclaredMethods(name);
-        for (MethodNode m : ms) {
-            Parameter[] paras = m.getParameters();
-            if (paras != null && paras.length == argsCount) {
+        List<MethodNode> methods = cNode.getDeclaredMethods(name);
+        for (MethodNode method : methods) {
+            Parameter[] params = method.getParameters();
+            if (params != null && params.length == argsCount) {
                 return true;
             }
         }
@@ -942,15 +918,15 @@ public class GeneralUtils {
     public static boolean inSamePackage(final ClassNode first, final ClassNode second) {
         PackageNode firstPackage = first.getPackage();
         PackageNode secondPackage = second.getPackage();
-        return ((firstPackage == null && secondPackage == null) ||
-                        firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
+        return ((firstPackage == null && secondPackage == null)
+                || firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
     }
 
     public static boolean inSamePackage(final Class<?> first, final Class<?> second) {
         Package firstPackage = first.getPackage();
         Package secondPackage = second.getPackage();
-        return ((firstPackage == null && secondPackage == null) ||
-                        firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
+        return ((firstPackage == null && secondPackage == null)
+                || firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
     }
 
     public static boolean isDefaultVisibility(final int modifiers) {


[groovy] 01/06: minor edits

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

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

commit c53c97621621c9a3ccc0f577c5d527c52ed2577f
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Feb 13 03:05:47 2020 +0800

    minor edits
    
    (cherry picked from commit 1a9c33864e465836a88f653773f715cd7d0f5614)
---
 src/test/groovy/transform/stc/STCAssignmentTest.groovy | 15 ---------------
 1 file changed, 15 deletions(-)

diff --git a/src/test/groovy/transform/stc/STCAssignmentTest.groovy b/src/test/groovy/transform/stc/STCAssignmentTest.groovy
index ace7882..cb688cc 100644
--- a/src/test/groovy/transform/stc/STCAssignmentTest.groovy
+++ b/src/test/groovy/transform/stc/STCAssignmentTest.groovy
@@ -138,21 +138,6 @@ class STCAssignmentTest extends StaticTypeCheckingTestCase {
         '''
     }
 
-    void testPlusEqualsOnProperty() {
-        assertScript '''
-            class C {
-                int i
-
-                static main(args) {
-                    def c = new C()
-                    c.i = 5
-                    c.i += 10
-                    assert c.i == 15
-                }
-            }
-        '''
-    }
-
     // GROOVY-9385
     void testPlusEqualsOnPrivateField() {
         assertScript '''