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 2019/11/09 07:18:31 UTC

[groovy] branch GROOVY_3_0_X updated (2f2a8c6 -> 94bc65c)

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 2f2a8c6  refactor code (closes #1072)
     new b307c5f  GROOVY-8721, GROOVY-9015: Avoid calling ClassNode#getTypeClass()
     new b53f309  ClosureUtils#hasImplicitParameter(ClosureExpression) can test for "it"
     new aa9af76  refactor code
     new 3a9a57d  Minor refactoring: remove unnecessary visiting (#1070)
     new bdad682  JUnit 4 and other minor edits
     new e0f3f47  copy method target for variable that resolves to implicit-this property
     new 9ce9f48  GROOVY-8305: build "file:" URL for "user.home" and set as Ivy variable
     new 7e61b82  remove extra config
     new 49df75f  if dependency is found in local .m2 repo, don't copy jars to grape cache
     new dddd5ff  GROOVY-8372: pass remote (not local) conf to addDependencyArtifact
     new 9269fe6  Rework check for runtime retention of repeatable annotation collector
     new 94bc65c  GROOVY-7996: check for get(String)/set(String,Object) or propertyMissing

The 12 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:
 src/main/groovy/groovy/grape/GrapeIvy.groovy       | 123 +++----
 .../groovy/ast/expr/ClosureExpression.java         |  17 +-
 .../codehaus/groovy/ast/tools/ClosureUtils.java    |   3 +-
 .../codehaus/groovy/ast/tools/GeneralUtils.java    |  11 +-
 .../codehaus/groovy/classgen/ExtendedVerifier.java |  44 +--
 .../classgen/InnerClassCompletionVisitor.java      |   4 +-
 .../groovy/classgen/asm/BytecodeHelper.java        | 153 ++++----
 .../groovy/runtime/callsite/CallSiteGenerator.java |  44 +--
 .../transform/stc/StaticTypeCheckingVisitor.java   |  59 ++-
 src/resources/groovy/grape/defaultGrapeConfig.xml  |   5 +-
 .../groovy/grape/defaultGrapeConfig.xml            |  35 --
 src/test/groovy/ClosureJavaIntegrationTest.java    |  12 +-
 .../MyIntegerAnnoTraceASTTransformation.java       |   2 +-
 src/test/groovy/bugs/Groovy7996.groovy             |  14 +-
 src/test/groovy/grape/GrapeIvyTest.groovy          | 407 ++++++++++++---------
 src/test/groovy/lang/GStringTest.java              |   4 +-
 src/test/groovy/lang/GroovyShellTest.java          |   4 +-
 src/test/groovy/lang/IntegerNumberRangeTest.java   |   4 +-
 src/test/groovy/lang/IntegerObjectRangeTest.java   |   4 +-
 src/test/groovy/util/EvalTest.java                 |   8 +-
 .../groovy/ast/MethodCallExpressionTest.java       |   2 +-
 src/test/org/codehaus/groovy/classgen/ForTest.java |   6 +-
 .../asm/sc/bugs/support/Groovy7365Support.java     |   2 +-
 .../org/codehaus/groovy/runtime/DummyBean.java     |   2 +-
 .../groovy/runtime/InvokeConstructorTest.java      |   6 +-
 .../groovy/runtime/InvokeGroovyMethodTest.java     |  14 +-
 .../groovy/runtime/memoize/CommonCacheTest.java    |   4 +-
 .../runtime/memoize/ConcurrentCommonCacheTest.java |   4 +-
 .../runtime/memoize/StampedCommonCacheTest.java    |   4 +-
 .../rootloadersync/SubclassingInJavaTest.java      |   4 +-
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 130 +------
 31 files changed, 530 insertions(+), 605 deletions(-)
 delete mode 100644 src/test-resources/groovy/grape/defaultGrapeConfig.xml


[groovy] 11/12: Rework check for runtime retention of repeatable annotation collector

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 9269fe6b07fbcfcff5c6d7befec6a2724c5447f4
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Nov 5 10:59:25 2019 -0600

    Rework check for runtime retention of repeatable annotation collector
    
    - if repeatee has runtime retention, collector must as well
    - if repeatable isn't resolved, evaluateExpression will handle aliasing
    
    (cherry picked from commit c2ea336d935beb62da4977e82714261c182b69dd)
---
 .../codehaus/groovy/classgen/ExtendedVerifier.java | 44 +++++++++++-----------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
index 3402886..57f13b1 100644
--- a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
@@ -51,10 +51,12 @@ import java.util.Collections;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 import static org.codehaus.groovy.ast.tools.GenericsUtils.correctToGenericsSpec;
 import static org.codehaus.groovy.ast.tools.GenericsUtils.correctToGenericsSpecRecurse;
 import static org.codehaus.groovy.ast.tools.GenericsUtils.createGenericsSpec;
+import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.evaluateExpression;
 
 /**
  * A specialized Groovy AST visitor meant to perform additional verifications upon the
@@ -177,10 +179,10 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport {
                 seen.add(visited);
                 nonSourceAnnotations.put(name, seen);
             }
-            boolean isTargetAnnotation = name.equals("java.lang.annotation.Target");
 
             // Check if the annotation target is correct, unless it's the target annotating an annotation definition
             // defining on which target elements the annotation applies
+            boolean isTargetAnnotation = name.equals("java.lang.annotation.Target");
             if (!isTargetAnnotation && !visited.isTargetAllowed(target)) {
                 addError("Annotation @" + name + " is not allowed on element " + AnnotationNode.targetToName(target), visited);
             }
@@ -206,28 +208,26 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport {
                 }
                 if (repeatable != null) {
                     AnnotationNode collector = new AnnotationNode(repeatable);
-                    if (repeatable.isResolved()) {
+                    if (repeatee.hasRuntimeRetention()) {
+                        collector.setRuntimeRetention(true);
+                    } else if (repeatable.isResolved()) {
                         Class<?> repeatableType = repeatable.getTypeClass();
-                        Retention retAnn = repeatableType.getAnnotation(Retention.class);
-                        collector.setRuntimeRetention(retAnn != null && retAnn.value().equals(RetentionPolicy.RUNTIME));
-                    } else if (repeatable.redirect() != null) {
-                        for (AnnotationNode annotationNode : repeatable.redirect().getAnnotations()) {
-                            if (!annotationNode.getClassNode().getName().equals("java.lang.annotation.Retention"))
-                                continue;
-                            String value = annotationNode.getMember("value").getText();
-                            collector.setRuntimeRetention(value.equals(RetentionPolicy.RUNTIME.name()) ||
-                                    value.equals(RetentionPolicy.class.getName() + "." + RetentionPolicy.RUNTIME.name()));
+                        Retention retention = repeatableType.getAnnotation(Retention.class);
+                        collector.setRuntimeRetention(retention != null && retention.value().equals(RetentionPolicy.RUNTIME));
+                    } else {
+                        for (AnnotationNode annotation : repeatable.getAnnotations()) {
+                            if (annotation.getClassNode().getName().equals("java.lang.annotation.Retention")) {
+                                Expression value = annotation.getMember("value"); assert value != null;
+                                Object retention = evaluateExpression(value, source.getConfiguration());
+                                collector.setRuntimeRetention(retention != null && retention.toString().equals("RUNTIME"));
+                                break;
+                            }
                         }
                     }
-
-                    List<Expression> annos = new ArrayList<>();
-                    for (AnnotationNode an : next.getValue()) {
-                        annos.add(new AnnotationConstantExpression(an));
-                    }
-                    collector.addMember("value", new ListExpression(annos));
-
-                    node.addAnnotation(collector);
+                    collector.addMember("value", new ListExpression(next.getValue().stream()
+                        .map(AnnotationConstantExpression::new).collect(Collectors.toList())));
                     node.getAnnotations().removeAll(next.getValue());
+                    node.addAnnotation(collector);
                 }
             }
         }
@@ -250,8 +250,8 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport {
 
     // TODO GROOVY-5011 handle case of @Override on a property
     private void visitOverride(AnnotatedNode node, AnnotationNode visited) {
-        ClassNode annotationClassNode = visited.getClassNode();
-        if (annotationClassNode.isResolved() && annotationClassNode.getName().equals("java.lang.Override")) {
+        ClassNode annotationType = visited.getClassNode();
+        if (annotationType.isResolved() && annotationType.getName().equals("java.lang.Override")) {
             if (node instanceof MethodNode && !Boolean.TRUE.equals(node.getNodeMetaData(Verifier.DEFAULT_PARAMETER_GENERATED))) {
                 boolean override = false;
                 MethodNode origMethod = (MethodNode) node;
@@ -288,7 +288,7 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport {
                 MethodNode found = getDeclaredMethodCorrected(genericsSpec, mn, correctedNext);
                 if (found != null) break;
             }
-            List<ClassNode> ifaces = new ArrayList<ClassNode>(Arrays.asList(next.getInterfaces()));
+            List<ClassNode> ifaces = new ArrayList<>(Arrays.asList(next.getInterfaces()));
             while (!ifaces.isEmpty()) {
                 ClassNode origInterface = ifaces.remove(0);
                 if (!origInterface.equals(ClassHelper.OBJECT_TYPE)) {


[groovy] 05/12: JUnit 4 and other 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 bdad682ab28beeff8395ee3e1cb4deb6b70d2193
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Nov 6 11:05:46 2019 -0600

    JUnit 4 and other minor edits
    
    (cherry picked from commit 7c26ce6c81b258ae5d4b654d6c7ebc74d3030c5f)
---
 src/main/groovy/groovy/grape/GrapeIvy.groovy | 118 ++++-----
 src/test/groovy/grape/GrapeIvyTest.groovy    | 355 ++++++++++++++-------------
 2 files changed, 233 insertions(+), 240 deletions(-)

diff --git a/src/main/groovy/groovy/grape/GrapeIvy.groovy b/src/main/groovy/groovy/grape/GrapeIvy.groovy
index be969b9..c1c637e 100644
--- a/src/main/groovy/groovy/grape/GrapeIvy.groovy
+++ b/src/main/groovy/groovy/grape/GrapeIvy.groovy
@@ -23,8 +23,6 @@ import org.apache.groovy.plugin.GroovyRunner
 import org.apache.groovy.plugin.GroovyRunnerRegistry
 import org.apache.ivy.Ivy
 import org.apache.ivy.core.IvyContext
-import org.apache.ivy.core.cache.ResolutionCacheManager
-import org.apache.ivy.core.event.IvyListener
 import org.apache.ivy.core.event.download.PrepareDownloadEvent
 import org.apache.ivy.core.event.resolve.StartResolveEvent
 import org.apache.ivy.core.module.descriptor.Configuration
@@ -52,7 +50,6 @@ import org.codehaus.groovy.reflection.ReflectionUtils
 import org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner
 import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl
 
-import javax.xml.parsers.DocumentBuilderFactory
 import java.util.jar.JarFile
 import java.util.regex.Pattern
 import java.util.zip.ZipEntry
@@ -86,7 +83,6 @@ class GrapeIvy implements GrapeEngine {
     // we keep the settings so that addResolver can add to the resolver chain
     IvySettings settings
 
-    @SuppressWarnings('Instanceof')
     GrapeIvy() {
         // if we are already initialized, quit
         if (enableGrapes) return
@@ -104,9 +100,8 @@ class GrapeIvy implements GrapeEngine {
             settings.load(grapeConfig) // exploit multi-methods for convenience
         } catch (java.text.ParseException ex) {
             def configLocation = grapeConfig instanceof File ? grapeConfig.canonicalPath : grapeConfig.toString()
-            System.err.println "Local Ivy config file '$configLocation' appears corrupt - ignoring it and using default config instead\nError was: " + ex.message
-            grapeConfig = GrapeIvy.getResource('defaultGrapeConfig.xml')
-            settings.load(grapeConfig)
+            System.err.println "Local Ivy config file '$configLocation' appears corrupt - ignoring it and using default config instead\nError was: ${ex.message}"
+            settings.load(GrapeIvy.getResource('defaultGrapeConfig.xml'))
         }
 
         // set up the cache dirs
@@ -418,11 +413,9 @@ class GrapeIvy implements GrapeEngine {
     }
 
     ResolveReport getDependencies(Map args, IvyGrabRecord... grabRecords) {
-        ResolutionCacheManager cacheManager = ivyInstance.resolutionCacheManager
-
+        def cacheManager = ivyInstance.resolutionCacheManager
         def millis = System.currentTimeMillis()
-        def md = new DefaultModuleDescriptor(ModuleRevisionId
-                .newInstance('caller', 'all-caller', 'working' + millis.toString()[-2..-1]), 'integration', null, true)
+        def md = new DefaultModuleDescriptor(ModuleRevisionId.newInstance('caller', 'all-caller', 'working' + millis.toString()[-2..-1]), 'integration', null, true)
         md.addConfiguration(new Configuration('default'))
         md.lastModified = millis
 
@@ -431,30 +424,34 @@ class GrapeIvy implements GrapeEngine {
         for (IvyGrabRecord grabRecord : grabRecords) {
             def conf = grabRecord.conf ?: ['*']
             DefaultDependencyDescriptor dd = (DefaultDependencyDescriptor) md.dependencies.find {
-                it.dependencyRevisionId.equals(grabRecord.mrid)
+                it.dependencyRevisionId == grabRecord.mrid
             }
-            if (dd) {
-                addDependencyArtifactDescriptor(dd, grabRecord, conf)
-            } else {
-                dd = new DefaultDependencyDescriptor(md, grabRecord.mrid, grabRecord.force,
-                        grabRecord.changing, grabRecord.transitive)
+            if (!dd) {
+                dd = new DefaultDependencyDescriptor(md, grabRecord.mrid, grabRecord.force, grabRecord.changing, grabRecord.transitive)
                 conf.each { dd.addDependencyConfiguration('default', it) }
-                addDependencyArtifactDescriptor(dd, grabRecord, conf)
                 md.addDependency(dd)
             }
+
+            // the optional configuration typically does not extend the default or master configuration, so prevent grabbing the main artifact
+            if (Collections.singleton('optional') == (conf as Set)) continue
+
+            // add artifact descriptor to dependency descriptor
+            def dad = new DefaultDependencyArtifactDescriptor(dd, grabRecord.mrid.name, grabRecord.type ?: 'jar', grabRecord.ext ?: 'jar', null, grabRecord.classifier ? [classifier: grabRecord.classifier] : null)
+            conf.each { dad.addConfiguration(it) }
+            dd.addDependencyArtifact('default', dad)
         }
 
         // resolve grab and dependencies
-        ResolveOptions resolveOptions = new ResolveOptions().tap {
-            confs = DEF_CONFIG as String[]
-            outputReport = false
-            validate = (boolean) (args.containsKey('validate') ? args.validate : false)
-        }
+        def resolveOptions = new ResolveOptions(
+            confs: DEF_CONFIG as String[],
+            outputReport: false,
+            validate: (boolean) (args.containsKey('validate') ? args.validate : false)
+        )
         ivyInstance.settings.defaultResolver = args.autoDownload ? 'downloadGrapes' : 'cachedGrapes'
         if (args.disableChecksums) {
             ivyInstance.settings.setVariable('ivy.checksums', '')
         }
-        boolean reportDownloads = System.getProperty('groovy.grape.report.downloads', 'false') == 'true'
+        boolean reportDownloads = Boolean.getBoolean('groovy.grape.report.downloads')
         if (reportDownloads) {
             addIvyListener()
         }
@@ -493,39 +490,27 @@ class GrapeIvy implements GrapeEngine {
     }
 
     private addIvyListener() {
-        ivyInstance.eventManager.addIvyListener([progress: { ivyEvent ->
+        ivyInstance.eventManager.addIvyListener { ivyEvent ->
             switch (ivyEvent) {
-                case StartResolveEvent:
-                    ivyEvent.moduleDescriptor.dependencies.each { it ->
-                        def name = it.toString()
-                        if (!resolvedDependencies.contains(name)) {
-                            resolvedDependencies << name
-                            System.err.println "Resolving $name"
-                        }
+            case StartResolveEvent:
+                ivyEvent.moduleDescriptor.dependencies.each {
+                    def name = it.toString()
+                    if (!resolvedDependencies.contains(name)) {
+                        resolvedDependencies << name
+                        System.err.println "Resolving $name"
                     }
-                    break
-                case PrepareDownloadEvent:
-                    ivyEvent.artifacts.each { it ->
-                        def name = it.toString()
-                        if (!downloadedArtifacts.contains(name)) {
-                            downloadedArtifacts << name
-                            System.err.println "Preparing to download artifact $name"
-                        }
+                }
+                break
+            case PrepareDownloadEvent:
+                ivyEvent.artifacts.each {
+                    def name = it.toString()
+                    if (!downloadedArtifacts.contains(name)) {
+                        downloadedArtifacts << name
+                        System.err.println "Preparing to download artifact $name"
                     }
-                    break
+                }
+                break
             }
-        }] as IvyListener)
-    }
-
-    @CompileStatic
-    private void addDependencyArtifactDescriptor(DefaultDependencyDescriptor dd, IvyGrabRecord grabRecord, List<String> conf) {
-        // TODO: find out "unknown" reason and change comment below - also, confirm conf[0] check vs conf.contains('optional')
-        if (conf[0] != 'optional' || grabRecord.classifier) {
-            // for some unknown reason optional dependencies should not have an artifactDescriptor
-            def dad = new DefaultDependencyArtifactDescriptor(dd,
-                    grabRecord.mrid.name, grabRecord.type ?: 'jar', grabRecord.ext ?: 'jar', null, grabRecord.classifier ? [classifier: grabRecord.classifier] : null)
-            conf.each { dad.addConfiguration(it) }
-            dd.addDependencyArtifact('default', dad)
         }
     }
 
@@ -540,8 +525,7 @@ class GrapeIvy implements GrapeEngine {
                         // TODO handle other types? e.g. 'dlls'
                         def jardir = new File(moduleDir, 'jars')
                         if (!jardir.exists()) return
-                        def dbf = DocumentBuilderFactory.newInstance()
-                        def db = dbf.newDocumentBuilder()
+                        def db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder()
                         def root = db.parse(ivyFile).documentElement
                         def publis = root.getElementsByTagName('publications')
                         for (int i = 0; i < publis.length; i++) {
@@ -784,20 +768,16 @@ class IvyGrabRecord {
     }
 
     @Override
-    boolean equals(Object obj) {
-        if (null == obj || obj.class != IvyGrabRecord) {
-            return false
+    boolean equals(Object that) {
+        if (that instanceof IvyGrabRecord) {
+            return (this.mrid == that.mrid)
+                && (this.conf == that.conf)
+                && (this.changing == that.changing)
+                && (this.transitive == that.transitive)
+                && (this.force == that.force)
+                && (this.classifier == that.classifier)
+                && (this.ext == that.ext)
+                && (this.type == that.type)
         }
-
-        IvyGrabRecord o = (IvyGrabRecord) obj
-
-        ((changing == o.changing)
-                && (transitive == o.transitive)
-                && (force == o.force)
-                && (mrid == o.mrid)
-                && (conf == o.conf)
-                && (classifier == o.classifier)
-                && (ext == o.ext)
-                && (type == o.type))
     }
 }
diff --git a/src/test/groovy/grape/GrapeIvyTest.groovy b/src/test/groovy/grape/GrapeIvyTest.groovy
index 0fb05b5..375d0c7 100644
--- a/src/test/groovy/grape/GrapeIvyTest.groovy
+++ b/src/test/groovy/grape/GrapeIvyTest.groovy
@@ -19,270 +19,284 @@
 package groovy.grape
 
 import org.codehaus.groovy.control.CompilationFailedException
-import gls.CompilableTestSupport
+import org.junit.BeforeClass
+import org.junit.Test
 
-class GrapeIvyTest extends CompilableTestSupport {
+import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
 
-    GrapeIvyTest() {
+final class GrapeIvyTest {
+
+    private static Set<String> jarNames(GroovyClassLoader loader) {
+        loader.URLs.collect { url -> url.path.split('/')[-1] } as Set
+    }
+
+    @BeforeClass
+    static void setUpClass() {
         // make sure files are installed locally
-        [[groupId:'log4j', artifactId:'log4j', version:'1.1.3'],
+        [
+            [groupId:'log4j', artifactId:'log4j', version:'1.1.3'],
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
             [groupId:'com.jidesoft', artifactId:'jide-oss', version:'2.2.12'],
-            [groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', conf:['default', 'optional']],
-            [groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15']
-        ].each {
-            Grape.resolve([autoDownload:true, classLoader:new GroovyClassLoader()], it)
+            [groupId:'commons-lang', artifactId:'commons-lang', version:'2.6'],
+            [groupId:'org.neo4j', artifactId:'neo4j-kernel', version:'2.0.0-RC1'],
+            [groupId:'commons-digester', artifactId:'commons-digester', version:'2.1'],
+            [groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15'],
+            [groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', conf:['default', 'optional']]
+        ].each { spec ->
+            Grape.resolve([autoDownload:true, classLoader:new GroovyClassLoader()], spec)
         }
     }
 
+    @Test
     void testSingleArtifact() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
-        Grape.grab(groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)', classLoader:loader)
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
+        Grape.grab(groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)', classLoader:shell.classLoader)
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testModuleWithDependencies() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
-        Grape.grab(groupId:'org.apache.poi', artifactId:'poi', version:'3.7', classLoader:loader)
-        assert shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class").name == 'org.apache.poi.POIDocument'
+        Grape.grab(groupId:'org.apache.poi', artifactId:'poi', version:'3.7', classLoader:shell.classLoader)
+        assert shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class').name == 'org.apache.poi.POIDocument'
     }
 
+    @Test
     void testMultipleDependencies() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
 
-        Grape.grab(classLoader:loader,
+        Grape.grab(classLoader:shell.classLoader,
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
             [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])
 
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
-        assert shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class").name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class').name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testListDependencies() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
 
-        Grape.grab(classLoader:loader,
+        Grape.grab(classLoader:shell.classLoader,
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
             [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])
 
-        def loadedDependencies = Grape.listDependencies(loader)
+        def loadedDependencies = Grape.listDependencies(shell.classLoader)
         assert loadedDependencies == [
             [group:'org.apache.poi', module:'poi', version:'3.7'],
             [group:'com.jidesoft', module:'jide-oss', version:'[2.2.1,2.3)']
         ]
     }
 
+    @Test
     void testGrabRefless() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
         shell.evaluate("new groovy.grape.Grape().grab(groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)')")
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testGrabScriptClass() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
         shell.evaluate("new groovy.grape.Grape().grab(groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)', refObject:this)")
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testGrabScriptLoader() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
-        shell.setVariable("loader", loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
+        shell.setVariable('loader', shell.classLoader)
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
         shell.evaluate("new groovy.grape.Grape().grab(groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)', classLoader:loader)")
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testGrabReflessMultiple() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
-        shell.evaluate("""new groovy.grape.Grape().grab([:],
+        shell.evaluate('''new groovy.grape.Grape().grab([:],
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
-            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])""")
+            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])''')
 
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
-        assert shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class").name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class').name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testGrabScriptClassMultiple() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
-        shell.evaluate("""new groovy.grape.Grape().grab(refObject: this,
+        shell.evaluate('''new groovy.grape.Grape().grab(refObject: this,
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
-            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])""")
+            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])''')
 
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
         assert shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class").name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testGrabScriptLoaderMultiple() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
-        shell.setVariable("loader", loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
+        shell.setVariable('loader', shell.classLoader)
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class")
+            shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class')
         }
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class")
+            shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class')
         }
-        shell.evaluate("""new groovy.grape.Grape().grab(classLoader:loader,
+        shell.evaluate('''new groovy.grape.Grape().grab(classLoader:loader,
             [groupId:'org.apache.poi', artifactId:'poi', version:'3.7'],
-            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])""")
+            [groupId:'com.jidesoft', artifactId:'jide-oss', version:'[2.2.1,2.3)'])''')
 
-        assert shell.evaluate("import com.jidesoft.swing.JideSplitButton; JideSplitButton.class").name == 'com.jidesoft.swing.JideSplitButton';
-        assert shell.evaluate("import org.apache.poi.POIDocument; POIDocument.class").name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import org.apache.poi.POIDocument; POIDocument.class').name == 'org.apache.poi.POIDocument'
+        assert shell.evaluate('import com.jidesoft.swing.JideSplitButton; JideSplitButton.class').name == 'com.jidesoft.swing.JideSplitButton';
     }
 
+    @Test
     void testSerialGrabs() {
         GroovyClassLoader loader = new GroovyClassLoader()
         Grape.grab(groupId:'log4j', artifactId:'log4j', version:'1.1.3', classLoader:loader)
         Grape.grab(groupId:'org.apache.poi', artifactId:'poi', version:'3.7', classLoader:loader)
         def jars = jarNames(loader)
         // because poi asks for log4j 1.2.13, but we already have 1.1.3 so it won't be loaded
-        assert jars.contains ("log4j-1.1.3.jar")
-        assert !jars.contains ("log4j-1.2.13.jar")
+        assert jars.contains('log4j-1.1.3.jar')
+        assert !jars.contains('log4j-1.2.13.jar')
 
         Grape.grab(groupId:'log4j', artifactId:'log4j', version:'1.2.13', classLoader:loader)
         jars = jarNames(loader)
         // because log4j 1.1.3 was loaded first, 1.2.13 should not get loaded
         // even though it was explicitly asked for
-        assert jars.contains ("log4j-1.1.3.jar")
-        assert !jars.contains ("log4j-1.2.13.jar")
+        assert jars.contains('log4j-1.1.3.jar')
+        assert !jars.contains('log4j-1.2.13.jar')
     }
 
+    @Test
     void testConf() {
-        GroovyClassLoader loader = new GroovyClassLoader()
+        Set noJars = [
+        ]
+        Set coreJars = [
+            'ivy-2.0.0.jar'
+        ]
+        Set testJars = [
+            'commons-lang-2.3.jar',
+            'junit-3.8.2.jar'
+        ]
+        Set optionalJars = [
+            'ant-1.6.2.jar',
+            'ant-nodeps-1.6.2.jar',
+            'ant-trax-1.6.2.jar',
+            'commons-codec-1.2.jar',
+            'commons-httpclient-3.0.jar',
+            'commons-logging-1.0.4.jar',
+            'commons-vfs-1.0.jar',
+            'jsch-0.1.31.jar',
+            'junit-3.8.1.jar',
+            'oro-2.0.8.jar'
+        ]
 
-        def coreJars = ["ivy-2.0.0.jar"] as Set
-        def optionalJars = [
-                "ant-1.6.2.jar",
-                "ant-trax-1.6.2.jar",
-                "ant-nodeps-1.6.2.jar",
-                "commons-httpclient-3.0.jar",
-                "junit-3.8.1.jar",
-                "commons-codec-1.2.jar",
-                "oro-2.0.8.jar",
-                "commons-vfs-1.0.jar",
-                "commons-logging-1.0.4.jar",
-                "jsch-0.1.31.jar",
-            ]  as Set
-        def testJars = [
-                "junit-3.8.2.jar",
-                "commons-lang-2.3.jar",
-            ]  as Set
-
-        Grape.grab(groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', classLoader:loader, preserveFiles:true)
+        def loader = new GroovyClassLoader()
+        Grape.grab(groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', classLoader:loader)
         def jars = jarNames(loader)
-        assert coreJars - jars == Collections.EMPTY_SET, "assert that all core jars are present"
-        assert testJars - jars == testJars, "assert that no test jars are present"
-        assert optionalJars - jars == optionalJars, "assert that no optional jars are present"
-        assert jars == coreJars, "assert that no extraneous jars are present"
+        assert jars == coreJars, 'assert that no extraneous jars are present'
+        assert coreJars - jars == noJars, 'assert that all core jars are present'
+        assert testJars - jars == testJars, 'assert that no test jars are present'
+        assert optionalJars - jars == optionalJars, 'assert that no optional jars are present'
 
         loader = new GroovyClassLoader()
         Grape.grab(groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', conf:'optional', classLoader:loader)
         jars = jarNames(loader)
-        assert coreJars - jars == coreJars, "assert that no core jars are present"
-        assert testJars - jars == testJars, "assert that no test jars are present"
-        assert optionalJars - jars == Collections.EMPTY_SET, "assert that all optional jars are present"
-        assert jars == optionalJars, "assert that no extraneous jars are present"
+        assert jars == optionalJars, 'assert that no extraneous jars are present'
+        assert coreJars - jars == coreJars, 'assert that no core jars are present'
+        assert testJars - jars == testJars, 'assert that no test jars are present'
+        assert optionalJars - jars == noJars, 'assert that all optional jars are present'
 
         loader = new GroovyClassLoader()
         Grape.grab(groupId:'org.apache.ivy', artifactId:'ivy', version:'2.0.0', conf:['default', 'optional'], classLoader:loader)
         jars = jarNames(loader)
-        assert coreJars - jars == Collections.EMPTY_SET, "assert that all core jars are present"
-        assert testJars - jars == testJars, "assert that no test jars are present"
-        assert optionalJars - jars == Collections.EMPTY_SET, "assert that all optional jars are present"
-        assert jars == coreJars + optionalJars, "assert that no extraneous jars are present"
-    }
-
-    private static Set<String> jarNames(GroovyClassLoader loader) {
-        loader.getURLs().collect { URL it -> it.getPath().split('/')[-1] } as Set
+        assert coreJars - jars == noJars, 'assert that all core jars are present'
+        assert testJars - jars == testJars, 'assert that no test jars are present'
+        assert optionalJars - jars == noJars, 'assert that all optional jars are present'
+        assert jars == coreJars + optionalJars, 'assert that no extraneous jars are present'
     }
 
+    @Test
     void testClassifier() {
-        GroovyClassLoader loader = new GroovyClassLoader()
-        GroovyShell shell = new GroovyShell(loader)
+        def shell = new GroovyShell(new GroovyClassLoader())
         shouldFail(CompilationFailedException) {
-            shell.evaluate("import net.sf.json.JSON; JSON")
+            shell.evaluate('import net.sf.json.JSON; JSON')
         }
-        Grape.grab(groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15', classLoader:loader)
-        assert shell.evaluate("import net.sf.json.JSON; JSON").name == 'net.sf.json.JSON'
+        Grape.grab(groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15', classLoader:shell.classLoader)
+        assert shell.evaluate('import net.sf.json.JSON; JSON').name == 'net.sf.json.JSON'
     }
 
+    @Test
     void testClassifierWithConf() {
-        def coreJars = [
-                "json-lib-2.2.3-jdk15.jar",
-                "commons-lang-2.4.jar",
-                "commons-collections-3.2.jar",
-                "ezmorph-1.0.6.jar",
-                "commons-logging-1.1.1.jar",
-                "commons-beanutils-1.7.0.jar"
-            ] as Set
-        def optionalJars = [
-                "xercesImpl-2.6.2.jar",
-                "xmlParserAPIs-2.6.2.jar",
-                "groovy-all-1.5.7.jar",
-                "oro-2.0.8.jar",
-                "jruby-1.1.jar",
-                "junit-3.8.2.jar",
-                "ant-launcher-1.7.0.jar",
-                "xalan-2.7.0.jar",
-                "json-lib-2.2.3-jdk15.jar",
-                "ant-1.7.0.jar",
-                "xom-1.1.jar",
-                "jaxen-1.1-beta-8.jar",
-                "jdom-1.0.jar",
-                "jline-0.9.94.jar",
-                "log4j-1.2.14.jar",
-                "dom4j-1.6.1.jar"
-            ] as Set
+        Set coreJars = [
+            'json-lib-2.2.3-jdk15.jar',
+            'commons-beanutils-1.7.0.jar',
+            'commons-collections-3.2.jar',
+            'commons-lang-2.4.jar',
+            'commons-logging-1.1.1.jar',
+            'ezmorph-1.0.6.jar'
+        ]
+        Set optionalJars = [
+            'ant-1.7.0.jar',
+            'ant-launcher-1.7.0.jar',
+            'dom4j-1.6.1.jar',
+            'groovy-all-1.5.7.jar',
+            'jaxen-1.1-beta-8.jar',
+            'jdom-1.0.jar',
+            'jline-0.9.94.jar',
+            'jruby-1.1.jar',
+            'junit-3.8.2.jar',
+            'log4j-1.2.14.jar',
+            'oro-2.0.8.jar',
+            'xalan-2.7.0.jar',
+            'xercesImpl-2.6.2.jar',
+            'xmlParserAPIs-2.6.2.jar',
+            'xom-1.1.jar'
+        ]
 
-        GroovyClassLoader loader = new GroovyClassLoader()
-        Grape.grab(groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15', classLoader:loader, preserveFiles:true)
+        def loader = new GroovyClassLoader()
+        Grape.grab(groupId:'net.sf.json-lib', artifactId:'json-lib', version:'2.2.3', classifier:'jdk15', classLoader:loader)
         assert jarNames(loader) == coreJars
 
         loader = new GroovyClassLoader()
@@ -294,8 +308,8 @@ class GrapeIvyTest extends CompilableTestSupport {
         assert jarNames(loader) == coreJars + optionalJars
     }
 
+    @Test // BeanUtils is a transitive dependency for Digester
     void testTransitiveShorthandControl() {
-        // BeanUtils is a transitive dependency for Digester
         assertScript '''
             @Grab('commons-digester:commons-digester:2.1')
             import org.apache.commons.digester.Digester
@@ -305,29 +319,26 @@ class GrapeIvyTest extends CompilableTestSupport {
         '''
     }
 
+    @Test
     void testTransitiveShorthandExpectFailure() {
-        assertScript '''
+        shouldFail MissingPropertyException, '''
             @Grab('commons-digester:commons-digester:2.1;transitive=false')
             import org.apache.commons.digester.Digester
 
             assert Digester.name.size() == 36
-            try {
-                assert org.apache.commons.beanutils.BeanUtils.name.size() == 38
-                assert false
-            } catch(MissingPropertyException mpe) { }
+            assert org.apache.commons.beanutils.BeanUtils.name.size() == 38
         '''
     }
 
+    @Test
     void testAutoDownloadGrapeConfig() {
-
         assertScript '''
             @Grab('commons-digester:commons-digester:2.1;transitive=false')
             import org.apache.commons.digester.Digester
 
             assert Digester.name.size() == 36
         '''
-
-        assert Grape.getInstance().ivyInstance.settings.defaultResolver.name == 'downloadGrapes'
+        assert Grape.instance.ivyInstance.settings.defaultResolver.name == 'downloadGrapes'
 
         assertScript '''
             @Grab('commons-digester:commons-digester:2.1;transitive=false')
@@ -336,8 +347,7 @@ class GrapeIvyTest extends CompilableTestSupport {
 
             assert Digester.name.size() == 36
         '''
-
-        assert Grape.getInstance().ivyInstance.settings.defaultResolver.name == 'cachedGrapes'
+        assert Grape.instance.ivyInstance.settings.defaultResolver.name == 'cachedGrapes'
 
         assertScript '''
             @Grab('commons-digester:commons-digester:2.1;transitive=false')
@@ -346,21 +356,18 @@ class GrapeIvyTest extends CompilableTestSupport {
 
             assert Digester.name.size() == 36
         '''
-
-        assert Grape.getInstance().ivyInstance.settings.defaultResolver.name == 'downloadGrapes'
+        assert Grape.instance.ivyInstance.settings.defaultResolver.name == 'downloadGrapes'
     }
 
-    /**
-     * GROOVY-470: multiple jars should be loaded for an artifacts with and without a classifier
-     */
+    @Test // GROOVY-470: multiple jars should be loaded for an artifacts with and without a classifier
     void testClassifierAndNonClassifierOnSameArtifact() {
         GroovyClassLoader loader = new GroovyClassLoader()
         Grape.grab(groupId:'org.neo4j', artifactId:'neo4j-kernel', version:'2.0.0-RC1', classLoader:loader)
         Grape.grab(groupId:'org.neo4j', artifactId:'neo4j-kernel', version:'2.0.0-RC1', classifier:'tests', classLoader:loader)
 
         def jars = jarNames(loader)
-        assert jars.contains ("neo4j-kernel-2.0.0-RC1.jar")
-        assert jars.contains ("neo4j-kernel-2.0.0-RC1-tests.jar")
+        assert jars.contains('neo4j-kernel-2.0.0-RC1.jar')
+        assert jars.contains('neo4j-kernel-2.0.0-RC1-tests.jar')
 
         // also check reverse ordering of deps
         loader = new GroovyClassLoader()
@@ -368,27 +375,33 @@ class GrapeIvyTest extends CompilableTestSupport {
         Grape.grab(groupId:'org.neo4j', artifactId:'neo4j-kernel', version:'2.0.0-RC1', classLoader:loader)
 
         jars = jarNames(loader)
-        assert jars.contains ("neo4j-kernel-2.0.0-RC1.jar")
-        assert jars.contains ("neo4j-kernel-2.0.0-RC1-tests.jar")
+        assert jars.contains('neo4j-kernel-2.0.0-RC1.jar')
+        assert jars.contains('neo4j-kernel-2.0.0-RC1-tests.jar')
     }
 
-    void testSystemProperties_groovy7548() {
+    @Test // GROOVY-7548
+    void testSystemProperties() {
         System.setProperty('groovy7548prop', 'x')
         assert System.getProperty('groovy7548prop') == 'x'
-        new GroovyShell().evaluate '''
-            @GrabConfig(systemProperties='groovy7548prop=y')
-            @Grab('commons-lang:commons-lang:2.6')
-            import org.apache.commons.lang.StringUtils
-            assert StringUtils.name == 'org.apache.commons.lang.StringUtils'
-        '''
-        assert System.getProperty('groovy7548prop') == 'y'
+        try {
+            assertScript '''
+                @GrabConfig(systemProperties='groovy7548prop=y')
+                @Grab('commons-lang:commons-lang:2.6')
+                import org.apache.commons.lang.StringUtils
+
+                assert StringUtils.name == 'org.apache.commons.lang.StringUtils'
+            '''
+            assert System.getProperty('groovy7548prop') == 'y'
+        } finally {
+            System.clearProperty('groovy7548prop')
+        }
     }
 
-    // GROOVY-7649
+    @Test // GROOVY-7649
     void testResolveSucceedsAfterFailure() {
         GroovyClassLoader loader = new GroovyClassLoader()
 
-        shouldFail{
+        shouldFail {
             Grape.resolve([classLoader:loader], [], [groupId:'bogus', artifactId:'bogus', version:'0.1'])
         }
 


[groovy] 09/12: if dependency is found in local .m2 repo, don't copy jars to grape cache

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 49df75f97d04f40554fbaaf692699761d8e065cc
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Nov 7 10:16:05 2019 -0600

    if dependency is found in local .m2 repo, don't copy jars to grape cache
    
    (cherry picked from commit eaf651e18c407e8564131c3cde36060c04811b03)
---
 src/resources/groovy/grape/defaultGrapeConfig.xml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/resources/groovy/grape/defaultGrapeConfig.xml b/src/resources/groovy/grape/defaultGrapeConfig.xml
index 14a180f..4d17a40 100644
--- a/src/resources/groovy/grape/defaultGrapeConfig.xml
+++ b/src/resources/groovy/grape/defaultGrapeConfig.xml
@@ -19,6 +19,7 @@
 
 -->
 <ivysettings>
+  <caches useOrigin="true"/>
   <settings defaultResolver="downloadGrapes"/>
   <resolvers>
     <chain name="downloadGrapes" returnFirst="true">


[groovy] 07/12: GROOVY-8305: build "file:" URL for "user.home" and set as Ivy variable

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 9ce9f48aed43ffb174012b4abcdfd6fce1d89aa0
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Nov 7 08:22:34 2019 -0600

    GROOVY-8305: build "file:" URL for "user.home" and set as Ivy variable
    
    (cherry picked from commit 412edb87e78a62de9b0e4f6de09416cee0475cae)
---
 src/main/groovy/groovy/grape/GrapeIvy.groovy      | 1 +
 src/resources/groovy/grape/defaultGrapeConfig.xml | 4 ++--
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/src/main/groovy/groovy/grape/GrapeIvy.groovy b/src/main/groovy/groovy/grape/GrapeIvy.groovy
index c1c637e..64fef55 100644
--- a/src/main/groovy/groovy/grape/GrapeIvy.groovy
+++ b/src/main/groovy/groovy/grape/GrapeIvy.groovy
@@ -90,6 +90,7 @@ class GrapeIvy implements GrapeEngine {
         // start ivy
         Message.defaultLogger = new DefaultMessageLogger(System.getProperty('ivy.message.logger.level', '-1') as int)
         settings = new IvySettings()
+        settings.setVariable('user.home.url', new File(System.getProperty('user.home')).toURI().toURL() as String)
 
         // configure settings
         def grapeConfig = localGrapeConfig
diff --git a/src/resources/groovy/grape/defaultGrapeConfig.xml b/src/resources/groovy/grape/defaultGrapeConfig.xml
index 11161d3..14a180f 100644
--- a/src/resources/groovy/grape/defaultGrapeConfig.xml
+++ b/src/resources/groovy/grape/defaultGrapeConfig.xml
@@ -26,8 +26,8 @@
         <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
         <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/>
       </filesystem>
-      <ibiblio name="localm2" root="file:${user.home}/.m2/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true"/>
-      <!-- todo add 'endorsed groovy extensions' resolver here -->
+      <ibiblio name="localm2" root="${user.home.url}/.m2/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true"/>
+      <!-- TODO: add 'endorsed groovy extensions' resolver here -->
       <ibiblio name="jcenter" root="https://jcenter.bintray.com/" m2compatible="true"/>
       <ibiblio name="ibiblio" m2compatible="true"/>
     </chain>


[groovy] 02/12: ClosureUtils#hasImplicitParameter(ClosureExpression) can test for "it"

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 b53f30946446468e3270bd6c53f2de9a1b1ad4fb
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Nov 5 19:20:36 2019 -0600

    ClosureUtils#hasImplicitParameter(ClosureExpression) can test for "it"
    
    (cherry picked from commit d91f5275a34b52b71594860d23cda2526f9418d9)
---
 .../org/codehaus/groovy/ast/expr/ClosureExpression.java | 17 +++++------------
 .../org/codehaus/groovy/ast/tools/ClosureUtils.java     |  3 +--
 2 files changed, 6 insertions(+), 14 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/ast/expr/ClosureExpression.java b/src/main/java/org/codehaus/groovy/ast/expr/ClosureExpression.java
index 7df3fd1..ccdceed 100644
--- a/src/main/java/org/codehaus/groovy/ast/expr/ClosureExpression.java
+++ b/src/main/java/org/codehaus/groovy/ast/expr/ClosureExpression.java
@@ -31,17 +31,17 @@ import org.codehaus.groovy.runtime.InvokerHelper;
  * or { i {@code ->} statement } or { i, x, String y {@code ->}  statement }
  */
 public class ClosureExpression extends Expression {
-    
+
     private final Parameter[] parameters;
     private Statement code;
     private VariableScope variableScope;
-    
+
     public ClosureExpression(Parameter[] parameters, Statement code) {
         this.parameters = parameters;
         this.code = code;
         super.setType(ClassHelper.CLOSURE_TYPE.getPlainNodeReference());
     }
-    
+
     public void visit(GroovyCodeVisitor visitor) {
         visitor.visitClosureExpression(this);
     }
@@ -49,7 +49,7 @@ public class ClosureExpression extends Expression {
     public Expression transformExpression(ExpressionTransformer transformer) {
         return this;
     }
-    
+
     public String toString() {
         return super.toString() + InvokerHelper.toString(parameters) + "{ " + code + " }";
     }
@@ -82,19 +82,12 @@ public class ClosureExpression extends Expression {
     }
 
     /**
-     * @return {@code true} if implicit {@code it} is supplied
-     */
-    public boolean hasItParameter() {
-        return null != parameters && 0 == parameters.length;
-    }
-
-    /**
      * @return {@code true} if one or more explicit parameters are supplied
      */
     public boolean isParameterSpecified() {
         return parameters != null && parameters.length > 0;
     }
-    
+
     public VariableScope getVariableScope() {
         return variableScope;
     }
diff --git a/src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java
index da07990..761e8eb 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java
@@ -22,10 +22,10 @@ import groovy.lang.Closure;
 import org.codehaus.groovy.ast.Parameter;
 import org.codehaus.groovy.ast.expr.ClosureExpression;
 import org.codehaus.groovy.control.io.ReaderSource;
+
 /**
  * Handy methods when working with Closure AST data structures.
  */
-
 public class ClosureUtils {
 
     /**
@@ -80,5 +80,4 @@ public class ClosureUtils {
     public static Parameter[] getParametersSafe(ClosureExpression ce) {
         return ce.getParameters() != null ? ce.getParameters() : Parameter.EMPTY_ARRAY;
     }
-
 }


[groovy] 10/12: GROOVY-8372: pass remote (not local) conf to addDependencyArtifact

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 dddd5ff74bbaeb4d654d47fa09fc18e4f5c46904
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Nov 6 15:33:01 2019 -0600

    GROOVY-8372: pass remote (not local) conf to addDependencyArtifact
    
    add dependency artifacts only if ext, type or classifier is non-default
    
    (cherry picked from commit 16280716c22848df5ebbef799f3ec1f2b5c99322)
---
 src/main/groovy/groovy/grape/GrapeIvy.groovy | 18 ++++-----
 src/test/groovy/grape/GrapeIvyTest.groovy    | 56 +++++++++++++++++++++++++++-
 2 files changed, 64 insertions(+), 10 deletions(-)

diff --git a/src/main/groovy/groovy/grape/GrapeIvy.groovy b/src/main/groovy/groovy/grape/GrapeIvy.groovy
index 64fef55..cb1d802 100644
--- a/src/main/groovy/groovy/grape/GrapeIvy.groovy
+++ b/src/main/groovy/groovy/grape/GrapeIvy.groovy
@@ -423,23 +423,23 @@ class GrapeIvy implements GrapeEngine {
         addExcludesIfNeeded(args, md)
 
         for (IvyGrabRecord grabRecord : grabRecords) {
-            def conf = grabRecord.conf ?: ['*']
+            def confs = grabRecord.conf ?: ['*']
             DefaultDependencyDescriptor dd = (DefaultDependencyDescriptor) md.dependencies.find {
                 it.dependencyRevisionId == grabRecord.mrid
             }
             if (!dd) {
                 dd = new DefaultDependencyDescriptor(md, grabRecord.mrid, grabRecord.force, grabRecord.changing, grabRecord.transitive)
-                conf.each { dd.addDependencyConfiguration('default', it) }
+                confs.each { conf -> dd.addDependencyConfiguration('default', conf) }
                 md.addDependency(dd)
             }
 
-            // the optional configuration typically does not extend the default or master configuration, so prevent grabbing the main artifact
-            if (Collections.singleton('optional') == (conf as Set)) continue
-
-            // add artifact descriptor to dependency descriptor
-            def dad = new DefaultDependencyArtifactDescriptor(dd, grabRecord.mrid.name, grabRecord.type ?: 'jar', grabRecord.ext ?: 'jar', null, grabRecord.classifier ? [classifier: grabRecord.classifier] : null)
-            conf.each { dad.addConfiguration(it) }
-            dd.addDependencyArtifact('default', dad)
+            if (grabRecord.classifier != null
+                    || (grabRecord.ext != null && grabRecord.ext != 'jar')
+                    || (grabRecord.type != null && grabRecord.type != 'jar')) {
+                // add artifact descriptor to dependency descriptor
+                def dad = new DefaultDependencyArtifactDescriptor(dd, grabRecord.mrid.name, grabRecord.type ?: 'jar', grabRecord.ext ?: 'jar', null, grabRecord.classifier ? [classifier: grabRecord.classifier] : null)
+                confs.each { conf -> dd.addDependencyArtifact(conf, dad) }
+            }
         }
 
         // resolve grab and dependencies
diff --git a/src/test/groovy/grape/GrapeIvyTest.groovy b/src/test/groovy/grape/GrapeIvyTest.groovy
index 375d0c7..635e5b4 100644
--- a/src/test/groovy/grape/GrapeIvyTest.groovy
+++ b/src/test/groovy/grape/GrapeIvyTest.groovy
@@ -209,7 +209,7 @@ final class GrapeIvyTest {
     }
 
     @Test
-    void testConf() {
+    void testConf1() {
         Set noJars = [
         ]
         Set coreJars = [
@@ -257,6 +257,60 @@ final class GrapeIvyTest {
         assert jars == coreJars + optionalJars, 'assert that no extraneous jars are present'
     }
 
+    @Test // GROOVY-8372
+    void testConf2() {
+        def tempDir = File.createTempDir()
+        def jarsDir = new File(tempDir, 'foo/bar/jars'); jarsDir.mkdirs()
+
+        new File(jarsDir, 'bar-1.2.3.jar').createNewFile()
+        new File(jarsDir, 'baz-1.2.3.jar').createNewFile()
+
+        new File(tempDir, 'ivysettings.xml').write '''\
+            <?xml version="1.0" encoding="UTF-8"?>
+            <ivysettings>
+                <caches useOrigin="true" />
+                <resolvers>
+                    <filesystem name="downloadGrapes">
+                        <ivy pattern="${ivy.settings.dir}/[organization]/[module]/ivy-[revision].xml" />
+                        <artifact pattern="${ivy.settings.dir}/[organization]/[module]/[type]s/[artifact]-[revision].[ext]" />
+                    </filesystem>
+                </resolvers>
+            </ivysettings>
+            '''.stripIndent()
+
+        new File(tempDir, 'foo/bar/ivy-1.2.3.xml').write '''\
+            <?xml version="1.0" encoding="UTF-8"?>
+            <ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
+                <info organisation="foo" module="bar" revision="1.2.3" status="release" />
+                <configurations>
+                    <conf name="default" visibility="public" extends="master" />
+                    <conf name="master" visibility="public" />
+                    <conf name="other" visibility="public" />
+                </configurations>
+                <publications>
+                    <artifact name="bar" type="jar" ext="jar" conf="master" />
+                    <artifact name="baz" type="jar" ext="jar" conf="other" />
+                </publications>
+            </ivy-module>
+            '''.stripIndent()
+
+        System.setProperty('grape.config', tempDir.absolutePath + File.separator + 'ivysettings.xml')
+        try {
+            Grape.@instance = null
+            def loader = new GroovyClassLoader()
+            // request conf="other" which should resolve to artifact "baz-1.2.3.jar"
+            def uris = Grape.resolve(classLoader:loader, validate:false, [group:'foo', module:'bar', version:'1.2.3', conf:'other'])
+
+            def jars = uris.collect { uri -> uri.path.split('/')[-1] } as Set
+            assert 'baz-1.2.3.jar' in jars
+            assert 'bar-1.2.3.jar' !in jars
+        } finally {
+            System.clearProperty('grape.config')
+            Grape.@instance = null
+            tempDir.deleteDir()
+        }
+    }
+
     @Test
     void testClassifier() {
         def shell = new GroovyShell(new GroovyClassLoader())


[groovy] 04/12: Minor refactoring: remove unnecessary visiting (#1070)

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 3a9a57d8c91fd2d4aa77c5155c4198a655d6afe7
Author: Daniel.Sun <su...@apache.org>
AuthorDate: Wed Nov 6 20:24:11 2019 +0800

    Minor refactoring: remove unnecessary visiting (#1070)
    
    (cherry picked from commit 25a7e2c704ec45d13fa8575f196b162013d2a457)
---
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 130 ++-------------------
 1 file changed, 12 insertions(+), 118 deletions(-)

diff --git a/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java b/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
index 51fd986..c6efdec 100644
--- a/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -155,7 +155,6 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.AnonymousInnerCla
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ArgumentsContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ArrayInitializerContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.AssertStatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.AssertStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.AssignmentExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BlockContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BlockStatementContext;
@@ -163,9 +162,7 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.BlockStatementsCo
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BlockStatementsOptContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BooleanLiteralAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BreakStatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.BreakStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.BuiltInTypeContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.BuiltInTypePrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CASE;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CastExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CastParExpressionContext;
@@ -183,16 +180,13 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.ClassicalForContr
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ClassifiedModifiersContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ClosureContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ClosureOrLambdaExpressionContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ClosureOrLambdaExpressionPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CommandArgumentContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CommandExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CommandExpressionContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CompilationUnitContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ConditionalExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ConditionalStatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ConditionalStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ContinueStatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ContinueStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CreatedNameContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.CreatorContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.DEC;
@@ -219,7 +213,6 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.ExpressionContext
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ExpressionInParContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ExpressionListContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ExpressionListElementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ExpressionStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.FieldDeclarationContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.FinallyBlockContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.FloatingPointLiteralAltContext;
@@ -235,7 +228,6 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.GT;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.GroovyParserRuleContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.GstringContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.GstringPathContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.GstringPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.GstringValueContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.IN;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.INC;
@@ -253,10 +245,7 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.LT;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LabeledStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LambdaBodyContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ListContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ListPrmrAltContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.LiteralPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LocalVariableDeclarationContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.LocalVariableDeclarationStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LogicalAndExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LogicalOrExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.LoopStmtAltContext;
@@ -264,11 +253,9 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.MapContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MapEntryContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MapEntryLabelContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MapEntryListContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.MapPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MemberDeclarationContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MethodBodyContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MethodDeclarationContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.MethodDeclarationStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.MethodNameContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ModifierContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ModifiersContext;
@@ -285,10 +272,8 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.NullLiteralAltCon
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PRIVATE;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PackageDeclarationContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ParExpressionContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.ParenPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PathElementContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PathExpressionContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.PostfixExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PostfixExpressionContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PowerExprAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.PrimitiveTypeContext;
@@ -310,7 +295,6 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.ShiftExprAltConte
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.StandardLambdaExpressionContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.StandardLambdaParametersContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.StatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.StringLiteralAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.StringLiteralContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.SuperPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.SwitchBlockStatementGroupContext;
@@ -321,7 +305,6 @@ import static org.apache.groovy.parser.antlr4.GroovyLangParser.ThisFormalParamet
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ThisPrmrAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.ThrowStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.TryCatchStatementContext;
-import static org.apache.groovy.parser.antlr4.GroovyLangParser.TryCatchStmtAltContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.TypeArgumentContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.TypeArgumentsContext;
 import static org.apache.groovy.parser.antlr4.GroovyLangParser.TypeArgumentsOrDiamondContext;
@@ -599,16 +582,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public AssertStatement visitAssertStmtAlt(AssertStmtAltContext ctx) {
-        return configureAST(this.visitAssertStatement(ctx.assertStatement()), ctx);
-    }
-
-    @Override
-    public Statement visitConditionalStmtAlt(ConditionalStmtAltContext ctx) {
-        return configureAST(this.visitConditionalStatement(ctx.conditionalStatement()), ctx);
-    }
-
-    @Override
     public Statement visitConditionalStatement(ConditionalStatementContext ctx) {
         if (asBoolean(ctx.ifElseStatement())) {
             return configureAST(this.visitIfElseStatement(ctx.ifElseStatement()), ctx);
@@ -770,11 +743,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public Statement visitTryCatchStmtAlt(TryCatchStmtAltContext ctx) {
-        return configureAST(this.visitTryCatchStatement(ctx.tryCatchStatement()), ctx);
-    }
-
-    @Override
     public Statement visitTryCatchStatement(TryCatchStatementContext ctx) {
         boolean resourcesExists = asBoolean(ctx.resources());
         boolean catchExists = asBoolean(ctx.catchClause());
@@ -1024,11 +992,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public ExpressionStatement visitExpressionStmtAlt(ExpressionStmtAltContext ctx) {
-        return (ExpressionStatement) this.visit(ctx.statementExpression());
-    }
-
-    @Override
     public ReturnStatement visitReturnStmtAlt(ReturnStmtAltContext ctx) {
         return configureAST(new ReturnStatement(asBoolean(ctx.expression())
                         ? (Expression) this.visit(ctx.expression())
@@ -1066,11 +1029,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public BreakStatement visitBreakStmtAlt(BreakStmtAltContext ctx) {
-        return configureAST(this.visitBreakStatement(ctx.breakStatement()), ctx);
-    }
-
-    @Override
     public ContinueStatement visitContinueStatement(ContinueStatementContext ctx) {
         if (0 == visitingLoopStatementCnt) {
             throw createParsingFailedException("continue statement is only allowed inside loops", ctx);
@@ -1084,21 +1042,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
 
     }
 
-    @Override
-    public ContinueStatement visitContinueStmtAlt(ContinueStmtAltContext ctx) {
-        return configureAST(this.visitContinueStatement(ctx.continueStatement()), ctx);
-    }
-
-    @Override
-    public Statement visitLocalVariableDeclarationStmtAlt(LocalVariableDeclarationStmtAltContext ctx) {
-        return configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx);
-    }
-
-    @Override
-    public MethodNode visitMethodDeclarationStmtAlt(MethodDeclarationStmtAltContext ctx) {
-        return configureAST(this.visitMethodDeclaration(ctx.methodDeclaration()), ctx);
-    }
-
     // } statement    --------------------------------------------------------------------
 
     @Override
@@ -1258,18 +1201,18 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     private boolean containsDefaultMethods(ClassDeclarationContext ctx) {
         List<MethodDeclarationContext> methodDeclarationContextList =
                 (List<MethodDeclarationContext>) ctx.classBody().classBodyDeclaration().stream()
-                .map(ClassBodyDeclarationContext::memberDeclaration)
-                .filter(Objects::nonNull)
-                .map(e -> (Object) e.methodDeclaration())
-                .filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> {
-                    MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e;
-
-                    if (createModifierManager(methodDeclarationContext).containsAny(DEFAULT)) {
-                        ((List) r).add(methodDeclarationContext);
-                    }
+                        .map(ClassBodyDeclarationContext::memberDeclaration)
+                        .filter(Objects::nonNull)
+                        .map(e -> (Object) e.methodDeclaration())
+                        .filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> {
+                            MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e;
+
+                            if (createModifierManager(methodDeclarationContext).containsAny(DEFAULT)) {
+                                ((List) r).add(methodDeclarationContext);
+                            }
 
-                    return r;
-        });
+                            return r;
+                        });
 
         return !methodDeclarationContextList.isEmpty();
     }
@@ -2768,11 +2711,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public Expression visitPostfixExprAlt(PostfixExprAltContext ctx) {
-        return this.visitPostfixExpression(ctx.postfixExpression());
-    }
-
-    @Override
     public Expression visitUnaryNotExprAlt(UnaryNotExprAltContext ctx) {
         if (asBoolean(ctx.NOT())) {
             return configureAST(
@@ -3084,16 +3022,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public ConstantExpression visitLiteralPrmrAlt(LiteralPrmrAltContext ctx) {
-        return configureAST((ConstantExpression) this.visit(ctx.literal()), ctx);
-    }
-
-    @Override
-    public GStringExpression visitGstringPrmrAlt(GstringPrmrAltContext ctx) {
-        return configureAST((GStringExpression) this.visit(ctx.gstring()), ctx);
-    }
-
-    @Override
     public Expression visitNewPrmrAlt(NewPrmrAltContext ctx) {
         return configureAST(this.visitCreator(ctx.creator()), ctx);
     }
@@ -3108,34 +3036,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
         return configureAST(new VariableExpression(ctx.SUPER().getText()), ctx);
     }
 
-
-    @Override
-    public Expression visitParenPrmrAlt(ParenPrmrAltContext ctx) {
-        return configureAST(this.visitParExpression(ctx.parExpression()), ctx);
-    }
-
-    @Override
-    public ClosureExpression visitClosureOrLambdaExpressionPrmrAlt(ClosureOrLambdaExpressionPrmrAltContext ctx) {
-        return configureAST(this.visitClosureOrLambdaExpression(ctx.closureOrLambdaExpression()), ctx);
-    }
-
-    @Override
-    public ListExpression visitListPrmrAlt(ListPrmrAltContext ctx) {
-        return configureAST(
-                this.visitList(ctx.list()),
-                ctx);
-    }
-
-    @Override
-    public MapExpression visitMapPrmrAlt(MapPrmrAltContext ctx) {
-        return configureAST(this.visitMap(ctx.map()), ctx);
-    }
-
-    @Override
-    public VariableExpression visitBuiltInTypePrmrAlt(BuiltInTypePrmrAltContext ctx) {
-        return configureAST(this.visitBuiltInType(ctx.builtInType()), ctx);
-    }
-
     // } primary       --------------------------------------------------------------------
 
     @Override
@@ -3491,13 +3391,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
     }
 
     @Override
-    public ConstantExpression visitStringLiteralAlt(StringLiteralAltContext ctx) {
-        return configureAST(
-                this.visitStringLiteral(ctx.stringLiteral()),
-                ctx);
-    }
-
-    @Override
     public ConstantExpression visitBooleanLiteralAlt(BooleanLiteralAltContext ctx) {
         return configureAST(new ConstantExpression("true".equals(ctx.BooleanLiteral().getText()), true), ctx);
     }
@@ -4785,3 +4678,4 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements Groov
 
     private static final String CLASS_NAME = "_CLASS_NAME";
 }
+


[groovy] 03/12: refactor code

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 aa9af766d5a94d2d24fa50ec655e4c9d0948632d
Author: mattisonchao <ma...@gmail.com>
AuthorDate: Wed Nov 6 17:04:59 2019 +0800

    refactor code
    
    I refactor some code about new java version and some unnecessary
    objects that I leant from effective java item6.
    
    --Make progress every day!
    
    (cherry picked from commit f1a0d190dd3bc84d5760cd44d5bd051ddca3a31b)
---
 src/test/groovy/ClosureJavaIntegrationTest.java            | 12 ++++++------
 .../annotations/MyIntegerAnnoTraceASTTransformation.java   |  2 +-
 src/test/groovy/lang/GStringTest.java                      |  4 ++--
 src/test/groovy/lang/GroovyShellTest.java                  |  4 ++--
 src/test/groovy/lang/IntegerNumberRangeTest.java           |  4 ++--
 src/test/groovy/lang/IntegerObjectRangeTest.java           |  4 ++--
 src/test/groovy/util/EvalTest.java                         |  8 ++++----
 .../org/codehaus/groovy/ast/MethodCallExpressionTest.java  |  2 +-
 src/test/org/codehaus/groovy/classgen/ForTest.java         |  6 +++---
 .../classgen/asm/sc/bugs/support/Groovy7365Support.java    |  2 +-
 src/test/org/codehaus/groovy/runtime/DummyBean.java        |  2 +-
 .../org/codehaus/groovy/runtime/InvokeConstructorTest.java |  6 +++---
 .../codehaus/groovy/runtime/InvokeGroovyMethodTest.java    | 14 +++++++-------
 .../codehaus/groovy/runtime/memoize/CommonCacheTest.java   |  4 ++--
 .../groovy/runtime/memoize/ConcurrentCommonCacheTest.java  |  4 ++--
 .../groovy/runtime/memoize/StampedCommonCacheTest.java     |  4 ++--
 .../groovy/tools/rootloadersync/SubclassingInJavaTest.java |  4 ++--
 17 files changed, 43 insertions(+), 43 deletions(-)

diff --git a/src/test/groovy/ClosureJavaIntegrationTest.java b/src/test/groovy/ClosureJavaIntegrationTest.java
index 59b0f4a..a855ff0 100644
--- a/src/test/groovy/ClosureJavaIntegrationTest.java
+++ b/src/test/groovy/ClosureJavaIntegrationTest.java
@@ -48,7 +48,7 @@ import static org.codehaus.groovy.runtime.DefaultGroovyMethods.sort;
  * mind, but these tests illustrate some of the possible ways to use them from Java.
  */
 public class ClosureJavaIntegrationTest extends TestCase {
-    Map<String, Integer> zoo = new LinkedHashMap<String, Integer>();
+    Map<String, Integer> zoo = new LinkedHashMap<>();
     List<String> animals = Arrays.asList("ant", "bear", "camel");
 
     @Override
@@ -64,7 +64,7 @@ public class ClosureJavaIntegrationTest extends TestCase {
     }
 
     public void testEachList() {
-        final List<Integer> result = new ArrayList<Integer>();
+        final List<Integer> result = new ArrayList<>();
         each(animals, new Closure(null) {
             public void doCall(String arg) {
                 result.add(arg.length());
@@ -74,7 +74,7 @@ public class ClosureJavaIntegrationTest extends TestCase {
     }
 
     public void testEachMap() {
-        final List<String> result = new ArrayList<String>();
+        final List<String> result = new ArrayList<>();
         each(zoo, new Closure(null) {
             public void doCall(String k, Integer v) {
                 result.add("k=" + k + ",v=" + v);
@@ -125,7 +125,7 @@ public class ClosureJavaIntegrationTest extends TestCase {
     }
 
     public void testFindAllAndCurry() {
-        Map<String, Integer> expected = new HashMap<String, Integer>(zoo);
+        Map<String, Integer> expected = new HashMap<>(zoo);
         expected.remove("Lions");
         Closure<Boolean> keyBiggerThan = new Closure<Boolean>(null) {
             public Boolean doCall(Map.Entry<String, Integer> e, Integer size) {
@@ -137,7 +137,7 @@ public class ClosureJavaIntegrationTest extends TestCase {
     }
 
     public void testListArithmetic() {
-        List<List> numLists = new ArrayList<List>();
+        List<List> numLists = new ArrayList<>();
         numLists.add(Arrays.asList(1, 2, 3));
         numLists.add(Arrays.asList(10, 20, 30));
         assertEquals(Arrays.asList(6, 60), collect(numLists, new Closure<Integer>(null) {
@@ -180,7 +180,7 @@ public class ClosureJavaIntegrationTest extends TestCase {
     }
 
     public void testTrampoline() {
-        final Reference<Closure<BigInteger>> ref = new Reference<Closure<BigInteger>>();
+        final Reference<Closure<BigInteger>> ref = new Reference<>();
         ref.set(new Closure<BigInteger>(null) {
             public Object doCall(Integer n, BigInteger total) {
                 return n > 1 ? ref.get().trampoline(n - 1, total.multiply(BigInteger.valueOf(n))) : total;
diff --git a/src/test/groovy/annotations/MyIntegerAnnoTraceASTTransformation.java b/src/test/groovy/annotations/MyIntegerAnnoTraceASTTransformation.java
index 3e4996e..aa22376 100644
--- a/src/test/groovy/annotations/MyIntegerAnnoTraceASTTransformation.java
+++ b/src/test/groovy/annotations/MyIntegerAnnoTraceASTTransformation.java
@@ -38,7 +38,7 @@ import java.util.List;
  */
 @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
 public class MyIntegerAnnoTraceASTTransformation implements ASTTransformation {
-    public static List<String> trace = new ArrayList<String>();
+    public static List<String> trace = new ArrayList<>();
 
     public void visit(ASTNode[] nodes, final SourceUnit source) {
         if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
diff --git a/src/test/groovy/lang/GStringTest.java b/src/test/groovy/lang/GStringTest.java
index 1891bf0..7ef901f 100644
--- a/src/test/groovy/lang/GStringTest.java
+++ b/src/test/groovy/lang/GStringTest.java
@@ -64,8 +64,8 @@ public class GStringTest extends GroovyTestCase {
     }
 
     public void testEqualsAndHashCode() {
-        DummyGString a = new DummyGString(new Object[]{new Integer(1)});
-        DummyGString b = new DummyGString(new Object[]{new Long(1)});
+        DummyGString a = new DummyGString(new Object[]{Integer.valueOf(1)});
+        DummyGString b = new DummyGString(new Object[]{Long.valueOf(1)});
         Comparable c = new DummyGString(new Object[]{new Double(2.3)});
 
         assertTrue("a == b", a.equals(b));
diff --git a/src/test/groovy/lang/GroovyShellTest.java b/src/test/groovy/lang/GroovyShellTest.java
index 65c77ff..d11738e 100644
--- a/src/test/groovy/lang/GroovyShellTest.java
+++ b/src/test/groovy/lang/GroovyShellTest.java
@@ -48,7 +48,7 @@ public class GroovyShellTest extends GroovyTestCase {
         GroovyShell shell = new GroovyShell();
         try {
             Object result = shell.evaluate(script1, "Test.groovy");
-            assertEquals(new Integer(1), result);
+            assertEquals(Integer.valueOf(1), result);
         }
         catch (Exception e) {
             fail(e.toString());
@@ -75,7 +75,7 @@ public class GroovyShellTest extends GroovyTestCase {
         GroovyShell shell = new GroovyShell(context);
         try {
             Object result = shell.evaluate(script2, "Test.groovy");
-            assertEquals(new Integer(2), result);
+            assertEquals(Integer.valueOf(2), result);
         }
         catch (Exception e) {
             fail(e.toString());
diff --git a/src/test/groovy/lang/IntegerNumberRangeTest.java b/src/test/groovy/lang/IntegerNumberRangeTest.java
index a2231bb..0b90797 100644
--- a/src/test/groovy/lang/IntegerNumberRangeTest.java
+++ b/src/test/groovy/lang/IntegerNumberRangeTest.java
@@ -28,7 +28,7 @@ public class IntegerNumberRangeTest extends NumberRangeTestCase {
      */
     @Override
     protected Range createRange(int from, int to) {
-        return new NumberRange(new Integer(from), new Integer(to));
+        return new NumberRange(Integer.valueOf(from), Integer.valueOf(to));
     }
 
     /**
@@ -36,7 +36,7 @@ public class IntegerNumberRangeTest extends NumberRangeTestCase {
      */
     @Override
     protected Comparable createValue(int value) {
-        return new Integer(value);
+        return Integer.valueOf(value);
     }
 
 }
diff --git a/src/test/groovy/lang/IntegerObjectRangeTest.java b/src/test/groovy/lang/IntegerObjectRangeTest.java
index 8bab654..9caf617 100644
--- a/src/test/groovy/lang/IntegerObjectRangeTest.java
+++ b/src/test/groovy/lang/IntegerObjectRangeTest.java
@@ -28,7 +28,7 @@ public class IntegerObjectRangeTest extends NumberRangeTestCase {
      */
     @Override
     protected Range createRange(int from, int to) {
-        return new ObjectRange(new Integer(from), new Integer(to));
+        return new ObjectRange(Integer.valueOf(from), Integer.valueOf(to));
     }
 
     /**
@@ -36,7 +36,7 @@ public class IntegerObjectRangeTest extends NumberRangeTestCase {
      */
     @Override
     protected Comparable createValue(int value) {
-        return new Integer(value);
+        return Integer.valueOf(value);
     }
 
 }
diff --git a/src/test/groovy/util/EvalTest.java b/src/test/groovy/util/EvalTest.java
index fb057b3..feb89a1 100644
--- a/src/test/groovy/util/EvalTest.java
+++ b/src/test/groovy/util/EvalTest.java
@@ -31,23 +31,23 @@ public class EvalTest extends TestCase {
     }
 
     public void testMeWithSymbolAndObject() throws CompilationFailedException {
-        Object result = Eval.me("x", new Integer(10), "x");
+        Object result = Eval.me("x", Integer.valueOf(10), "x");
         assertEquals("10", result.toString());
     }
 
     public void testX() throws CompilationFailedException {
-        Object result = Eval.x(new Integer(10), "x");
+        Object result = Eval.x(Integer.valueOf(10), "x");
         assertEquals("10", result.toString());
     }
 
     public void testXY() throws CompilationFailedException {
-        Integer ten = new Integer(10);
+        Integer ten = Integer.valueOf(10);
         Object result = Eval.xy(ten, ten, "x+y");
         assertEquals("20", result.toString());
     }
 
     public void testXYZ() throws CompilationFailedException {
-        Integer ten = new Integer(10);
+        Integer ten = Integer.valueOf(10);
         Object result = Eval.xyz(ten, ten, ten, "x+y+z");
         assertEquals("30", result.toString());
     }
diff --git a/src/test/org/codehaus/groovy/ast/MethodCallExpressionTest.java b/src/test/org/codehaus/groovy/ast/MethodCallExpressionTest.java
index cbd6bab..3d221a7 100644
--- a/src/test/org/codehaus/groovy/ast/MethodCallExpressionTest.java
+++ b/src/test/org/codehaus/groovy/ast/MethodCallExpressionTest.java
@@ -38,7 +38,7 @@ public class MethodCallExpressionTest extends ASTTest {
      */
     private boolean visited;
 
-    private List<String> defaultScriptMethods = new ArrayList<String>();
+    private List<String> defaultScriptMethods = new ArrayList<>();
 
     private ClassCodeVisitorSupport methodCallVisitor = new ClassCodeVisitorSupport() {
 
diff --git a/src/test/org/codehaus/groovy/classgen/ForTest.java b/src/test/org/codehaus/groovy/classgen/ForTest.java
index 165d1a3..c37dbdf 100644
--- a/src/test/org/codehaus/groovy/classgen/ForTest.java
+++ b/src/test/org/codehaus/groovy/classgen/ForTest.java
@@ -44,7 +44,7 @@ public class ForTest extends TestSupport {
         assertTrue("Managed to create bean", bean != null);
 
         System.out.println("################ Now about to invoke a method without looping");
-        Object value = new Integer(10000);
+        Object value = Integer.valueOf(10000);
 
         try {
             InvokerHelper.invokeMethod(bean, "oneParamDemo", new Object[]{value});
@@ -75,7 +75,7 @@ public class ForTest extends TestSupport {
         assertTrue("Managed to create bean", bean != null);
 
         System.out.println("################ Now about to invoke a method with looping");
-        Object[] array = {new Integer(1234), "abc", "def"};
+        Object[] array = {Integer.valueOf(1234), "abc", "def"};
 
         try {
             InvokerHelper.invokeMethod(bean, "iterateDemo", new Object[]{array});
@@ -107,7 +107,7 @@ public class ForTest extends TestSupport {
         assertTrue("Managed to create bean", bean != null);
 
         System.out.println("################ Now about to invoke a method with many parameters");
-        Object[] array = {new Integer(1000 * 1000), "foo-", "bar~"};
+        Object[] array = {Integer.valueOf(1000 * 1000), "foo-", "bar~"};
 
         try {
             InvokerHelper.invokeMethod(bean, "manyParamDemo", array);
diff --git a/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/support/Groovy7365Support.java b/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/support/Groovy7365Support.java
index d7b2437..4d73b8c 100644
--- a/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/support/Groovy7365Support.java
+++ b/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/support/Groovy7365Support.java
@@ -23,6 +23,6 @@ import java.util.Set;
 
 public class Groovy7365Support<A, B> {
     public Set<String> getStrings() {
-        return new LinkedHashSet<String>();
+        return new LinkedHashSet<>();
     }
 }
diff --git a/src/test/org/codehaus/groovy/runtime/DummyBean.java b/src/test/org/codehaus/groovy/runtime/DummyBean.java
index 80a72f8..32c4219 100644
--- a/src/test/org/codehaus/groovy/runtime/DummyBean.java
+++ b/src/test/org/codehaus/groovy/runtime/DummyBean.java
@@ -29,7 +29,7 @@ import java.util.Map;
  */
 public class DummyBean {
     private String name = "James";
-    private Integer i = new Integer(123);
+    private Integer i = Integer.valueOf(123);
     private Map dynamicProperties = new HashMap();
     private Point point;
     private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
diff --git a/src/test/org/codehaus/groovy/runtime/InvokeConstructorTest.java b/src/test/org/codehaus/groovy/runtime/InvokeConstructorTest.java
index 716d7c3..fda5c3c 100644
--- a/src/test/org/codehaus/groovy/runtime/InvokeConstructorTest.java
+++ b/src/test/org/codehaus/groovy/runtime/InvokeConstructorTest.java
@@ -35,17 +35,17 @@ public class InvokeConstructorTest extends GroovyTestCase {
     }
 
     public void testInvokeConstructorOneParamWhichIsNull() throws Throwable {
-        assertConstructor(new DummyBean("Bob", new Integer(1707)), new Object[]{"Bob", new Integer(1707)});
+        assertConstructor(new DummyBean("Bob", Integer.valueOf(1707)), new Object[]{"Bob", Integer.valueOf(1707)});
     }
 
     public void testConstructorWithGStringCoercion() throws Throwable {
-        GString gstring = new GString(new Object[]{new Integer(123)}) {
+        GString gstring = new GString(new Object[]{Integer.valueOf(123)}) {
             public String[] getStrings() {
                 return new String[]{""};
             }
         };
 
-        Object expected = new Long(gstring.toString());
+        Object expected = Long.valueOf(gstring.toString());
 
         assertConstructor(expected, new Object[]{gstring});
     }
diff --git a/src/test/org/codehaus/groovy/runtime/InvokeGroovyMethodTest.java b/src/test/org/codehaus/groovy/runtime/InvokeGroovyMethodTest.java
index 2f865aa..e022078 100644
--- a/src/test/org/codehaus/groovy/runtime/InvokeGroovyMethodTest.java
+++ b/src/test/org/codehaus/groovy/runtime/InvokeGroovyMethodTest.java
@@ -53,19 +53,19 @@ public class InvokeGroovyMethodTest extends GroovyTestCase {
     }
 
     public void testMatchesWithObject() throws Throwable {
-        assertMatches(new Integer(1), new Integer(1), true);
-        assertMatches(new Integer(1), new Integer(2), false);
+        assertMatches(Integer.valueOf(1), Integer.valueOf(1), true);
+        assertMatches(Integer.valueOf(1), Integer.valueOf(2), false);
     }
 
     public void testMatchesWithClass() throws Throwable {
-        assertMatches(new Integer(1), Integer.class, true);
-        assertMatches(new Integer(1), Number.class, true);
-        assertMatches(new Integer(1), Double.class, false);
+        assertMatches(Integer.valueOf(1), Integer.class, true);
+        assertMatches(Integer.valueOf(1), Number.class, true);
+        assertMatches(Integer.valueOf(1), Double.class, false);
     }
 
     public void testMatchesWithList() throws Throwable {
-        assertMatches(new Integer(1), Arrays.asList(new Object[]{new Integer(2), new Integer(1)}), true);
-        assertMatches(new Integer(1), Arrays.asList(new Object[]{new Integer(2), new Integer(3)}), false);
+        assertMatches(Integer.valueOf(1), Arrays.asList(new Object[]{Integer.valueOf(2), Integer.valueOf(1)}), true);
+        assertMatches(Integer.valueOf(1), Arrays.asList(new Object[]{Integer.valueOf(2), Integer.valueOf(3)}), false);
     }
 
     // Implementation methods
diff --git a/src/test/org/codehaus/groovy/runtime/memoize/CommonCacheTest.java b/src/test/org/codehaus/groovy/runtime/memoize/CommonCacheTest.java
index b7ed91a..2223e54 100644
--- a/src/test/org/codehaus/groovy/runtime/memoize/CommonCacheTest.java
+++ b/src/test/org/codehaus/groovy/runtime/memoize/CommonCacheTest.java
@@ -171,7 +171,7 @@ public class CommonCacheTest {
 
     @Test
     public void testLruCache() {
-        CommonCache<String, String> sc = new CommonCache<String, String>(3);
+        CommonCache<String, String> sc = new CommonCache<>(3);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
@@ -185,7 +185,7 @@ public class CommonCacheTest {
 
     @Test
     public void testFifoCache() {
-        CommonCache<String, String> sc = new CommonCache<String, String>(3, 3, EvictableCache.EvictionStrategy.FIFO);
+        CommonCache<String, String> sc = new CommonCache<>(3, 3, EvictableCache.EvictionStrategy.FIFO);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
diff --git a/src/test/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCacheTest.java b/src/test/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCacheTest.java
index 97ecadc..efbb054 100644
--- a/src/test/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCacheTest.java
+++ b/src/test/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCacheTest.java
@@ -172,7 +172,7 @@ public class ConcurrentCommonCacheTest {
 
     @Test
     public void testLruCache() {
-        ConcurrentCommonCache<String, String> sc = new ConcurrentCommonCache<String, String>(3);
+        ConcurrentCommonCache<String, String> sc = new ConcurrentCommonCache<>(3);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
@@ -186,7 +186,7 @@ public class ConcurrentCommonCacheTest {
 
     @Test
     public void testFifoCache() {
-        ConcurrentCommonCache<String, String> sc = new ConcurrentCommonCache<String, String>(3, 3, EvictableCache.EvictionStrategy.FIFO);
+        ConcurrentCommonCache<String, String> sc = new ConcurrentCommonCache<>(3, 3, EvictableCache.EvictionStrategy.FIFO);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
diff --git a/src/test/org/codehaus/groovy/runtime/memoize/StampedCommonCacheTest.java b/src/test/org/codehaus/groovy/runtime/memoize/StampedCommonCacheTest.java
index 072492f..2fc6ff6 100644
--- a/src/test/org/codehaus/groovy/runtime/memoize/StampedCommonCacheTest.java
+++ b/src/test/org/codehaus/groovy/runtime/memoize/StampedCommonCacheTest.java
@@ -172,7 +172,7 @@ public class StampedCommonCacheTest {
 
     @Test
     public void testLruCache() {
-        StampedCommonCache<String, String> sc = new StampedCommonCache<String, String>(3);
+        StampedCommonCache<String, String> sc = new StampedCommonCache<>(3);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
@@ -186,7 +186,7 @@ public class StampedCommonCacheTest {
 
     @Test
     public void testFifoCache() {
-        StampedCommonCache<String, String> sc = new StampedCommonCache<String, String>(3, 3, EvictableCache.EvictionStrategy.FIFO);
+        StampedCommonCache<String, String> sc = new StampedCommonCache<>(3, 3, EvictableCache.EvictionStrategy.FIFO);
         sc.put("a", "1");
         sc.put("b", "2");
         sc.put("c", "3");
diff --git a/src/test/org/codehaus/groovy/tools/rootloadersync/SubclassingInJavaTest.java b/src/test/org/codehaus/groovy/tools/rootloadersync/SubclassingInJavaTest.java
index 0001c7e..3276c60 100644
--- a/src/test/org/codehaus/groovy/tools/rootloadersync/SubclassingInJavaTest.java
+++ b/src/test/org/codehaus/groovy/tools/rootloadersync/SubclassingInJavaTest.java
@@ -34,8 +34,8 @@ public class SubclassingInJavaTest {
 
    @Test
    public void testGenericSubclassWithBafflingSymptom() {
-      OtherConcreteGenericJavaSubclass unrelatedInstance = new OtherConcreteGenericJavaSubclass(new HashSet<String>());
-      ConcreteGenericJavaSubclass instance = new ConcreteGenericJavaSubclass(new HashSet<String>());
+      OtherConcreteGenericJavaSubclass unrelatedInstance = new OtherConcreteGenericJavaSubclass(new HashSet<>());
+      ConcreteGenericJavaSubclass instance = new ConcreteGenericJavaSubclass(new HashSet<>());
       instance.addNote("abcd");
    }
 }


[groovy] 12/12: GROOVY-7996: check for get(String)/set(String, Object) or propertyMissing

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 94bc65cb81d0bd613aaf1700c2a75f6be8c9b4da
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Nov 5 18:56:17 2019 -0600

    GROOVY-7996: check for get(String)/set(String,Object) or propertyMissing
    
    (cherry picked from commit 8b0e5b7bc9aa7af2c08faee5dad482899a6a0265)
---
 .../transform/stc/StaticTypeCheckingVisitor.java      | 19 +++++++++++++++++++
 src/test/groovy/bugs/Groovy7996.groovy                | 14 +++++++++-----
 2 files changed, 28 insertions(+), 5 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index b8d7a8c..ae8bee4 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1694,6 +1694,25 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
                     }
                 }
             }
+
+            // GROOVY-7996: check if receiver implements get(String)/set(String,Object) or propertyMissing(String)
+            if (!testClass.isArray() && !isPrimitiveType(getUnwrapper(testClass))
+                    && pexp.isImplicitThis() && typeCheckingContext.getEnclosingClosure() != null) {
+                MethodNode mopMethod;
+                if (readMode) {
+                    mopMethod = testClass.getMethod("get", new Parameter[]{new Parameter(STRING_TYPE, "name")});
+                } else {
+                    mopMethod = testClass.getMethod("set", new Parameter[]{new Parameter(STRING_TYPE, "name"), new Parameter(OBJECT_TYPE, "value")});
+                }
+                if (mopMethod == null) mopMethod = testClass.getMethod("propertyMissing", new Parameter[]{new Parameter(STRING_TYPE, "propertyName")});
+
+                if (mopMethod != null) {
+                    pexp.putNodeMetaData(DYNAMIC_RESOLUTION, Boolean.TRUE);
+                    pexp.removeNodeMetaData(DECLARATION_INFERRED_TYPE);
+                    pexp.removeNodeMetaData(INFERRED_TYPE);
+                    return true;
+                }
+            }
         }
 
         for (Receiver<String> receiver : receivers) {
diff --git a/src/test/groovy/bugs/Groovy7996.groovy b/src/test/groovy/bugs/Groovy7996.groovy
index fc0872f..39de261 100644
--- a/src/test/groovy/bugs/Groovy7996.groovy
+++ b/src/test/groovy/bugs/Groovy7996.groovy
@@ -18,16 +18,18 @@
  */
 package groovy.bugs
 
-import groovy.test.NotYetImplemented
+import groovy.transform.CompileStatic
 import org.junit.Test
 
 import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
 
+@CompileStatic
 final class Groovy7996 {
 
-    @Test @NotYetImplemented
+    @Test
     void testFieldAccessFromClosure1() {
-        assertScript '''
+        def err = shouldFail '''
             class Foo {
                 def build(@DelegatesTo(value=Foo, strategy=Closure.DELEGATE_FIRST) Closure block) {
                     this.with(block)
@@ -45,13 +47,15 @@ final class Groovy7996 {
                 boolean doStuff() {
                     Foo foo = new Foo()
                     foo.build {
-                        bar.isEmpty() // "ClassCastException: java.lang.String cannot be cast to java.util.List"
+                        bar.isEmpty() // ClassCastException: java.lang.String cannot be cast to java.util.List
                     }
                 }
             }
 
-            assert new Bar().doStuff()
+            new Bar().doStuff()
         '''
+
+        assert err =~ /Cannot find matching method java.lang.Object#isEmpty\(\)/
     }
 
     @Test


[groovy] 01/12: GROOVY-8721, GROOVY-9015: Avoid calling ClassNode#getTypeClass()

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 b307c5f8b3dac4988ca14ace7752349f47d8700b
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Nov 5 14:09:31 2019 -0600

    GROOVY-8721, GROOVY-9015: Avoid calling ClassNode#getTypeClass()
    
    GROOVY-4146
    
    (cherry picked from commit 8c66dec035ffc3fb40a1322e6e1b902e217f3d1d)
---
 .../classgen/InnerClassCompletionVisitor.java      |   4 +-
 .../groovy/classgen/asm/BytecodeHelper.java        | 153 ++++++++++-----------
 .../groovy/runtime/callsite/CallSiteGenerator.java |  44 +++---
 3 files changed, 98 insertions(+), 103 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java b/src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java
index 1e52435..4b8a1a2 100644
--- a/src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java
@@ -168,12 +168,12 @@ public class InnerClassCompletionVisitor extends InnerClassVisitorHelper impleme
             mv.visitFieldInsn(GETFIELD, classInternalName, "this$0", outerClassDescriptor);
         }
     }
-    
+
     private void addDefaultMethods(InnerClassNode node) {
         final boolean isStatic = isStatic(node);
 
         ClassNode outerClass = node.getOuterClass();
-        final String classInternalName = org.codehaus.groovy.classgen.asm.BytecodeHelper.getClassInternalName(node);
+        final String classInternalName = BytecodeHelper.getClassInternalName(node);
         final String outerClassInternalName = getInternalName(outerClass, isStatic);
         final String outerClassDescriptor = getTypeDescriptor(outerClass, isStatic);
         final int objectDistance = getObjectDistance(outerClass);
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java
index 7491ca8..58323b5 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java
@@ -24,7 +24,6 @@ import org.codehaus.groovy.ast.CompileUnit;
 import org.codehaus.groovy.ast.GenericsType;
 import org.codehaus.groovy.ast.MethodNode;
 import org.codehaus.groovy.ast.Parameter;
-import org.codehaus.groovy.ast.decompiled.DecompiledClassNode;
 import org.codehaus.groovy.classgen.asm.util.TypeUtil;
 import org.codehaus.groovy.reflection.ReflectionCache;
 import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
@@ -48,17 +47,22 @@ import static org.codehaus.groovy.ast.ClassHelper.short_TYPE;
  * A helper class for bytecode generation with AsmClassGenerator.
  */
 public class BytecodeHelper implements Opcodes {
-    
-    private static String DTT_CLASSNAME = BytecodeHelper.getClassInternalName(DefaultTypeTransformation.class.getName());
 
+    private static String DTT_CLASSNAME = BytecodeHelper.getClassInternalName(DefaultTypeTransformation.class);
+
+    /**
+     * @return the ASM internal name of the type
+     */
     public static String getClassInternalName(ClassNode t) {
-        if (t.isPrimaryClassNode() || t instanceof DecompiledClassNode) {
-            if (t.isArray()) return "[L"+getClassInternalName(t.getComponentType())+";";
-            return getClassInternalName(t.getName());
+        if (t.isArray()) {
+            return TypeUtil.getDescriptionByType(t);
         }
-        return getClassInternalName(t.getTypeClass());
+        return getClassInternalName(t.getName());
     }
 
+    /**
+     * @return the ASM internal name of the type
+     */
     public static String getClassInternalName(Class t) {
         return org.objectweb.asm.Type.getInternalName(t);
     }
@@ -70,55 +74,56 @@ public class BytecodeHelper implements Opcodes {
         return name.replace('.', '/');
     }
 
+    /**
+     * Returns a method descriptor for the given {@link org.codehaus.groovy.ast.MethodNode}.
+     *
+     * @param methodNode the method node for which to create the descriptor
+     * @return a method descriptor as defined in section JVMS section 4.3.3
+     */
+    public static String getMethodDescriptor(MethodNode methodNode) {
+        return getMethodDescriptor(methodNode.getReturnType(), methodNode.getParameters());
+    }
+
+    /**
+     * @return the ASM method type descriptor
+     */
     public static String getMethodDescriptor(ClassNode returnType, Parameter[] parameters) {
         ClassNode[] parameterTypes = new ClassNode[parameters.length];
-        for (int i = 0; i < parameters.length; i++) {
+        for (int i = 0, n = parameters.length; i < n; i += 1) {
             parameterTypes[i] = parameters[i].getType();
         }
-
         return getMethodDescriptor(returnType, parameterTypes);
     }
 
+    /**
+     * @return the ASM method type descriptor
+     */
     public static String getMethodDescriptor(ClassNode returnType, ClassNode[] parameterTypes) {
         StringBuilder buffer = new StringBuilder(100);
-        buffer.append("(");
+        buffer.append('(');
         for (ClassNode parameterType : parameterTypes) {
             buffer.append(getTypeDescription(parameterType));
         }
-        buffer.append(")");
+        buffer.append(')');
         buffer.append(getTypeDescription(returnType));
         return buffer.toString();
     }
 
     /**
-     * Returns a method descriptor for the given {@link org.codehaus.groovy.ast.MethodNode}.
-     *
-     * @param methodNode the method node for which to create the descriptor
-     * @return a method descriptor as defined in section JVMS section 4.3.3
-     */
-    public static String getMethodDescriptor(MethodNode methodNode) {
-        return getMethodDescriptor(methodNode.getReturnType(), methodNode.getParameters());
-    }
-    
-    /**
      * @return the ASM method type descriptor
      */
     public static String getMethodDescriptor(Class returnType, Class[] paramTypes) {
         // lets avoid class loading
         StringBuilder buffer = new StringBuilder(100);
-        buffer.append("(");
+        buffer.append('(');
         for (Class paramType : paramTypes) {
             buffer.append(getTypeDescription(paramType));
         }
-        buffer.append(")");
+        buffer.append(')');
         buffer.append(getTypeDescription(returnType));
         return buffer.toString();
     }
 
-    public static String getTypeDescription(Class c) {
-        return org.objectweb.asm.Type.getDescriptor(c);
-    }
-
     /**
      * array types are special:
      * eg.: String[]: classname: [Ljava.lang.String;
@@ -132,16 +137,18 @@ public class BytecodeHelper implements Opcodes {
      */
     public static String getClassLoadingTypeDescription(ClassNode c) {
         String desc = TypeUtil.getDescriptionByType(c);
-
         if (!c.isArray()) {
             if (desc.startsWith("L") && desc.endsWith(";")) {
                 desc = desc.substring(1, desc.length() - 1); // remove "L" and ";"
             }
         }
-
         return desc.replace('/', '.');
     }
 
+    public static String getTypeDescription(Class c) {
+        return org.objectweb.asm.Type.getDescriptor(c);
+    }
+
     /**
      * array types are special:
      * eg.: String[]: classname: [Ljava/lang/String;
@@ -165,24 +172,20 @@ public class BytecodeHelper implements Opcodes {
         if (ClassHelper.isPrimitiveType(d.redirect())) {
             d = d.redirect();
         }
-
         String desc = TypeUtil.getDescriptionByType(d);
-
         if (!end && desc.endsWith(";")) {
             desc = desc.substring(0, desc.length() - 1);
         }
-
         return desc;
     }
 
-
     /**
      * @return an array of ASM internal names of the type
      */
     public static String[] getClassInternalNames(ClassNode[] names) {
         int size = names.length;
         String[] answer = new String[size];
-        for (int i = 0; i < size; i++) {
+        for (int i = 0; i < size; i += 1) {
             answer[i] = getClassInternalName(names[i]);
         }
         return answer;
@@ -218,7 +221,7 @@ public class BytecodeHelper implements Opcodes {
                 }
         }
     }
-    
+
     /**
      * Negate a boolean on stack.
      */
@@ -235,16 +238,6 @@ public class BytecodeHelper implements Opcodes {
     }
 
     /**
-     * load a message on the stack and remove it right away. Good for put a mark in the generated bytecode for debugging purpose.
-     *
-     * @param msg
-     */
-    /*public void mark(String msg) {
-        mv.visitLdcInsn(msg);
-        mv.visitInsn(POP);
-    }*/
-
-    /**
      * returns a name that Class.forName() can take. Notably for arrays:
      * [I, [Ljava.lang.String; etc
      * Regular object type:  java.lang.String
@@ -281,10 +274,6 @@ public class BytecodeHelper implements Opcodes {
         return name.replace('/', '.');
     }
 
-    /*public void dup() {
-        mv.visitInsn(DUP);
-    }*/
-
     private static boolean hasGenerics(Parameter[] param) {
         if (param.length == 0) return false;
         for (Parameter parameter : param) {
@@ -333,7 +322,6 @@ public class BytecodeHelper implements Opcodes {
                 if (anInterface.isUsingGenerics()) return true;
             }
         }
-
         return false;
     }
 
@@ -374,7 +362,6 @@ public class BytecodeHelper implements Opcodes {
             GenericsType gt = new GenericsType(type);
             writeGenericsBounds(ret, gt, false);
         }
-
         return ret.toString();
     }
 
@@ -443,8 +430,8 @@ public class BytecodeHelper implements Opcodes {
         } else {
             mv.visitTypeInsn(
                     CHECKCAST,
-                    type.isArray() ? 
-                            BytecodeHelper.getTypeDescription(type) : 
+                    type.isArray() ?
+                            BytecodeHelper.getTypeDescription(type) :
                             BytecodeHelper.getClassInternalName(type.getName()));
         }
     }
@@ -480,50 +467,62 @@ public class BytecodeHelper implements Opcodes {
         } else {
             mv.visitTypeInsn(
                     CHECKCAST,
-                    type.isArray() ? 
-                            BytecodeHelper.getTypeDescription(type) : 
+                    type.isArray() ?
+                            BytecodeHelper.getTypeDescription(type) :
                                 BytecodeHelper.getClassInternalName(type.getName()));
         }
     }
 
     /**
-     * Generates the bytecode to unbox the current value on the stack
-     */
-    public static void unbox(MethodVisitor mv, Class type) {
-        if (type.isPrimitive() && type != Void.TYPE) {
-            String returnString = "(Ljava/lang/Object;)" + BytecodeHelper.getTypeDescription(type);
-            mv.visitMethodInsn(INVOKESTATIC, DTT_CLASSNAME, type.getName() + "Unbox", returnString, false);
-        }
-    }
-
-    public static void unbox(MethodVisitor mv, ClassNode type) {
-        if (type.isPrimaryClassNode()) return;
-        unbox(mv, type.getTypeClass());
-    }
-
-    /**
-     * box top level operand
+     * Generates the bytecode to autobox the current value on the stack.
      */
     @Deprecated
     public static boolean box(MethodVisitor mv, ClassNode type) {
-        if (type.isPrimaryClassNode()) return false;
-        return box(mv, type.getTypeClass());
+        if (ClassHelper.isPrimitiveType(type) && !"void".equalsIgnoreCase(type.getName())) {
+            box(mv, BytecodeHelper.getTypeDescription(type));
+            return true;
+        }
+        return false;
     }
 
-    
     /**
-     * Generates the bytecode to autobox the current value on the stack
+     * Generates the bytecode to autobox the current value on the stack.
      */
     @Deprecated
     public static boolean box(MethodVisitor mv, Class type) {
         if (ReflectionCache.getCachedClass(type).isPrimitive && type != void.class) {
-            String returnString = "(" + BytecodeHelper.getTypeDescription(type) + ")Ljava/lang/Object;";
-            mv.visitMethodInsn(INVOKESTATIC, DTT_CLASSNAME, "box", returnString, false);
+            box(mv, BytecodeHelper.getTypeDescription(type));
             return true;
         }
         return false;
     }
 
+    private static void box(MethodVisitor mv, String typeDescription) {
+        mv.visitMethodInsn(INVOKESTATIC, DTT_CLASSNAME, "box", "(" + typeDescription + ")Ljava/lang/Object;", false);
+    }
+
+    /**
+     * Generates the bytecode to unbox the current value on the stack.
+     */
+    public static void unbox(MethodVisitor mv, ClassNode type) {
+        if (ClassHelper.isPrimitiveType(type) && !"void".equalsIgnoreCase(type.getName())) {
+            unbox(mv, type.getName(), BytecodeHelper.getTypeDescription(type));
+        }
+    }
+
+    /**
+     * Generates the bytecode to unbox the current value on the stack.
+     */
+    public static void unbox(MethodVisitor mv, Class type) {
+        if (type.isPrimitive() && type != Void.TYPE) {
+            unbox(mv, type.getName(), BytecodeHelper.getTypeDescription(type));
+        }
+    }
+
+    private static void unbox(MethodVisitor mv, String typeName, String typeDescription) {
+        mv.visitMethodInsn(INVOKESTATIC, DTT_CLASSNAME, typeName + "Unbox", "(Ljava/lang/Object;)" + typeDescription, false);
+    }
+
     /**
      * Visits a class literal. If the type of the classnode is a primitive type,
      * the generated bytecode will be a GETSTATIC Integer.TYPE.
diff --git a/src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.java b/src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.java
index 1267cfe..b9cbbf7 100644
--- a/src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.java
+++ b/src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteGenerator.java
@@ -18,8 +18,6 @@
  */
 package org.codehaus.groovy.runtime.callsite;
 
-import groovy.lang.GroovyRuntimeException;
-import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.classgen.GeneratorContext;
 import org.codehaus.groovy.classgen.asm.BytecodeHelper;
 import org.codehaus.groovy.reflection.CachedClass;
@@ -36,23 +34,22 @@ import java.lang.reflect.Modifier;
 
 public class CallSiteGenerator {
 
-    private static final String GRE = BytecodeHelper.getClassInternalName(ClassHelper.make(GroovyRuntimeException.class));
-    
-    private CallSiteGenerator () {}
-    
+    private CallSiteGenerator() {
+    }
+
     private static MethodVisitor writeMethod(ClassWriter cw, String name, int argumentCount, final String superClass, CachedMethod cachedMethod, String receiverType, String parameterDescription, boolean useArray) {
         MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "call" + name, "(L" + receiverType + ";" + parameterDescription + ")Ljava/lang/Object;", null, null);
         mv.visitCode();
-        
+
         final Label tryStart = new Label();
         mv.visitLabel(tryStart);
-        
+
         // call for checking if method is still valid
         for (int i = 0; i < argumentCount; ++i) mv.visitVarInsn(Opcodes.ALOAD, i);
         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, superClass, "checkCall", "(Ljava/lang/Object;" + parameterDescription + ")Z", false);
         Label l0 = new Label();
         mv.visitJumpInsn(Opcodes.IFEQ, l0);
-        
+
         // valid method branch
 
         Class callClass = cachedMethod.getDeclaringClass().getTheClass();
@@ -60,7 +57,7 @@ public class CallSiteGenerator {
 
         String type = BytecodeHelper.getClassInternalName(callClass.getName());
         String descriptor = BytecodeHelper.getMethodDescriptor(cachedMethod.getReturnType(), cachedMethod.getNativeParameterTypes());
-        
+
         // prepare call
         int invokeMethodCode = Opcodes.INVOKEVIRTUAL;
         if (cachedMethod.isStatic()) {
@@ -86,8 +83,8 @@ public class CallSiteGenerator {
             // cast argument to parameter class, inclusive unboxing
             // for methods with primitive types
             BytecodeHelper.doCast(mv, parameters[i]);
-        }        
-        
+        }
+
         // make call
         mv.visitMethodInsn(invokeMethodCode, type, cachedMethod.getName(), descriptor, useInterface);
 
@@ -99,7 +96,7 @@ public class CallSiteGenerator {
 
         // return
         mv.visitInsn(Opcodes.ARETURN);
-        
+
         // fall back after method change
         mv.visitLabel(l0);
         for (int i = 0; i < argumentCount; ++i) mv.visitVarInsn(Opcodes.ALOAD, i);
@@ -108,29 +105,28 @@ public class CallSiteGenerator {
         }
         mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/callsite/CallSiteArray", "defaultCall" + name, "(Lorg/codehaus/groovy/runtime/callsite/CallSite;L" + receiverType + ";[Ljava/lang/Object;)Ljava/lang/Object;", false);
         mv.visitInsn(Opcodes.ARETURN);
-        
+
         // exception unwrapping for stackless exceptions
         final Label tryEnd = new Label();
         mv.visitLabel(tryEnd);
         final Label catchStart = new Label();
         mv.visitLabel(catchStart);
         mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/ScriptBytecodeAdapter", "unwrap", "(Lgroovy/lang/GroovyRuntimeException;)Ljava/lang/Throwable;", false);
-        mv.visitInsn(Opcodes.ATHROW);        
-        mv.visitTryCatchBlock(tryStart, tryEnd, catchStart, GRE);
-        
+        mv.visitInsn(Opcodes.ATHROW);
+        mv.visitTryCatchBlock(tryStart, tryEnd, catchStart, "groovy/lang/GroovyRuntimeException");
+
         mv.visitMaxs(0, 0);
         mv.visitEnd();
         return mv;
     }
-    
 
     public static void genCallWithFixedParams(ClassWriter cw, String name, final String superClass, CachedMethod cachedMethod, String receiverType ) {
         if (cachedMethod.getParamsCount() > 4) return;
-        
+
         StringBuilder pdescb = new StringBuilder();
         final int pc = cachedMethod.getParamsCount();
         for (int i = 0; i != pc; ++i) pdescb.append("Ljava/lang/Object;");
-        
+
         writeMethod(cw,name,pc+2,superClass,cachedMethod,receiverType,pdescb.toString(),false);
     }
 
@@ -203,7 +199,7 @@ public class CallSiteGenerator {
         String internalName = name.replace('.', '/');
         classHeader(cw, internalName, "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite");
         cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "__constructor__", "Ljava/lang/reflect/Constructor;", null, null);
- 
+
         genConstructor(cw, "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", internalName);
 
         genCallXxxWithArray(cw, "", "org/codehaus/groovy/runtime/callsite/StaticMetaMethodSite", cachedMethod, "java/lang/Object");
@@ -232,7 +228,7 @@ public class CallSiteGenerator {
         final String name = callSiteLoader.createClassName(cachedMethod.getName());
 
         final byte[] bytes = genPogoMetaMethodSite(cachedMethod, cw, name);
-        
+
         return callSiteLoader.defineClassAndGetConstructor(name, bytes);
     }
 
@@ -244,7 +240,7 @@ public class CallSiteGenerator {
         final String name = callSiteLoader.createClassName(cachedMethod.getName());
 
         final byte[] bytes = genPojoMetaMethodSite(cachedMethod, cw, name);
-        
+
         return callSiteLoader.defineClassAndGetConstructor(name, bytes);
     }
 
@@ -256,7 +252,7 @@ public class CallSiteGenerator {
         final String name = callSiteLoader.createClassName(cachedMethod.getName());
 
         final byte[] bytes = genStaticMetaMethodSite(cachedMethod, cw, name);
-        
+
         return callSiteLoader.defineClassAndGetConstructor(name, bytes);
     }
 


[groovy] 06/12: copy method target for variable that resolves to implicit-this property

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 e0f3f474e018d4bf4d08d804fa122c5498bcca70
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Nov 7 16:56:53 2019 -0600

    copy method target for variable that resolves to implicit-this property
    
    (cherry picked from commit 575f67a442048f875d8f2ab097c22329e9be7819)
---
 .../codehaus/groovy/ast/tools/GeneralUtils.java    | 11 ++++--
 .../transform/stc/StaticTypeCheckingVisitor.java   | 40 ++++++++++++----------
 2 files changed, 29 insertions(+), 22 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 b7360ba..3241767 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java
@@ -730,14 +730,20 @@ public class GeneralUtils {
         return new BinaryExpression(lhv, PLUS, rhv);
     }
 
-    public static Expression propX(Expression owner, String property) {
+    public static PropertyExpression propX(Expression owner, String property) {
         return new PropertyExpression(owner, property);
     }
 
-    public static Expression propX(Expression owner, Expression property) {
+    public static PropertyExpression propX(Expression owner, Expression property) {
         return new PropertyExpression(owner, property);
     }
 
+    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) {
         return new ReturnStatement(new ExpressionStatement(expr));
     }
@@ -919,5 +925,4 @@ public class GeneralUtils {
         return ((firstPackage == null && secondPackage == null) ||
                         firstPackage != null && secondPackage != null && firstPackage.getName().equals(secondPackage.getName()));
     }
-
 }
diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index 37abc13..b8d7a8c 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -187,6 +187,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.isOrImplements;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.thisPropX;
 import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
 import static org.codehaus.groovy.ast.tools.GenericsUtils.findActualTypeByGenericsPlaceholderName;
 import static org.codehaus.groovy.ast.tools.GenericsUtils.makeDeclaringAndActualGenericsTypeMap;
@@ -626,13 +627,12 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
                 BinaryExpression enclosingBinaryExpression = typeCheckingContext.getEnclosingBinaryExpression();
                 if (enclosingBinaryExpression != null) {
                     Expression leftExpression = enclosingBinaryExpression.getLeftExpression();
-                    Expression rightExpression = enclosingBinaryExpression.getRightExpression();
                     SetterInfo setterInfo = removeSetterInfo(leftExpression);
                     if (setterInfo != null) {
+                        Expression rightExpression = enclosingBinaryExpression.getRightExpression();
                         if (!ensureValidSetter(vexp, leftExpression, rightExpression, setterInfo)) {
                             return;
                         }
-
                     }
                 }
             }
@@ -729,25 +729,27 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
     }
 
     private boolean tryVariableExpressionAsProperty(final VariableExpression vexp, final String dynName) {
-        VariableExpression implicitThis = varX("this");
-        PropertyExpression pe = new PropertyExpression(implicitThis, dynName);
-        pe.setImplicitThis(true);
-        if (visitPropertyExpressionSilent(pe, vexp)) {
-            ClassNode previousIt = vexp.getNodeMetaData(INFERRED_TYPE);
-            vexp.copyNodeMetaData(implicitThis);
-            vexp.putNodeMetaData(INFERRED_TYPE, previousIt);
-            storeType(vexp, getType(pe));
-            Object val = pe.getNodeMetaData(READONLY_PROPERTY);
+        PropertyExpression pexp = thisPropX(true, dynName);
+        if (visitPropertyExpressionSilent(pexp, vexp)) {
+            ClassNode propertyType = getType(pexp);
+            pexp.removeNodeMetaData(INFERRED_TYPE);
+
+            vexp.copyNodeMetaData(pexp.getObjectExpression());
+            Object val = pexp.getNodeMetaData(READONLY_PROPERTY);
             if (val != null) vexp.putNodeMetaData(READONLY_PROPERTY, val);
-            val = pe.getNodeMetaData(IMPLICIT_RECEIVER);
+            val = pexp.getNodeMetaData(IMPLICIT_RECEIVER);
             if (val != null) vexp.putNodeMetaData(IMPLICIT_RECEIVER, val);
+            val = pexp.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
+            if (val != null) vexp.putNodeMetaData(DIRECT_METHOD_CALL_TARGET, val);
+
+            storeType(vexp, propertyType);
             return true;
         }
         return false;
     }
 
-    private boolean visitPropertyExpressionSilent(PropertyExpression pe, Expression lhsPart) {
-        return (existsProperty(pe, !isLHSOfEnclosingAssignment(lhsPart)));
+    private boolean visitPropertyExpressionSilent(final PropertyExpression pe, final Expression lhsPart) {
+        return existsProperty(pe, !isLHSOfEnclosingAssignment(lhsPart));
     }
 
     @Override
@@ -762,7 +764,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
     }
 
     private boolean isLHSOfEnclosingAssignment(final Expression expression) {
-        final BinaryExpression ec = typeCheckingContext.getEnclosingBinaryExpression();
+        BinaryExpression ec = typeCheckingContext.getEnclosingBinaryExpression();
         return ec != null && ec.getLeftExpression() == expression && isAssignment(ec.getOperation().getType());
     }
 
@@ -4153,12 +4155,12 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
         return resultType;
     }
 
-    private static boolean isEmptyCollection(Expression expr) {
+    private static boolean isEmptyCollection(final Expression expr) {
         return (expr instanceof ListExpression && ((ListExpression) expr).getExpressions().size() == 0) ||
                 (expr instanceof MapExpression && ((MapExpression) expr).getMapEntryExpressions().size() == 0);
     }
 
-    private static boolean hasInferredReturnType(Expression expression) {
+    private static boolean hasInferredReturnType(final Expression expression) {
         ClassNode type = expression.getNodeMetaData(INFERRED_RETURN_TYPE);
         return type != null && !type.getName().equals("java.lang.Object");
     }
@@ -4180,7 +4182,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
 
     }
 
-    protected void storeType(Expression exp, ClassNode cn) {
+    protected void storeType(final Expression exp, ClassNode cn) {
         if (exp instanceof VariableExpression && ((VariableExpression) exp).isClosureSharedVariable() && isPrimitiveType(cn)) {
             cn = getWrapper(cn);
         } else if (exp instanceof MethodCallExpression && ((MethodCallExpression) exp).isSafe() && isPrimitiveType(cn)) {
@@ -4213,7 +4215,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
         }
         if (exp instanceof VariableExpression) {
             VariableExpression var = (VariableExpression) exp;
-            final Variable accessedVariable = var.getAccessedVariable();
+            Variable accessedVariable = var.getAccessedVariable();
             if (accessedVariable != exp && accessedVariable instanceof VariableExpression) {
                 storeType((VariableExpression) accessedVariable, cn);
             }


[groovy] 08/12: remove extra config

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 7e61b82f9db62d3f97806b892422e12dc2d3ebd1
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu Nov 7 10:06:40 2019 -0600

    remove extra config
    
    (cherry picked from commit 707c2bf3a15c6354ba6d0f124fa08f3ff3fe22ff)
---
 .../groovy/grape/defaultGrapeConfig.xml            | 35 ----------------------
 1 file changed, 35 deletions(-)

diff --git a/src/test-resources/groovy/grape/defaultGrapeConfig.xml b/src/test-resources/groovy/grape/defaultGrapeConfig.xml
deleted file mode 100644
index cd33ee2..0000000
--- a/src/test-resources/groovy/grape/defaultGrapeConfig.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<!--
-
-     Licensed to the Apache Software Foundation (ASF) under one
-     or more contributor license agreements.  See the NOTICE file
-     distributed with this work for additional information
-     regarding copyright ownership.  The ASF licenses this file
-     to you under the Apache License, Version 2.0 (the
-     "License"); you may not use this file except in compliance
-     with the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing,
-     software distributed under the License is distributed on an
-     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     KIND, either express or implied.  See the License for the
-     specific language governing permissions and limitations
-     under the License.
-
--->
-<ivysettings>
-  <settings defaultResolver="downloadGrapes"/>
-  <resolvers>
-    <chain name="downloadGrapes" returnFirst="true">
-      <filesystem name="cachedGrapes">
-        <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
-        <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/>
-      </filesystem>
-      <ibiblio name="localm2" root="file:${user.home}/.m2/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true"/>
-      <!-- todo add 'endorsed groovy extensions' resolver here -->
-      <!--<ibiblio name="jcenter" root="http://jcenter.bintray.com/" m2compatible="true"/>-->
-      <ibiblio name="ibiblio" m2compatible="true"/>
-    </chain>
-  </resolvers>
-</ivysettings>