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/07 20:09:10 UTC

(groovy) branch GROOVY_3_0_X updated (b505625ef8 -> 2202988cbf)

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

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


    from b505625ef8 GROOVY-11369: STC: map entry before access method
     new f9b4eee804 GROOVY-11223: STC: create setter access error
     new 2202988cbf minor items

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


Summary of changes:
 build.gradle                                       |  4 +
 .../transform/stc/StaticTypeCheckingSupport.java   | 25 +++---
 .../transform/stc/StaticTypeCheckingVisitor.java   | 25 ++++--
 .../stc/FieldsAndPropertiesSTCTest.groovy          | 95 +++++++++++++++++++---
 .../groovy/classgen/asm/sc/bugs/Groovy7300.groovy  |  3 +-
 5 files changed, 121 insertions(+), 31 deletions(-)


(groovy) 01/02: GROOVY-11223: STC: create setter access error

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

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

commit f9b4eee804270242de22edc204feab2f9b900392
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue May 7 14:45:03 2024 -0500

    GROOVY-11223: STC: create setter access error
---
 .../transform/stc/StaticTypeCheckingVisitor.java   | 21 ++++++++--
 .../stc/FieldsAndPropertiesSTCTest.groovy          | 46 ++++++++++++++++++----
 .../groovy/classgen/asm/sc/bugs/Groovy7300.groovy  |  3 +-
 3 files changed, 58 insertions(+), 12 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 e30d2605e8..5313e58915 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1042,8 +1042,21 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
             }
             return false;
         } else {
-            ClassNode firstSetterType = setterType.apply(setterInfo.setters.get(0));
-            addAssignmentError(firstSetterType, getType(valueExpression), expression);
+            List<MethodNode> visibleSetters = filterMethodsByVisibility(setterInfo.setters, typeCheckingContext.getEnclosingClassNode());
+            if (visibleSetters.isEmpty()) {
+                String message; // GROOVY-11223
+                if (setterInfo.setters.size() == 1) {
+                    message = String.format("Cannot access method: %2$s of class: %1$s",
+                        prettyPrintTypeName(setterInfo.setters.get(0).getDeclaringClass()),
+                        toMethodParametersString(setterInfo.name, extractTypesFromParameters(setterInfo.setters.get(0).getParameters())));
+                } else {
+                    message = "Cannot access methods: " + prettyPrintMethodList(setterInfo.setters);
+                }
+                addStaticTypeError(message, leftExpression);
+            } else {
+                ClassNode[] tergetTypes = visibleSetters.stream().map(setterType).toArray(ClassNode[]::new);
+                addAssignmentError(tergetTypes.length == 1 ? tergetTypes[0] : new UnionTypeClassNode(tergetTypes), getType(valueExpression), expression);
+            }
             return true;
         }
     }
@@ -1807,9 +1820,9 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
         checkOrMarkPrivateAccess(expressionToStoreOn, field, lhsOfAssignment);
         boolean accessible = hasAccessToMember(isSuperExpression(expressionToStoreOn.getObjectExpression()) ? typeCheckingContext.getEnclosingClassNode() : receiver, field.getDeclaringClass(), field.getModifiers());
 
-        if (expressionToStoreOn instanceof AttributeExpression) { // TODO: expand to include PropertyExpression
+        if (expressionToStoreOn instanceof AttributeExpression) {
             if (!accessible) {
-                addStaticTypeError("The field " + field.getDeclaringClass().getNameWithoutPackage() + "." + field.getName() + " is not accessible", expressionToStoreOn.getProperty());
+                addStaticTypeError("Cannot access field: " + field.getName() + " of class: " + prettyPrintTypeName(field.getDeclaringClass()), expressionToStoreOn.getProperty());
             }
         }
 
diff --git a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
index 1ace4b82ad..15122ed929 100644
--- a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
+++ b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
@@ -207,7 +207,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                 }
             }
         ''',
-        'The field C.x is not accessible'
+        'Cannot access field: x of class: C'
     }
 
     void testShouldComplainAboutMissingAttribute() {
@@ -261,7 +261,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                 }
             }
         ''',
-        'The field C.x is not accessible'
+        'Cannot access field: x of class: C'
     }
 
     void testPropertyWithInheritance() {
@@ -675,13 +675,21 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                 def foo = 1
             }
             def map = new C()
-            map.put('foo', 42)
-            assert map.foo == 42
+            map.put('foo', 11)
+            assert map.foo == 11
+            assert map['foo'] == 11
         '''
         assertScript """
             def map = new ${MapType.name}()
-            map.put('foo', 42)
-            assert map.foo == 42
+            map.put('foo', 11)
+            assert map.foo == 11
+            assert map['foo'] == 11
+            map.put('bar', 22)
+            assert map.bar == 22
+            assert map['bar'] == 22
+            map.put('baz', 33)
+            assert map.baz == 33
+            assert map['baz'] == 33
         """
     }
 
@@ -779,6 +787,26 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         '''
     }
 
+    // GROOVY-11223
+    void testMapPropertyAccess10() {
+        assertScript """
+            def map = new ${MapType.name}()
+            map.foo = 11 // public setter
+            assert map.foo == null
+            assert map.getFoo() == 11
+        """
+        shouldFailWithMessages """
+            def map = new ${MapType.name}()
+            map.bar = 22 // protected setter: Cannot assign value of type int to variable of type Object
+        """,
+        "Cannot access method: setBar(java.lang.Object) of class: ${MapType.name}"
+        shouldFailWithMessages """
+            def map = new ${MapType.name}()
+            map.baz = 33 // package-private setter: Cannot assign value of type int to variable of type Object
+        """,
+        "Cannot access method: setBaz(java.lang.Object) of class: ${MapType.name}"
+    }
+
     void testTypeCheckerDoesNotThinkPropertyIsReadOnly() {
         assertScript '''
             // a base class defining a read-only property
@@ -1624,8 +1652,12 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         String boo = "I don't fancy fields in interfaces"
     }
 
-    static class MapType extends HashMap<String,Object> {
+    static class MapType extends HashMap<String,Number> {
         def foo = 1
+        protected bar = 2
+        @PackageScope baz = 3
+        protected void setBar(bar) {}
+        @PackageScope void setBaz(baz) {}
     }
 
     static class BaseClass {
diff --git a/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/Groovy7300.groovy b/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/Groovy7300.groovy
index 58908dd36e..ab854aae97 100644
--- a/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/Groovy7300.groovy
+++ b/src/test/org/codehaus/groovy/classgen/asm/sc/bugs/Groovy7300.groovy
@@ -76,6 +76,7 @@ final class Groovy7300 extends StaticTypeCheckingTestCase implements StaticCompi
                 def getX() { super.@x }
             }
             assert false
-        ''', 'The field A.x is not accessible'
+        ''',
+        'Cannot access field: x of class: A'
     }
 }


(groovy) 02/02: minor items

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

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

commit 2202988cbf4bae54694feffef3ebfc41d311cb4a
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue May 7 14:53:36 2024 -0500

    minor items
---
 build.gradle                                       |  4 ++
 .../transform/stc/StaticTypeCheckingSupport.java   | 25 +++++------
 .../transform/stc/StaticTypeCheckingVisitor.java   |  4 +-
 .../stc/FieldsAndPropertiesSTCTest.groovy          | 51 ++++++++++++++++++++--
 4 files changed, 64 insertions(+), 20 deletions(-)

diff --git a/build.gradle b/build.gradle
index 29c6f8d304..7cf869227d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -106,6 +106,10 @@ allprojects {
     }
 }
 
+clean.doFirst {
+    delete "${rootDir}/build-logic"
+}
+
 task(copyTestResources, type: Copy)
         .from('src/test')
         .into("$buildDir/classes/test")
diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
index cd354a596f..50103d5348 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
@@ -24,7 +24,6 @@ import org.codehaus.groovy.GroovyBugError;
 import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.ast.GenericsType;
 import org.codehaus.groovy.ast.GenericsType.GenericsTypeName;
-import org.codehaus.groovy.ast.InnerClassNode;
 import org.codehaus.groovy.ast.MethodNode;
 import org.codehaus.groovy.ast.Parameter;
 import org.codehaus.groovy.ast.Variable;
@@ -2033,24 +2032,22 @@ public abstract class StaticTypeCheckingSupport {
     }
 
     /**
-     * Filter methods according to visibility
+     * Filters methods according to visibility.
      *
      * @param methodNodeList method nodes to filter
-     * @param enclosingClassNode the enclosing class
-     * @return filtered method nodes
+     * @param enclosingClassNode the enclosing type
+     * @return filtered method nodes (new list)
      * @since 3.0.0
      */
     public static List<MethodNode> filterMethodsByVisibility(final List<MethodNode> methodNodeList, final ClassNode enclosingClassNode) {
         if (!asBoolean(methodNodeList)) {
-            return StaticTypeCheckingVisitor.EMPTY_METHODNODE_LIST;
+            return Collections.emptyList();
         }
 
         List<MethodNode> result = new LinkedList<>();
+        List< ClassNode> outers = enclosingClassNode.getOuterClasses();
 
-        boolean isEnclosingInnerClass = enclosingClassNode instanceof InnerClassNode;
-        List<ClassNode> outerClasses = enclosingClassNode.getOuterClasses();
-
-        outer:
+        next_method:
         for (MethodNode methodNode : methodNodeList) {
             if (methodNode instanceof ExtensionMethodNode) {
                 result.add(methodNode);
@@ -2059,23 +2056,23 @@ public abstract class StaticTypeCheckingSupport {
 
             ClassNode declaringClass = methodNode.getDeclaringClass();
 
-            if (isEnclosingInnerClass) {
-                for (ClassNode outerClass : outerClasses) {
+            if (asBoolean(outers)) {
+                for (ClassNode outerClass : outers) {
                     if (outerClass.isDerivedFrom(declaringClass)) {
                         if (outerClass.equals(declaringClass)) {
                             result.add(methodNode);
-                            continue outer;
+                            continue next_method;
                         } else {
                             if (methodNode.isPublic() || methodNode.isProtected()) {
                                 result.add(methodNode);
-                                continue outer;
+                                continue next_method;
                             }
                         }
                     }
                 }
             }
 
-            if (declaringClass instanceof InnerClassNode) {
+            if (declaringClass.getOuterClass() != null) {
                 if (declaringClass.getOuterClasses().contains(enclosingClassNode)) {
                     result.add(methodNode);
                     continue;
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 5313e58915..eb162daf8d 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1460,7 +1460,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
     protected boolean existsProperty(final PropertyExpression pexp, final boolean readMode, final ClassCodeVisitorSupport visitor) {
         super.visitPropertyExpression(pexp);
 
-        String propertyName = pexp.getPropertyAsString();
+        final String propertyName = pexp.getPropertyAsString();
         if (propertyName == null) return false;
 
         Expression objectExpression = pexp.getObjectExpression();
@@ -1613,7 +1613,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
 
                 if (field != null && storeField(field, pexp, receiverType, visitor, receiver.getData(), !readMode)) return true;
 
-                foundGetterOrSetter = (foundGetterOrSetter || !setters.isEmpty() || getter != null);
+                foundGetterOrSetter = (foundGetterOrSetter || getter != null || !setters.isEmpty());
             }
 
             // GROOVY-5568: the property may be defined by DGM
diff --git a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
index 15122ed929..7edaea09c0 100644
--- a/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
+++ b/src/test/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy
@@ -195,8 +195,44 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         'No such property: x for class: C'
     }
 
+    // GROOVY-11319
     @NotYetImplemented
     void testShouldComplainAboutMissingProperty3() {
+        shouldFailWithMessages '''
+            class C {
+                private int getX() { 1 }
+            }
+            class D extends C {
+                void test() {
+                    super.x
+                }
+            }
+            new D().test()
+        ''',
+        'No such property: x for class: C'
+    }
+
+    // GROOVY-11319
+    @NotYetImplemented
+    void testShouldComplainAboutMissingProperty4() {
+        shouldFailWithMessages '''
+            class C {
+                private void setX(int i) {
+                    assert false : 'cannot access'
+                }
+            }
+            class D extends C {
+                void test() {
+                    super.x = 1
+                }
+            }
+            new D().test()
+        ''',
+        'No such property: x for class: C'
+    }
+
+    @NotYetImplemented
+    void testShouldComplainAboutMissingProperty5() {
         shouldFailWithMessages '''
             class C {
                 private x
@@ -206,8 +242,9 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
                     this.x
                 }
             }
+            new D().test()
         ''',
-        'Cannot access field: x of class: C'
+        'No such property: x for class: D'
     }
 
     void testShouldComplainAboutMissingAttribute() {
@@ -624,16 +661,22 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
         '''
     }
 
+    // GROOVY-5988
     void testMapPropertyAccess3() {
         assertScript '''
-            String key = 'foo'
-            Map map = [(key): 123]
+            String key = 'name'
+            Map<String, Integer> map = [:]
+            map[key] = 123
             @ASTTest(phase=INSTRUCTION_SELECTION, value={
                 assert node.getNodeMetaData(INFERRED_TYPE) == Integer_TYPE
             })
             def val = map[key]
             assert val == 123
         '''
+        assertScript '''
+            def names = [:].getProperties().keySet()
+            assert names.toSorted() == ['class', 'empty'] // TODO: remove?
+        '''
     }
 
     // GROOVY-5797
@@ -777,7 +820,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase {
             assert map.metaClass == null
         '''
         assertScript type + '''
-            def test(C map) {
+            def test(C map) { // no diff
                 assert map.entry == null
                 assert map.empty == null
                 assert map.class == null