You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2024/05/09 13:50:18 UTC

(groovy) branch GROOVY_4_0_X updated: GROOVY 11370: STC: extension method cannot provide map property

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

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


The following commit(s) were added to refs/heads/GROOVY_4_0_X by this push:
     new 4c8533bbd0 GROOVY 11370: STC: extension method cannot provide map property
4c8533bbd0 is described below

commit 4c8533bbd03ccde654a2f2070365105f1e28664f
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Thu May 9 08:27:40 2024 -0500

    GROOVY 11370: STC: extension method cannot provide map property
---
 .../transform/stc/StaticTypeCheckingVisitor.java   |  52 +++---
 src/test/groovy/bugs/Groovy9115.groovy             |  42 ++---
 .../stc/FieldsAndPropertiesSTCTest.groovy          | 203 ++++++++++++++-------
 .../sc/FieldsAndPropertiesStaticCompileTest.groovy |  39 ++--
 4 files changed, 210 insertions(+), 126 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 60b17da09c..492034f774 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1635,32 +1635,34 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
                 foundGetterOrSetter = (foundGetterOrSetter || getter != null || !setters.isEmpty());
             }
 
-            // GROOVY-5568: the property may be defined by DGM
-            for (ClassNode dgmReceiver : isPrimitiveType(receiverType) ? new ClassNode[]{receiverType, getWrapper(receiverType)} : new ClassNode[]{receiverType}) {
-                Set<MethodNode> methods = findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), dgmReceiver, getterName);
-                for (MethodNode method : findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), dgmReceiver, isserName)) {
-                    if (isPrimitiveBoolean(method.getReturnType())) methods.add(method);
-                }
-                if (staticOnlyAccess && receiver.getData() == null && !isClassType(receiver.getType())) {
-                    // GROOVY-10820: ensure static extension when property accessed in static manner
-                    methods.removeIf(method -> !((ExtensionMethodNode) method).isStaticExtension());
-                }
-                if (isUsingGenericsOrIsArrayUsingGenerics(dgmReceiver)) {
-                    methods.removeIf(method -> // GROOVY-10075: "List<Integer>" vs "List<String>"
-                        !typeCheckMethodsWithGenerics(dgmReceiver, ClassNode.EMPTY_ARRAY, method)
-                    );
-                }
-                if (!methods.isEmpty()) {
-                    List<MethodNode> bestMethods = chooseBestMethod(dgmReceiver, methods, ClassNode.EMPTY_ARRAY);
-                    if (bestMethods.size() == 1) {
-                        MethodNode getter = bestMethods.get(0);
-                        if (visitor != null) {
-                            visitor.visitMethod(getter);
+            if (!readMode || isThisExpression(objectExpression) || isSuperExpression(objectExpression) || !isOrImplements(objectExpressionType, MAP_TYPE)) { // GROOVY-11370
+                // GROOVY-5568, GROOVY-9115, GROOVY-9123: the property may be defined by an extension
+                for (ClassNode dgmReceiver : isPrimitiveType(receiverType) ? new ClassNode[]{receiverType, getWrapper(receiverType)} : new ClassNode[]{receiverType}) {
+                    Set<MethodNode> methods = findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), dgmReceiver, getterName);
+                    for (MethodNode method : findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), dgmReceiver, isserName)) {
+                        if (isPrimitiveBoolean(method.getReturnType())) methods.add(method);
+                    }
+                    if (staticOnlyAccess && receiver.getData() == null && !isClassType(receiver.getType())) {
+                        // GROOVY-10820: ensure static extension when property accessed in static manner
+                        methods.removeIf(method -> !((ExtensionMethodNode) method).isStaticExtension());
+                    }
+                    if (isUsingGenericsOrIsArrayUsingGenerics(dgmReceiver)) {
+                        methods.removeIf(method -> // GROOVY-10075: "List<Integer>" vs "List<String>"
+                            !typeCheckMethodsWithGenerics(dgmReceiver, ClassNode.EMPTY_ARRAY, method)
+                        );
+                    }
+                    if (!methods.isEmpty()) {
+                        List<MethodNode> bestMethods = chooseBestMethod(dgmReceiver, methods, ClassNode.EMPTY_ARRAY);
+                        if (bestMethods.size() == 1) {
+                            MethodNode getter = bestMethods.get(0);
+                            if (visitor != null) {
+                                visitor.visitMethod(getter);
+                            }
+                            ClassNode returnType = inferReturnTypeGenerics(dgmReceiver, getter, ArgumentListExpression.EMPTY_ARGUMENTS);
+                            storeInferredTypeForPropertyExpression(pexp, returnType);
+                            if (readMode) storeTargetMethod(pexp, getter);
+                            return true;
                         }
-                        ClassNode returnType = inferReturnTypeGenerics(dgmReceiver, getter, ArgumentListExpression.EMPTY_ARGUMENTS);
-                        storeInferredTypeForPropertyExpression(pexp, returnType);
-                        if (readMode) storeTargetMethod(pexp, getter);
-                        return true;
                     }
                 }
             }
diff --git a/src/test/groovy/bugs/Groovy9115.groovy b/src/test/groovy/bugs/Groovy9115.groovy
index 748327ded0..900e9318fb 100644
--- a/src/test/groovy/bugs/Groovy9115.groovy
+++ b/src/test/groovy/bugs/Groovy9115.groovy
@@ -18,49 +18,47 @@
  */
 package groovy.bugs
 
-import groovy.transform.CompileStatic
 import org.junit.Test
 
 import static groovy.test.GroovyAssert.assertScript
 
-@CompileStatic
 final class Groovy9115 {
 
     @Test
-    void testSetPropertyInIfStmt() {
+    void testSetProperty1() {
         assertScript '''
             @groovy.transform.CompileStatic
-            class Derived {
-                def m() {
-                    if (true) {
-                        File file = File.createTempFile("hello${System.nanoTime()}", ".tmp")
-                        file.text = 'Groovy9115Bug'
-                        assert 'Groovy9115Bug' == file.text
-                    }
-
-                    return null
+            void test() {
+                File file = File.createTempFile('test', null)
+                try {
+                    file.text = 'GROOVY-9115' // via ResourceGroovyMethods#setText
+                    assert file.text == 'GROOVY-9115'
+                } finally {
+                    file.delete()
                 }
             }
 
-            new Derived().m()
+            test()
         '''
     }
 
     @Test
-    void testSetProperty() {
+    void testSetProperty2() {
         assertScript '''
             @groovy.transform.CompileStatic
-            class Derived {
-                def m() {
-                    File file = File.createTempFile("hello${System.nanoTime()}", ".tmp")
-                    file.text = 'Groovy9115Bug'
-                    assert 'Groovy9115Bug' == file.text
-
-                    return null
+            void test() {
+                if (true) {
+                    File file = File.createTempFile('test', null)
+                    try {
+                        file.text = 'GROOVY-9115' // via ResourceGroovyMethods#setText
+                        assert file.text == 'GROOVY-9115'
+                    } finally {
+                        file.delete()
+                    }
                 }
             }
 
-            new Derived().m()
+            test()
         '''
     }
 }
diff --git a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
index 4b140a5eff..75eab43812 100644
--- a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
+++ b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
@@ -293,6 +293,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                     this.@x
                 }
             }
+            new D().test()
         ''',
         'Cannot access field: x of class: C'
     }
@@ -354,9 +355,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
 
     // GROOVY-9955
     void testStaticPropertyWithInheritanceFromAnotherSourceUnit() {
-        assertScript '''
-            import groovy.transform.stc.FieldsAndPropertiesSTCTest.Public
-
+        assertScript """import ${Public.canonicalName}
             assert Public.answer == 42
             assert Public.CONST == 'XX'
             assert Public.VALUE == null
@@ -365,7 +364,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             Public.@VALUE = 'ZZ'
             assert Public.@VALUE == 'ZZ'
             Public.VALUE = null
-        '''
+        """
     }
 
     void testDateProperties() {
@@ -682,20 +681,23 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
     void testMapPropertyAccess5() {
         assertScript '''
             def map = [:]
-            assert map.entry     == null
-            assert map.empty     == null
-            assert map.class     == null
-            assert map.metaClass == null // TODO
-
-            map.entry     = null
-            map.empty     = null // not read-only property
-            map.class     = null // not read-only property
-            map.metaClass = null // TODO: 6549 SC is "put"
+            assert map.entry      == null
+            assert map.empty      == null
+            assert map.class      == null
+            assert map.metaClass  == null // TODO
+            assert map.properties == null
+
+            map.entry      = null
+            map.empty      = null // not read-only property
+            map.class      = null // not read-only property
+            map.metaClass  = null // TODO: 6549 SC is "put"
+            map.properties = null
 
             assert  map.containsKey('entry')
             assert  map.containsKey('empty')
             assert  map.containsKey('class')
           //assert !map.containsKey('metaClass')
+            assert  map.containsKey('properties')
         '''
     }
 
@@ -840,6 +842,24 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         """
     }
 
+    // GROOVY-11370
+    void testMapPropertyAccess11() {
+        assertScript '''
+            def map = [:]
+            @ASTTest(phase=INSTRUCTION_SELECTION, value={
+                assert node.getNodeMetaData(INFERRED_TYPE) == OBJECT_TYPE // not METACLASS_TYPE
+            })
+            def val = map.metaClass
+        '''
+        assertScript '''
+            def map = [:]
+            @ASTTest(phase=INSTRUCTION_SELECTION, value={
+                assert node.getNodeMetaData(INFERRED_TYPE) == OBJECT_TYPE // not MAP_TYPE
+            })
+            def val = map.properties
+        '''
+    }
+
     void testTypeCheckerDoesNotThinkPropertyIsReadOnly() {
         assertScript '''
             // a base class defining a read-only property
@@ -1005,13 +1025,58 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                     }
                 }
             }
-            Outer.Inner.FOO
+            def foo = Outer.Inner.FOO
             assert Outer.props == [bar: 10, baz: 20, foo: 30]
         '''
     }
 
-    // GROOVY-10981, GROOVY-10985
     void testOuterPropertyAccess9() {
+        assertScript '''
+            class Outer {
+                static final int ONE = 1
+                enum Inner {
+                    CONST(1 + ONE)
+                    final int value
+                    Inner(int value) {
+                        this.value = value
+                    }
+                }
+            }
+            assert Outer.Inner.CONST.value == 2
+        '''
+    }
+
+    void testOuterPropertyAccess10() {
+        assertScript '''
+            class Outer {
+                class Inner {
+                    def m() { p }
+                }
+                String p = 'field'
+                String getP() { 'property' }
+            }
+            String which = new Outer.Inner(new Outer()).m()
+            assert which == 'property'
+        '''
+    }
+
+    // GROOVY-11199
+    void testOuterPropertyAccess11() {
+        assertScript '''
+            class Outer {
+                class Inner {
+                    def m() { p = 'method' }
+                }
+                String p = 'field'
+                String getP() { 'property' }
+            }
+            String which = new Outer.Inner(new Outer()).m()
+            assert which == 'method'
+        '''
+    }
+
+    // GROOVY-10981, GROOVY-10985
+    void testOuterPropertyAccess12() {
         for (propertySource in [
                 'def get(String name){if(name=="VALUE")return 2}',
                 'def getProperty(String name){if(name=="VALUE")return 2}',
@@ -1038,51 +1103,46 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
     // GROOVY-11029
     void testSuperPropertyAccess1() {
         assertScript '''
-            class Foo {
-                Object myThing
+            class C {
+                Object thing
             }
-            class Bar extends Foo {
+            class D extends C {
                 @Override
-                Object getMyThing() {
-                    super.myThing
+                Object getThing() {
+                    super.thing
                 }
                 @Override
-                void setMyThing(Object object) {
-                    super.myThing = object
+                void setThing(object) {
+                    super.thing = object
                 }
             }
-
-            def bar = new Bar()
-            def value = 'thing'
-            bar.myThing = value
-            assert bar.myThing === value
+            def d = new D()
+            d.thing = 'value'
+            assert d.thing == 'value'
         '''
     }
 
     // GROOVY-9562
     void testSuperPropertyAccess2() {
         assertScript '''
-            abstract class One {
-                int prop = 1
+            abstract class A {
+                final int prop = 1
             }
-
-            abstract class Two {
-                int prop = 2
-
-                abstract baz()
+            abstract class B {
+                final int prop = 2
+                abstract int baz()
             }
-
-            class Foo extends One {
-                Two bar() {
-                    new Two() {
-                        def baz() {
+            class C extends A {
+                B bar() {
+                    new B() {
+                        int baz() {
                             prop
                         }
                     }
                 }
             }
-
-            assert new Foo().bar().baz() == 2
+            Number which = new C().bar().baz()
+            assert which == 2 // super before outer
         '''
     }
 
@@ -1109,8 +1169,8 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             class C {
                 private int x
                 void test() {
-                    def c = { -> x = 666 }
-                    c()
+                    def func = { -> x = 666 }
+                    func()
                     assert x == 666
                 }
             }
@@ -1163,9 +1223,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
     // GROOVY-5737
     void testGeneratedFieldAccessInClosure() {
         assertScript '''
-            import groovy.util.logging.*
-
-            @Log
+            @groovy.util.logging.Log
             class GreetingActor {
                 def receive = {
                     log.info "test"
@@ -1175,6 +1233,36 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         '''
     }
 
+    // GROOVY-6277
+    void testPublicFieldVersusPrivateGetter() {
+        assertScript '''
+            class C {
+                private String getWho() { 'C' }
+            }
+            class D extends C {
+                public String who = 'D'
+            }
+            String result = new D().who
+            assert result == 'D'
+        '''
+    }
+
+    void testProtectedAccessorFromSamePackage() {
+        assertScript '''
+            class C {
+                protected String getWho() { 'C' }
+            }
+            class D {
+                def m(C c) {
+                    def x = c.who
+                    x.toLowerCase()
+                }
+            }
+            String result = new D().m(new C())
+            assert result == 'c'
+        '''
+    }
+
     // GROOVY-6610
     void testPrivateStaticFieldAccessBeforeThis() {
         assertScript '''
@@ -1408,7 +1496,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                     assert md.parameters[0].originType == STRING_TYPE
                 }
             })
-            void testBody() {
+            void test() {
                 def c = new C()
                 test1:
                 c.x = 1
@@ -1417,7 +1505,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                 c.x = "3"
                 assert c.x == "3"
             }
-            testBody()
+            test()
         '''
     }
 
@@ -1446,12 +1534,11 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             abstract class A implements I { String which
                 void setX(boolean b) { which = 'boolean' }
             }
-
-            void test(A a) {
-                a.x = 'value'
-                assert a.which == 'String'
+            A a = new A() {
+                void setX(String s) { which = 'String' }
             }
-            test(new A() { void setX(String s) { which = 'String' } })
+            a.x = 'value'
+            assert a.which == 'String'
         '''
     }
 
@@ -1487,16 +1574,13 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             assertScript '''
                 class C {
                     int which
-
                     C() {
                         contentView = 42L
                         assert which == 2
                     }
-
                     void setContentView(Date value) { which = 1 }
                     void setContentView(Long value) { which = 2 }
                 }
-
                 class D extends C {
                     void m() {
                         contentView = 42L
@@ -1505,7 +1589,6 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                         assert which == 1
                     }
                 }
-
                 new D().m()
             '''
         }
@@ -1516,14 +1599,11 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             assertScript '''
                 class C {
                     int which
-
                     void setContentView(Date value) { which = 1 }
                     void setContentView(Long value) { which = 2 }
                 }
-
                 class D extends C {
                 }
-
                 new D().with {
                     contentView = 42L
                     assert which == 2
@@ -1539,7 +1619,6 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             class BooleanSetterOnly {
                 void setFlag(boolean b) {}
             }
-
             def b = new BooleanSetterOnly()
             b.flag = 'foo'
         '''
@@ -1547,7 +1626,6 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             class StringSetterOnly {
                 void setFlag(String b) {}
             }
-
             def b = new StringSetterOnly()
             b.flag = false
         '''
@@ -1555,7 +1633,6 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             class ClassSetterOnly {
                 void setFlag(Class b) {}
             }
-
             def b = new ClassSetterOnly()
             b.flag = 'java.lang.String'
         '''
diff --git a/src/test/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy
index 14831a4594..22964e632e 100644
--- a/src/test/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy
+++ b/src/test/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy
@@ -18,8 +18,12 @@
  */
 package org.codehaus.groovy.classgen.asm.sc
 
+import groovy.test.NotYetImplemented
 import groovy.transform.stc.FieldsAndPropertiesSTCTest
 
+/**
+ * Unit tests for static compilation : fields and properties.
+ */
 final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCTest implements StaticCompilationTestSupport {
 
     // GROOVY-5561
@@ -235,8 +239,8 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
                 }
                 assert new D().m() == 0
             """
-            def b = astTrees['D'][1]
-            assert  b.contains('GETFIELD C.x')
+            def d = astTrees['D'][1]
+            assert d.contains('GETFIELD C.x')
         }
     }
 
@@ -279,9 +283,9 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
             }
             assert D.m() == 0
         '''
-        def b = astTrees['D'][1]
-        assert  b.contains('GETSTATIC D.x')
-        assert !b.contains('INVOKESTATIC org/codehaus/groovy/runtime/ScriptBytecodeAdapter.getGroovyObjectProperty')
+        def d = astTrees['D'][1]
+        assert  d.contains('GETSTATIC D.x')
+        assert !d.contains('INVOKESTATIC org/codehaus/groovy/runtime/ScriptBytecodeAdapter.getGroovyObjectProperty')
     }
 
     void testReadPropertyFromSuperClass() {
@@ -298,9 +302,9 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
                 }
                 assert new D().m() == 0
             """
-            def b = astTrees['D'][1]
-            assert !b.contains('GETFIELD C.x') : 'no GETFIELD in D'
-            assert  b.contains('INVOKEVIRTUAL D.getX') : 'getX() in D'
+            def d = astTrees['D'][1]
+            assert !d.contains('GETFIELD C.x') : 'no GETFIELD in D'
+            assert  d.contains('INVOKEVIRTUAL D.getX') : 'getX() in D'
         }
     }
 
@@ -324,8 +328,8 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
             d.m()
             assert d.isGetterCalled() == false
         '''
-        def b = astTrees['D'][1]
-        assert b.contains('GETFIELD C.x')
+        def d = astTrees['D'][1]
+        assert d.contains('GETFIELD C.x')
     }
 
     void testUseAttributeExternal() {
@@ -547,7 +551,6 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
                 class C {
                    void setOut(int a) {}
                 }
-
                 def c = new C()
                 try {
                 } finally {
@@ -568,7 +571,6 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
                    void setOut(int a) {}
                    void setOut(String a) {}
                 }
-
                 def c = new C()
                 try {
                 } finally {
@@ -579,8 +581,8 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
         } finally {
             assert astTrees.values().any {
                 def code = it.toString()
-                code.contains('INVOKEVIRTUAL C.setOut (I)V') &&
-                        code.contains('INVOKEVIRTUAL C.setOut (Ljava/lang/String;)V')
+                code.contains('INVOKEVIRTUAL C.setOut (I)V')
+                        && code.contains('INVOKEVIRTUAL C.setOut (Ljava/lang/String;)V')
             }
         }
     }
@@ -776,7 +778,6 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
                         println accessedAndMutated
                         accessedAndMutated = 'def'
                     }
-
                     void test() {
                         cl()
                         assert mutated == 'abc'
@@ -803,7 +804,7 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
     void testPropertyAccessOnEnumClass() {
         assertScript '''
             enum E { }
-            assert E.getModifiers() == E.modifiers
+            assert E.modifiers == E.getModifiers()
         '''
     }
 
@@ -859,6 +860,12 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT
         '''
     }
 
+    // GROOVY-6277
+    @Override @NotYetImplemented
+    void testPublicFieldVersusPrivateGetter() {
+        super.testPublicFieldVersusPrivateGetter()
+    }
+
     // GROOVY-11223
     @Override
     void testMapPropertyAccess10() {