You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2022/01/24 05:23:57 UTC
[groovy] branch GROOVY_4_0_X updated (eb2c9e3 -> 8efeaf2)
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a change to branch GROOVY_4_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git.
from eb2c9e3 GROOVY-8433: Category transform implies static methods
new e103144 GROOVY-10434: ClassNode isSealed() refactoring: mark methods @Incubating, move sealed detection to an earlier phase and fix redirect issue
new 8efeaf2 GROOVY-6363: add test case
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:
src/main/java/groovy/lang/MetaClassImpl.java | 29 +--
src/main/java/groovy/transform/Sealed.java | 4 +-
.../java/org/codehaus/groovy/ast/ClassNode.java | 8 +-
.../org/codehaus/groovy/classgen/Verifier.java | 38 +--
.../SealedCompletionASTTransformation.java | 81 ++++++
src/test/groovy/lang/CategoryAnnotationTest.groovy | 273 +++++++++++----------
src/test/groovy/lang/MixinAnnotationTest.groovy | 24 +-
7 files changed, 284 insertions(+), 173 deletions(-)
create mode 100644 src/main/java/org/codehaus/groovy/transform/SealedCompletionASTTransformation.java
[groovy] 02/02: GROOVY-6363: add test case
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch GROOVY_4_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 8efeaf26d5b693d20cafee54bc25df7048afbc87
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Jan 21 10:04:00 2022 -0600
GROOVY-6363: add test case
---
src/main/java/groovy/lang/MetaClassImpl.java | 29 +--
src/test/groovy/lang/CategoryAnnotationTest.groovy | 273 +++++++++++----------
src/test/groovy/lang/MixinAnnotationTest.groovy | 24 +-
3 files changed, 185 insertions(+), 141 deletions(-)
diff --git a/src/main/java/groovy/lang/MetaClassImpl.java b/src/main/java/groovy/lang/MetaClassImpl.java
index aa9fdf8..7600e7a 100644
--- a/src/main/java/groovy/lang/MetaClassImpl.java
+++ b/src/main/java/groovy/lang/MetaClassImpl.java
@@ -3252,21 +3252,22 @@ public class MetaClassImpl implements MetaClass, MutableMetaClass {
* {@code null} : ignore method
* {@code true} : replace
*/
- private static Boolean getMatchKindForCategory(MetaMethod aMethod, MetaMethod categoryMethod) {
- CachedClass[] params1 = aMethod.getParameterTypes();
- CachedClass[] params2 = categoryMethod.getParameterTypes();
- if (params1.length != params2.length) return Boolean.FALSE;
+ private static Boolean getMatchKindForCategory(final MetaMethod aMethod, final MetaMethod categoryMethod) {
+ CachedClass[] paramTypes1 = aMethod.getParameterTypes();
+ CachedClass[] paramTypes2 = categoryMethod.getParameterTypes();
+ int n = paramTypes1.length;
+ if (n != paramTypes2.length) return Boolean.FALSE;
+ for (int i = 0; i < n; i += 1) {
+ if (paramTypes1[i] != paramTypes2[i]) return Boolean.FALSE;
+ }
+
+ Class selfType1 = aMethod.getDeclaringClass().getTheClass();
+ Class selfType2 = categoryMethod.getDeclaringClass().getTheClass();
+ // replace if self type is the same or the category self type is more specific
+ if (selfType1 == selfType2 || selfType1.isAssignableFrom(selfType2)) return Boolean.TRUE;
+ // GROOVY-6363: replace if the private method self type is more specific
+ // if (aMethod.isPrivate() && selfType2.isAssignableFrom(selfType1)) return Boolean.TRUE;
- for (int i = 0; i < params1.length; i++) {
- if (params1[i] != params2[i]) return Boolean.FALSE;
- }
-
- Class aMethodClass = aMethod.getDeclaringClass().getTheClass();
- Class categoryMethodClass = categoryMethod.getDeclaringClass().getTheClass();
-
- if (aMethodClass == categoryMethodClass) return Boolean.TRUE;
- boolean match = aMethodClass.isAssignableFrom(categoryMethodClass);
- if (match) return Boolean.TRUE;
return null;
}
diff --git a/src/test/groovy/lang/CategoryAnnotationTest.groovy b/src/test/groovy/lang/CategoryAnnotationTest.groovy
index 098783b..0a0fde2 100644
--- a/src/test/groovy/lang/CategoryAnnotationTest.groovy
+++ b/src/test/groovy/lang/CategoryAnnotationTest.groovy
@@ -18,98 +18,92 @@
*/
package groovy.lang
-import groovy.test.GroovyTestCase
+import groovy.test.NotYetImplemented
+import org.junit.Test
-class CategoryAnnotationTest extends GroovyTestCase {
- void testTransformationOfPropertyInvokedOnThis() {
- //Test the fix for GROOVY-3367
- assertScript """
- @Category(Distance3367)
- class DistanceCategory3367 {
- Distance3367 plus(Distance3367 increment) {
- new Distance3367(number: this.number + increment.number)
- }
- }
+import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
+
+final class CategoryAnnotationTest {
- class Distance3367 {
+ @Test // GROOVY-3367
+ void testTransformationOfPropertyInvokedOnThis() {
+ assertScript '''
+ class Distance {
def number
}
+ @Category(Distance)
+ class DistanceCategory {
+ Distance plus(Distance increment) {
+ new Distance(number: this.number + increment.number)
+ }
+ }
- use(DistanceCategory3367) {
- def d1 = new Distance3367(number: 5)
- def d2 = new Distance3367(number: 10)
+ use(DistanceCategory) {
+ def d1 = new Distance(number: 5)
+ def d2 = new Distance(number: 10)
def d3 = d1 + d2
assert d3.number == 15
}
- """
+ '''
}
- void testTransformationWithCatchClause() {
- //Test the fix for GROOVY-4801
- assertScript """
- class ExceptionHandler {
- static def handled(Object self, Closure block) {
- try { block.call() }
- catch (Throwable t) { t.message }
- }
+ @Test // GROOVY-3543
+ void testCategoryMethodsHavingDeclarationStatements() {
+ // Declaration statements in category class' methods were not being visited by
+ // CategoryASTTransformation's expressionTransformer resulting in declaration
+ // variables not being defined on varStack resulting in compilation errors later
+ assertScript '''
+ interface Test {
+ String getName()
}
-
- @Mixin(ExceptionHandler)
- class Caller {
- def thrower() { handled { 1/0 } }
+ class MyTest implements Test {
+ String getName() {
+ return "Pre-"
+ }
}
-
- assert new Caller().thrower() == 'Division by zero'
- """
- }
-
- void testCategoryMethodsHavingDeclarationStatements() {
- // GROOVY-3543: Declaration statements in category class' methods were not being visited by
- // CategoryASTTransformation's expressionTransformer resulting in declaration variables not being
- // defined on varStack resulting in compilation errors later
- assertScript """
@Category(Test)
class TestCategory {
- String getSuperName1() {
- String myname = ""
- return myname + "hi from category"
+ String getSuperName1() {
+ String myname = ""
+ return myname + "hi from category"
}
// 2nd test case of JIRA
- String getSuperName2() {
- String myname = this.getName()
- for(int i = 0; i < 5; i++) myname += i
+ String getSuperName2() {
+ String myname = this.getName()
+ for(int i = 0; i < 5; i++) myname += i
return myname + "-Post"
}
// 3rd test case of JIRA
- String getSuperName3() {
- String myname = this.getName()
+ String getSuperName3() {
+ String myname = this.getName()
for(i in 0..4) myname += i
return myname + "-Post"
}
}
- interface Test {
- String getName()
- }
-
- class MyTest implements Test {
- String getName() {
- return "Pre-"
- }
+ def test = new MyTest()
+ use(TestCategory) {
+ assert test.getSuperName1() == "hi from category"
+ assert test.getSuperName2() == "Pre-01234-Post"
+ assert test.getSuperName3() == "Pre-01234-Post"
}
-
- def onetest = new MyTest()
- use(TestCategory) {
- assert onetest.getSuperName1() == "hi from category"
- assert onetest.getSuperName2() == "Pre-01234-Post"
- assert onetest.getSuperName3() == "Pre-01234-Post"
- }
- """
+ '''
}
+ @Test // GROOVY-3543
void testPropertyNameExpandingToGetterInsideCategoryMethod() {
- //GROOVY-3543: Inside the category method, this.getType().name was failing but this.getType().getName() was not.
- assertScript """
+ // Inside the category method, this.getType().name was failing but this.getType().getName() was not.
+ assertScript '''
+ class Type {
+ String name
+ }
+ interface Guy {
+ Type getType()
+ }
+ class MyGuyver implements Guy {
+ Type type
+ }
@Category(Guy)
class Naming {
String getTypeName() {
@@ -120,59 +114,46 @@ class CategoryAnnotationTest extends GroovyTestCase {
}
}
- interface Guy {
- Type getType()
- }
-
- class Type {
- String name
- }
-
- class MyGuyver implements Guy {
- Type type
- }
-
def atype = new Type(name: 'String')
def onetest = new MyGuyver(type:atype)
use(Naming) {
assert onetest.getTypeName() == onetest.getType().getName()
}
- """
+ '''
}
+ @Test
void testClosureUsingThis() {
- assertScript """
- @Category(Guy)
- class Filtering {
- List process() {
- this.messages.findAll{it.name != this.getName()}
- }
- }
-
+ assertScript '''
interface Guy {
String getName()
List getMessages()
}
-
class MyGuyver implements Guy {
List messages
String name
}
+ @Category(Guy)
+ class Filtering {
+ List process() {
+ this.messages.findAll{it.name != this.getName()}
+ }
+ }
- def onetest = new MyGuyver(
- name: 'coucou',
- messages : [['name':'coucou'], ['name':'test'], ['name':'salut']])
+ def onetest = new MyGuyver(name: 'coucou',
+ messages: [['name':'coucou'], ['name':'test'], ['name':'salut']]
+ )
- Guy.mixin Filtering
+ Guy.mixin Filtering
- assert onetest.process() == onetest.messages.findAll{it.name != onetest.getName()}
- """
+ assert onetest.process() == onetest.messages.findAll{it.name != onetest.getName()}
+ '''
}
+ @Test // GROOVY-4546
void testClosureWithinDeclarationExpressionAndMultipleAssignment() {
- // GROOVY-4546
- assertScript """
+ assertScript '''
@Category(Integer)
class MyOps {
def multiplesUpTo4() { [this * 2, this * 3, this * 4] }
@@ -195,16 +176,12 @@ class CategoryAnnotationTest extends GroovyTestCase {
assert 5.alsoMultiplesUpTo(6) == [10, 15, 20, 25, 30]
assert 5.twice() == 10
}
- """
+ '''
}
- // GROOVY-6120
+ @Test // GROOVY-6120
void testFieldShouldNotBeAllowedInCategory() {
- def message = shouldFail(RuntimeException) {
- assertScript '''
- @Mixin(Foo)
- class Bar { }
-
+ def err = shouldFail RuntimeException, '''
@Category(Bar)
class Foo {
public x = 5
@@ -212,20 +189,18 @@ class CategoryAnnotationTest extends GroovyTestCase {
x
}
}
+ @Mixin(Foo)
+ class Bar {
+ }
assert new Bar().foo() == 5
- '''
- }
- assert message.contains('The @Category transformation does not support instance fields')
+ '''
+ assert err =~ /The @Category transformation does not support instance fields/
}
- // GROOVY-6120
+ @Test // GROOVY-6120
void testPropertyShouldNotBeAllowedInCategory() {
- def message = shouldFail(RuntimeException) {
- assertScript '''
- @Mixin(Foo)
- class Bar { }
-
+ def err = shouldFail RuntimeException, '''
@Category(Bar)
class Foo {
int x = 5
@@ -233,56 +208,67 @@ class CategoryAnnotationTest extends GroovyTestCase {
x
}
}
+ @Mixin(Foo)
+ class Bar {
+ }
assert new Bar().foo() == 5
- '''
- }
- assert message.contains('The @Category transformation does not support instance properties')
+ '''
+ assert err =~ /The @Category transformation does not support instance properties/
}
- // GROOVY-6120
+ @Test // GROOVY-6120
void testShouldNotThrowVerifyError() {
assertScript '''
- @Mixin(Foo)
- class Bar { int x = 5 }
-
@Category(Bar)
class Foo {
def foo() {
x
}
}
+ @Mixin(Foo)
+ class Bar {
+ int x = 5
+ }
assert new Bar().foo() == 5
'''
}
- // GROOVY-6120
+ @Test // GROOVY-6120
void testCategoryShouldBeCompatibleWithCompileStatic() {
assertScript '''
- @Mixin(Foo)
- class Bar { int x = 5 }
+ import groovy.transform.CompileStatic
+ @CompileStatic
@Category(Bar)
- @groovy.transform.CompileStatic
class Foo {
def foo() {
x
}
}
+ @Mixin(Foo)
+ class Bar {
+ int x = 5
+ }
assert new Bar().foo() == 5
'''
}
- void testCategoryShouldBeCompatibleWithCompileStatic_GROOVY6917() {
+ @Test // GROOVY-6917
+ void testCategoryShouldBeCompatibleWithCompileStatic2() {
assertScript '''
- @groovy.transform.CompileStatic
+ import groovy.transform.CompileStatic
+
+ @CompileStatic
@Category(Integer)
class IntegerCategory {
- Integer twice() { this * 2 }
+ Integer twice() {
+ this * 2
+ }
List<Integer> multiplesUpTo(Integer num) {
- (2..num).collect{ j -> this * j }
+ (2..num).collect{ n -> this * n }
}
List<Integer> multiplyAll(List<Integer> nums) {
nums.collect{ it * this }
@@ -296,5 +282,40 @@ class CategoryAnnotationTest extends GroovyTestCase {
}
'''
}
-}
+ @NotYetImplemented @Test // GROOVY-6363
+ void testCategoryMethodOverridesPrivateMethod() {
+ assertScript '''
+ import groovy.transform.CompileStatic
+
+ interface Path {
+ def m()
+ }
+ @Category(Path)
+ class PathExtension {
+ boolean isEmpty() {
+ return true
+ }
+ }
+ class UnixPath implements Path {
+ private boolean isEmpty() {
+ return false
+ }
+ @CompileStatic
+ @Override m() {
+ isEmpty().toString()
+ }
+ }
+
+ Path getPath(String path) {
+ return new UnixPath()
+ }
+
+ use (PathExtension) {
+ def path = getPath('/foo')
+ assert path.isEmpty() : 'private method used'
+ assert path.m() == 'false' : 'category method used'
+ }
+ '''
+ }
+}
diff --git a/src/test/groovy/lang/MixinAnnotationTest.groovy b/src/test/groovy/lang/MixinAnnotationTest.groovy
index 49df14f..6591a32 100644
--- a/src/test/groovy/lang/MixinAnnotationTest.groovy
+++ b/src/test/groovy/lang/MixinAnnotationTest.groovy
@@ -58,7 +58,7 @@ final class MixinAnnotationTest {
}
@Test
- void testMultipleMixinAnnotation () {
+ void testMultipleMixinAnnotation() {
assertScript '''
@Category(Object)
class CategoryToUse1 {
@@ -86,6 +86,28 @@ final class MixinAnnotationTest {
'''
}
+ @Test // GROOVY-4801
+ void testMixinWithTryCatchClause() {
+ assertScript '''
+ class ExceptionHandler {
+ static tryCatch(Object self, Closure block) {
+ try {
+ block.call()
+ } catch (Throwable t) {
+ return t.message
+ }
+ }
+ }
+
+ @Mixin(ExceptionHandler)
+ class C {
+ def m() { tryCatch { 1/0 } }
+ }
+
+ assert new C().m() == 'Division by zero'
+ '''
+ }
+
@Test // GROOVY-10200
void testStaticInnerMixinAnnotation() {
assertScript '''
[groovy] 01/02: GROOVY-10434: ClassNode isSealed() refactoring: mark methods @Incubating, move sealed detection to an earlier phase and fix redirect issue
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch GROOVY_4_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit e103144ad76baac6a576a983b54cd3bc53b3cba9
Author: Paul King <pa...@asert.com.au>
AuthorDate: Wed Jan 19 15:04:35 2022 +1000
GROOVY-10434: ClassNode isSealed() refactoring: mark methods @Incubating, move sealed detection to an earlier phase and fix redirect issue
---
src/main/java/groovy/transform/Sealed.java | 4 +-
.../java/org/codehaus/groovy/ast/ClassNode.java | 8 ++-
.../org/codehaus/groovy/classgen/Verifier.java | 38 +++-------
.../SealedCompletionASTTransformation.java | 81 ++++++++++++++++++++++
4 files changed, 99 insertions(+), 32 deletions(-)
diff --git a/src/main/java/groovy/transform/Sealed.java b/src/main/java/groovy/transform/Sealed.java
index fef0bff..3fa96a1 100644
--- a/src/main/java/groovy/transform/Sealed.java
+++ b/src/main/java/groovy/transform/Sealed.java
@@ -35,7 +35,9 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Incubating
-@GroovyASTTransformationClass("org.codehaus.groovy.transform.SealedASTTransformation")
+@GroovyASTTransformationClass({
+ "org.codehaus.groovy.transform.SealedASTTransformation",
+ "org.codehaus.groovy.transform.SealedCompletionASTTransformation"})
public @interface Sealed {
/**
* List of the permitted subclasses.
diff --git a/src/main/java/org/codehaus/groovy/ast/ClassNode.java b/src/main/java/org/codehaus/groovy/ast/ClassNode.java
index 81fa7dd..0874d61 100644
--- a/src/main/java/org/codehaus/groovy/ast/ClassNode.java
+++ b/src/main/java/org/codehaus/groovy/ast/ClassNode.java
@@ -19,6 +19,7 @@
package org.codehaus.groovy.ast;
import org.apache.groovy.ast.tools.ClassNodeUtils;
+import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.Expression;
@@ -388,8 +389,9 @@ public class ClassNode extends AnnotatedNode {
}
/**
- * @return permitted subclasses of sealed type
+ * @return permitted subclasses of sealed type, may initially be empty in early compiler phases
*/
+ @Incubating
public List<ClassNode> getPermittedSubclasses() {
if (redirect != null)
return redirect.getPermittedSubclasses();
@@ -397,6 +399,7 @@ public class ClassNode extends AnnotatedNode {
return permittedSubclasses;
}
+ @Incubating
public void setPermittedSubclasses(List<ClassNode> permittedSubclasses) {
if (redirect != null) {
redirect.setPermittedSubclasses(permittedSubclasses);
@@ -1420,7 +1423,10 @@ public class ClassNode extends AnnotatedNode {
/**
* @return true for native and emulated (annotation based) sealed classes
*/
+ @Incubating
public boolean isSealed() {
+ if (redirect != null) return redirect.isSealed();
+ lazyClassInit();
return !getAnnotations(SEALED_TYPE).isEmpty() || !getPermittedSubclasses().isEmpty();
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/Verifier.java b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
index 1a99ca4..81314b2 100644
--- a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
@@ -56,7 +56,6 @@ import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.FieldExpression;
-import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
@@ -103,7 +102,6 @@ import static org.apache.groovy.ast.tools.MethodNodeUtils.getCodeAsBlock;
import static org.apache.groovy.ast.tools.MethodNodeUtils.getPropertyName;
import static org.apache.groovy.ast.tools.MethodNodeUtils.methodDescriptorWithoutReturnType;
import static org.codehaus.groovy.ast.AnnotationNode.METHOD_TARGET;
-import static org.codehaus.groovy.ast.ClassHelper.SEALED_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.isObjectType;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveBoolean;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveDouble;
@@ -113,7 +111,6 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.block;
import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callThisX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
-import static org.codehaus.groovy.ast.tools.GeneralUtils.classX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.declS;
import static org.codehaus.groovy.ast.tools.GeneralUtils.fieldX;
@@ -165,9 +162,14 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
// NOTE: timeStamp constants shouldn't belong to Verifier but kept here for binary compatibility
public static final String __TIMESTAMP = "__timeStamp";
public static final String __TIMESTAMP__ = "__timeStamp__239_neverHappen";
+ @Deprecated
public static final Class<Sealed> SEALED_CLASS = Sealed.class;
+ @Deprecated
public static final Class<NonSealed> NON_SEALED_CLASS = NonSealed.class;
+ private static final Class<Sealed> SEALED_TYPE = Sealed.class;
+ private static final Class<NonSealed> NON_SEALED_TYPE = NonSealed.class;
+
private ClassNode classNode;
private MethodNode methodNode;
@@ -243,7 +245,6 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
if (classNode.getNodeMetaData(ClassNodeSkip.class) == null) {
classNode.setNodeMetaData(ClassNodeSkip.class, true);
}
- addDetectedSealedClasses(node);
return;
}
@@ -275,8 +276,6 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
checkForDuplicateMethods(node);
addCovariantMethods(node);
detectNonSealedClasses(node);
- addDetectedSealedClasses(node);
-
checkFinalVariables(node);
}
@@ -292,8 +291,8 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
private void detectNonSealedClasses(ClassNode node) {
if (isFinal(node.getModifiers())) return;
- if (Boolean.TRUE.equals(node.getNodeMetaData(SEALED_CLASS))) return;
- if (Boolean.TRUE.equals(node.getNodeMetaData(NON_SEALED_CLASS))) return;
+ if (Boolean.TRUE.equals(node.getNodeMetaData(SEALED_TYPE))) return;
+ if (Boolean.TRUE.equals(node.getNodeMetaData(NON_SEALED_TYPE))) return;
ClassNode sn = node.getSuperClass();
boolean found = false;
while (sn != null && !sn.equals(ClassHelper.OBJECT_TYPE)) {
@@ -304,31 +303,10 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
sn = sn.getSuperClass();
}
if (found) {
- node.putNodeMetaData(NON_SEALED_CLASS, Boolean.TRUE);
+ node.putNodeMetaData(NON_SEALED_TYPE, Boolean.TRUE);
}
}
- private void addDetectedSealedClasses(ClassNode node) {
- boolean sealed = Boolean.TRUE.equals(node.getNodeMetaData(SEALED_CLASS));
- List<ClassNode> permitted = node.getPermittedSubclasses();
- if (!sealed || !permitted.isEmpty() || node.getModule() == null) return;
- for (ClassNode possibleSubclass : node.getModule().getClasses()) {
- if (possibleSubclass.getSuperClass().equals(node)) {
- permitted.add(possibleSubclass);
- }
- for (ClassNode iface : possibleSubclass.getInterfaces()) {
- if (iface.equals(node)) {
- permitted.add(possibleSubclass);
- }
- }
- }
- List<Expression> names = new ArrayList<>();
- for (ClassNode next : permitted) {
- names.add(classX(ClassHelper.make(next.getName())));
- }
- AnnotationNode an = node.getAnnotations(SEALED_TYPE).get(0);
- an.addMember("permittedSubclasses", new ListExpression(names));
- }
private void checkFinalVariables(final ClassNode node) {
GroovyClassVisitor visitor = new FinalVariableAnalyzer(null, getFinalVariablesCallback());
diff --git a/src/main/java/org/codehaus/groovy/transform/SealedCompletionASTTransformation.java b/src/main/java/org/codehaus/groovy/transform/SealedCompletionASTTransformation.java
new file mode 100644
index 0000000..c7f880c
--- /dev/null
+++ b/src/main/java/org/codehaus/groovy/transform/SealedCompletionASTTransformation.java
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+package org.codehaus.groovy.transform;
+
+import groovy.transform.NonSealed;
+import groovy.transform.Sealed;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotatedNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.ListExpression;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.codehaus.groovy.ast.ClassHelper.make;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.classX;
+
+/**
+ * Handles sealed class permitted subclass detection.
+ */
+@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
+public class SealedCompletionASTTransformation extends AbstractASTTransformation {
+
+ private static final Class<Sealed> SEALED_CLASS = Sealed.class;
+ private static final ClassNode SEALED_TYPE = make(SEALED_CLASS);
+
+ @Override
+ public void visit(ASTNode[] nodes, SourceUnit source) {
+ init(nodes, source);
+ AnnotatedNode parent = (AnnotatedNode) nodes[1];
+ AnnotationNode anno = (AnnotationNode) nodes[0];
+ if (!SEALED_TYPE.equals(anno.getClassNode())) return;
+
+ if (parent instanceof ClassNode) {
+ addDetectedSealedClasses((ClassNode) parent);
+ }
+ }
+
+ private void addDetectedSealedClasses(ClassNode node) {
+ boolean sealed = Boolean.TRUE.equals(node.getNodeMetaData(SEALED_CLASS));
+ List<ClassNode> permitted = node.getPermittedSubclasses();
+ if (!sealed || !permitted.isEmpty() || node.getModule() == null) return;
+ for (ClassNode possibleSubclass : node.getModule().getClasses()) {
+ if (possibleSubclass.getSuperClass().equals(node)) {
+ permitted.add(possibleSubclass);
+ }
+ for (ClassNode iface : possibleSubclass.getInterfaces()) {
+ if (iface.equals(node)) {
+ permitted.add(possibleSubclass);
+ }
+ }
+ }
+ List<Expression> names = new ArrayList<>();
+ for (ClassNode next : permitted) {
+ names.add(classX(ClassHelper.make(next.getName())));
+ }
+ AnnotationNode an = node.getAnnotations(SEALED_TYPE).get(0);
+ an.addMember("permittedSubclasses", new ListExpression(names));
+ }
+}