daniellansun commented on code in PR #3297:
URL: https://github.com/apache/groovy/pull/3297#discussion_r4570320080
##########
src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java:
##########
@@ -205,9 +240,29 @@ public Expression transform(final Expression exp) {
if (pexp.isImplicitThis() || "this".equals(obj)) {
String propName = pexp.getPropertyAsString();
if (knownFields.contains(propName)) {
+ if (isDeclaredInstancePropertyInClosure(propName)) {
+ // this.name in a closure is read through the
accessor, as in a class
+ PropertyExpression propertyExpression =
propX(varX(weaved), propName);
+ propertyExpression.setSourcePosition(exp);
+ return propertyExpression;
+ }
// GROOVY-12587: use the declared field, so a static one
is read through the implementing class
return transformFieldReference(exp,
traitClass.getDeclaredField(propName), null);
}
+ if (propName != null && !inClosure && exp != assignmentTarget)
{
+ String getter = findStaticAccessor(propName, false);
+ if (getter != null) { // GROOVY-12614
+ return transformStaticAccessorCall(exp, getter, null);
+ }
+ }
+ }
+ } else if (exp instanceof PrefixExpression || exp instanceof
PostfixExpression) {
+ Expression oldTarget = assignmentTarget;
+ assignmentTarget = exp instanceof PrefixExpression ?
((PrefixExpression) exp).getExpression() : ((PostfixExpression)
exp).getExpression();
+ try {
+ return super.transform(exp);
+ } finally {
+ assignmentTarget = oldTarget;
}
Review Comment:
For a plain static accessor, `++` and `--` are marked as `assignmentTarget`
and then left to `super.transform`, so they are not rewritten as getter plus
setter, unlike `+=`. With a class override, assignment and `+=` use the trait
accessor, but `++` / `--` use the class getter and setter in dynamic and
`@TypeChecked` code, and under `@CompileStatic` the getter is the trait's and
the setter is the class's. That looks like the older property-form split left
in place, as `COMPATIBILITY.md` already notes that increment and decrement are
unchanged.
The Terms, however, say that increment and decrement have the same meaning
as the name they apply to. Would you consider either bringing these in line
with `+=`, or adjusting the Terms and adding tests in all three modes?
##########
src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java:
##########
@@ -218,10 +273,14 @@ public Expression transform(final Expression exp) {
mce.setImplicitThis(false);
mce.setMethodTarget(ClassHelper.CLOSURE_TYPE.getMethods("rehydrate").get(0));
mce.setSourcePosition(exp);
- boolean oldInClosure = inClosure;
+ boolean oldInClosure = inClosure, oldInLambdaOnly = inLambdaOnly,
oldInLambda = inLambda;
+ inLambdaOnly = exp instanceof LambdaExpression && (!inClosure ||
inLambdaOnly);
inClosure = true;
+ inLambda = oldInLambda || exp instanceof LambdaExpression;
Review Comment:
I may have missed a test for this, but `inLambda` is set with `oldInLambda
|| exp instanceof LambdaExpression`, so it stays true when a regular `{ }`
closure is nested inside a lambda. `isClosurePropertyReference` and
`isDeclaredInstancePropertyInClosure` then return false, and a declared
instance property in that inner closure goes to the backing field in all three
modes, which does not match instance rule 4. The reverse nesting already
follows rule 5. If an implementing-class setter is used as a validation hook,
this path would skip it.
Could this flag track only the innermost construct? A test for `{ name }`
and `this.name` inside a lambda, in all three modes, would make the intended
rule visible. If the present behaviour is kept, I think the guide should say so
plainly.
##########
src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java:
##########
@@ -739,6 +758,24 @@ private static MethodNode
createInterfaceStaticForwarder(final ClassNode traitCl
return forwarder;
}
+ /**
+ * Builds a public-static accessor on the trait interface for a static
trait
+ * field. Implementing classes declare their own accessors, so this one is
+ * reached only when a promoted trait static is called through the trait
+ * itself; it throws, as the trait has no static state of its own.
+ */
+ private static MethodNode createTraitStaticStateAccessor(final ClassNode
traitClass, final FieldNode field, final String name, final Parameter[] params)
{
+ String message = "Cannot access static field " + field.getName() + "
of trait " + traitClass.getName()
+ + " through the trait itself: trait static state belongs to
each implementing class,"
+ + " so call the trait static method on an implementing class";
+ Statement body =
throwS(ctorX(ClassHelper.make(MissingFieldException.class),
+ args(constX(message), constX(field.getName()),
classX(traitClass))));
Review Comment:
The failure mode through the trait itself is now a clearer
`MissingFieldException` that uses the source field name and the trait name, and
does not leak the helper name. The guide already describes this; would a short
`COMPATIBILITY.md` entry be useful as well, especially if the fix is also taken
to 6.0.x?
##########
src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java:
##########
@@ -791,15 +828,36 @@ private MethodNode processMethod(final ClassNode
traitClass, final ClassNode tra
return mNode;
}
- private Statement processBody(final VariableExpression thisObject, final
Statement code, final ClassNode trait, final ClassNode traitHelper, final
ClassNode fieldHelper, final Collection<String> knownFields) {
+ private Statement processBody(final VariableExpression thisObject, final
Statement code, final ClassNode trait, final ClassNode traitHelper, final
ClassNode fieldHelper, final Collection<String> knownFields, final boolean
staticallyCompiled) {
if (code != null) {
code.visit(new NAryOperationRewriter(sourceUnit, knownFields));
code.visit(new SuperCallTraitTransformer(sourceUnit));
- code.visit(new TraitReceiverTransformer(thisObject, sourceUnit,
trait, traitHelper, fieldHelper, knownFields));
+ code.visit(new TraitReceiverTransformer(thisObject, sourceUnit,
trait, traitHelper, fieldHelper, knownFields, staticallyCompiled));
}
return code;
}
+ /**
+ * Indicates whether trait code will be statically compiled: the member,
or else the trait, is
+ * annotated with {@code @CompileStatic}, and not with {@code
@CompileDynamic} or in skip mode.
+ */
+ private static boolean isStaticallyCompiled(final AnnotatedNode member,
final ClassNode trait) {
+ for (AnnotatedNode node : new AnnotatedNode[]{member, trait}) {
+ boolean compileStatic = false;
+ for (AnnotationNode annotation : node.getAnnotations()) {
+ String name = annotation.getClassNode().getName();
+ Expression mode = annotation.getMember("value");
+ if (name.equals("groovy.transform.CompileDynamic") || (mode !=
null && mode.getText().equals("groovy.transform.TypeCheckingMode.SKIP")
+ && (name.equals("groovy.transform.CompileStatic") ||
name.equals("groovy.transform.TypeChecked")))) {
+ return false;
+ }
+ compileStatic = compileStatic ||
name.equals("groovy.transform.CompileStatic");
+ }
+ if (compileStatic) return true;
+ }
+ return false;
+ }
Review Comment:
`isStaticallyCompiled` only looks at annotations on the member or the trait.
A method body still ends up as `invokestatic` when `@CompileStatic` is applied
only through a compiler customizer, so the main effect is whether the
GROOVY-12608 statically compiled lambda rewrite is triggered. It may be enough
to document or test that case.
##########
src/spec/doc/_traits.adoc:
##########
@@ -812,6 +823,173 @@ getters and setters, like in this last example:
include::../test/TraitsSpecificationTest.groovy[tags=intcouple_impl_override_directgetter,indent=0]
----
+[[traits-member-access]]
+== Member access in trait code
+
+This section states, as rules, which method, accessor or field a name in trait
code refers to. The rules are the
+same for dynamic, `@TypeChecked` and `@CompileStatic` code: the compilation
mode decides _when_ a name is resolved and
+what is reported for a name that cannot be resolved, but not _what_ a
resolvable name refers to.
+
+=== Terms
+
+Trait code::
+The body of a method declared in a trait, including the bodies of closures and
lambdas nested in it. In the rules
+below, a _method body_ means the code of the method outside any nested closure
or lambda.
+
+Implementing class::
+For an instance member, the class of the object the trait code is running for.
For a static member, the class that
+names the trait in its `implements` clause. A subclass of that class is not an
implementing class in its own right:
+trait code called through the subclass runs for the class that implements the
trait.
+
+Declared property::
+A property the trait declares with a property declaration, such as `String
name`. The trait supplies its storage
+(its _backing field_) and, unless the trait declares them itself, its accessor
methods.
+
+Accessor-only property::
+A property that exists only because the trait declares an accessor method,
such as `String getTitle()`. It has no
+backing field.
+
+Forms of reference::
+For a property `p`, the _simple name_ `p`, the _qualified name_ `this.p`, and
the _method form_ `getP()`, `isP()`
+or `setP(v)`, with or without `this.`. An assignment, compound assignment,
increment or decrement of `p` is a
+reference of the same form as the name it is applied to.
+
+=== Instance members
+
+For instance members, a trait behaves as a superclass of the implementing
class would
+(see <<The meaning of this>>).
+
+. *Methods are virtual.* A call `m()` or `this.m()` from trait code invokes
the method the implementing class has for
+that signature: its own declaration if there is one, otherwise the trait's.
This holds in a method body, a closure and
+a lambda, and it holds for accessor methods called in the method form.
+. *An accessor-only property is its accessor.* A simple or qualified name that
refers to an accessor-only property is
+a call of the accessor, to which rule 1 applies.
+. *In a method body, a declared property is its backing field.* The simple
name `p` and the qualified name `this.p`
+read or write the trait's backing field directly. No accessor is called, so an
accessor that the implementing class
+declares is not used. This is what the same names mean in the class that
declares a property.
+. *In a closure, a declared property is its accessor.* The simple name `p` is
looked up through the closure's
+delegate and owner according to its resolve strategy, like any other name in a
closure. With the default strategy and
+no delegate that has the property, the owner is asked, and it answers through
its accessor. The qualified name
+`this.p` is not offered to the delegate: it is a call of the accessor on the
implementing instance. Rule 1 applies to
+the accessor in both cases. This is what the same names mean in a closure in
the class that declares a property.
+. *In a lambda, a declared property is its backing field.* Rule 3 applies to
the simple name `p` in a lambda as it
+does in a method body. A statically compiled lambda has no delegate or owner
to resolve the name through.
+
+[source,groovy]
+----
+include::../test/TraitsSpecificationTest.groovy[tags=member_access_instance,indent=0]
+----
+<1> a declared property
+<2> an accessor-only property
+<3> rule 3: the backing field of the trait
+<4> rule 1: the accessor of the implementing class
+<5> rule 4: the accessor of the implementing class, reached through the
closure or called on `this`
+<6> rule 2: a call of the accessor, in a method body and in a closure alike
+<7> the implementing class declares accessors of its own
+<8> code outside the trait always goes through the accessor
+
+To let an implementing class supply the value that trait code sees, read the
property in the method form, or declare
+it as an accessor-only property.
+
+=== Static members
+
+Static members of a trait belong to the implementing class. They are not
shared between the classes that implement
+the trait, and they are not inherited the way instance members are.
+
+. *Static state is per implementing class.* Each implementing class has its
own copy of every static field and
+declared static property of the trait.
+. *Static methods are not virtual.* A call `m()` or `this.m()` from trait code
to a static method of the trait invokes
+the trait's own method, even when the implementing class declares a static
method with the same signature. This holds
+in a method body, a closure and a lambda, and is what a static method call
means in a class.
+. *`@Virtual` makes a static method virtual in method bodies.* A call from a
method body to a static method the trait
+declares with `@Virtual` invokes the implementing class's static method with
that signature if it declares one,
+and the trait's otherwise. A call from a closure or a lambda is not affected
by `@Virtual`: rule 2 applies to it.
+. *A static accessor-only property is its accessor.* A simple or qualified
name that refers to a static accessor-only
+property is a call of the accessor, to which rules 2 and 3 apply: the trait's
own accessor, or for a `@Virtual`
+accessor in a method body, the implementing class's. An assignment `p = v` is
a call of the setter, and a compound
+assignment `p op= v` is a call of the setter with the value of `getP() op v`.
+. *A declared static property is its backing field.* The simple name `p` and
the qualified name `this.p` read or
+write the implementing class's copy of the trait's static field, in a method
body, a closure and a lambda. No accessor
+is called.
+
+[source,groovy]
+----
+include::../test/TraitsSpecificationTest.groovy[tags=member_access_static,indent=0]
+----
+<1> a declared static property
+<2> a static accessor-only property
+<3> a `@Virtual` static accessor-only property
+<4> rule 5: the trait's static field, not the accessor of `Item`
+<5> rules 2 and 4: the trait's own accessor, called or read as a property
+<6> rules 3 and 4: the static method of the implementing class, called or read
as a property
+<7> rule 3: `@Virtual` does not extend into a closure
+<8> rule 3: `Plain` declares no `getLabel()`, so the trait's is used
+
+[source,groovy]
+----
+include::../test/TraitsSpecificationTest.groovy[tags=member_access_static_state,indent=0]
+----
+<1> rule 5: updates the copy of `total` that belongs to the class `add` was
called on
+<2> rule 1: `Apples` and `Pears` each have their own `total`
+<3> code outside the trait reads the property of each class
+
+=== Summary
+
+The table shows what trait code uses for a member named `p` (or `getP()`),
when the implementing class also declares
+an accessor `getP()`. _Class_ means the implementing class's accessor and
_trait_ means the trait's own accessor or
+backing field.
+
+[cols="3a,2a,2a,2a,2a"]
+|===
+| Member of the trait | Reference | In a method body | In a closure | In a
lambda
+
+| Instance accessor-only property
+| `p`, `this.p`, `getP()`
+| class
+| class
+| class
+
+.2+| Declared instance property
+| `p`, `this.p`
+| trait (field)
+| class
+| trait (field)
+
+| `getP()`
+| class
+| class
+| class
+
+| Static accessor-only property
+| `p`, `this.p`, `getP()`
+| trait
+| trait
+| trait
+
+| `@Virtual` static accessor-only property
+| `p`, `this.p`, `getP()`
+| class
+| trait
+| trait
+
+| Declared static property
+| `p`, `this.p`, `getP()`
+| trait
+| trait
+| trait
+|===
+
+[NOTE]
+====
+Two parts of this table describe the rules rather than what every compilation
mode does today:
+
+* A _name_ (`p` or `this.p`) of a static accessor-only property in a closure
or a lambda is resolved by the closure,
+so that its delegate can supply the name. When no delegate does, dynamic and
`@TypeChecked` code reach the
+implementing class's accessor, with or without `@Virtual`, where the rules
give the trait's own. The method form
+`getP()` follows the rules in every mode.
Review Comment:
Would it be worth spelling out the `@CompileStatic` case for a `@Virtual`
static accessor as well?
`TraitMemberAccessMatrix.virtualStaticAccessorOnlyProperty` records that
`label` and `this.label` in a closure or a lambda use the implementing class in
all three modes, whereas a plain static accessor does so only in dynamic and
`@TypeChecked` code. The table can stay as the rule; I think the NOTE should
list that cell the same way the matrix does.
##########
src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java:
##########
@@ -426,6 +465,51 @@ protected boolean writeDirectMethodCall(final MethodNode
target, final boolean i
}
}
+ /**
+ * Returns the trait helper method behind {@code target} when {@code
target} is a
+ * static method of a trait, which the trait interface forwards to its
helper with
+ * the trait as the receiver class.
+ */
+ private static MethodNode findTraitHelperMethod(final MethodNode target) {
+ if (target.isStatic() && isTrait(target.getDeclaringClass())) {
+ Parameter[] parameters = target.getParameters();
+ for (MethodNode method :
Traits.findHelper(target.getDeclaringClass()).getDeclaredMethods(target.getName()))
{
+ Parameter[] helperParameters = method.getParameters();
+ if (method.isStatic() && helperParameters.length ==
parameters.length + 1
+ &&
ClassHelper.isClassType(helperParameters[0].getType())
+ &&
ParameterUtils.parametersEqual(Arrays.copyOfRange(helperParameters, 1,
helperParameters.length), parameters)) {
+ return method;
+ }
+ }
+ }
+ return null;
Review Comment:
A super-trait static accessor in a statically compiled method body does not
yet take the same `invokestatic` path as a closure. This lookup only runs when
`target.isStatic() && isTrait(target.getDeclaringClass())`, and only when
`closureThis || isTraitSelf(receiver)`. `transformMethodCallOnThis` writes a
super-trait `getN()` as `this.getN($static$self)` without `setMethodTarget`, so
the writer sees the child helper. The result is still correct, but the method
body goes through `invokedynamic` and boxing, while the closure path is already
`invokestatic` on the super-trait helper. Aligning the two would need the call
to be bound to the super-trait helper, not only a wider lookup. I mention this
in case you want to take it in a follow-up.
##########
src/test/groovy/org/codehaus/groovy/transform/traitx/TraitASTTransformationTest.groovy:
##########
@@ -2420,6 +2420,535 @@ final class TraitASTTransformationTest {
"""
}
+ // GROOVY-12593
+ @CompileModesTest
+ void testTraitStaticPropertyNamedLikeFieldOfClass(String mode) {
+ for (name in ['name', 'module', 'componentType', 'packageName']) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static String $name = 'x'
+ static String sm1() { $name = 'a'; $name }
+ static String sm2() { this.$name = 'b'; $name }
+ static String sm3() { $name += 'c'; $name }
+ static String sm4() { Closure c = { -> $name = 'd' };
c.call(); $name }
+ static String sm5() { Runnable r = () -> { $name = 'e' };
r.run(); $name }
+ String im1() { $name = 'f'; $name }
+ String im2() { this.$name = 'g'; $name }
+ }
+ $mode
+ class C implements T {
+ }
+
+ $mode void m() {
+ assert C.sm1() == 'a'
+ assert C.sm2() == 'b'
+ assert C.sm3() == 'bc'
+ assert C.sm4() == 'd'
+ assert C.sm5() == 'e'
+ assert C.$name == 'e'
+ assert new C().im1() == 'f'
+ assert new C().im2() == 'g'
+ assert C.$name == 'g'
+ }
+ m()
+ """
+ }
+
+ assertScript shell, """
+ $mode
+ trait T {
+ static String name = 'x'
+ }
+ $mode
+ trait U extends T {
+ static void update(String value) { name = value }
+ }
+ $mode
+ class C implements U {
+ }
+
+ $mode void m() {
+ C.update('y')
+ assert C.name == 'y'
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12597
+ @CompileModesTest
+ void testTraitStaticStateThroughTrait(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ private static boolean flag = true
+ static int count = 1
+ static boolean isReady() { flag }
+ static void setReady(boolean b) { flag = b }
+ static boolean viaClosure() { [1].collect { flag }[0] }
+ private static int peek() { count }
+ static int viaPrivate() { peek() }
+ static String pure() { 'pure' }
+ }
+ $mode
+ class C implements T {
+ }
+ $mode
+ class D extends C {
+ }
+
+ $mode
+ void expectNoState(String field, Closure action) {
+ try {
+ action.call()
+ assert false : 'expected MissingFieldException'
+ } catch (MissingFieldException e) {
+ assert e.field == field
+ assert e.type == T
+ assert e.message == 'Cannot access static field ' + field
+ ' of trait T through the trait itself: ' +
+ 'trait static state belongs to each implementing
class, so call the trait static method on an implementing class'
+ }
+ }
+
+ $mode void m() {
+ assert C.isReady() && C.ready && D.isReady()
+ assert C.viaClosure() && C.viaPrivate() == 1 && C.count == 1
+ C.setReady(false)
+ assert !C.isReady()
+
+ expectNoState('flag') { T.isReady() }
+ expectNoState('flag') { T.ready }
+ expectNoState('flag') { T.setReady(true) }
+ expectNoState('flag') { T.viaClosure() }
+ expectNoState('count') { T.viaPrivate() }
+ expectNoState('count') { T.getCount() }
+ expectNoState('count') { T.count }
+ assert T.pure() == 'pure'
+
+ assert !C.isReady()
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12590
+ @CompileModesTest
+ void testTraitStaticAccessorReadAsProperty(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static boolean flag = true
+ static boolean isReady() { flag }
+ static String sm() { ready ? 'yes' : 'no' }
+ static String st() { this.ready ? 'yes' : 'no' }
+ static Closure getG() { { -> flag } }
+ static Object sg() { g.call() }
+ }
+ $mode
+ class C implements T {
+ }
+ $mode
+ class D implements T {
+ }
+
+ $mode void m() {
+ assert C.sm() == 'yes'
+ assert C.st() == 'yes'
+ assert C.sg() == true
+ D.flag = false // each implementing class has its own trait
state
+ assert C.sm() == 'yes'
+ assert D.sm() == 'no'
+ assert D.st() == 'no'
+ assert D.sg() == false
+ }
+ m()
+ """
+
+ assertScript shell, """
+ import java.util.function.Supplier
+
+ $mode
+ trait T {
+ static boolean flag = true
+ static boolean isReady() { flag }
+ String getName() { 'name' }
+ String im() { ready ? 'yes' : 'no' }
+ String iname() { name }
+ String ic() { def c = { -> ready ? 'yes' : 'no' }; c() }
+ static String sc() { def c = { -> ready ? 'yes' : 'no' }; c() }
+ static String sl() { Supplier<String> s = () -> ready ? 'yes'
: 'no'; s.get() }
+ }
+ $mode
+ class C implements T {
+ }
+ $mode
+ class D implements T {
+ }
+
+ $mode void m() {
+ D.flag = false
+ assert new C().im() == 'yes'
+ assert new D().im() == 'no'
+ assert new C().iname() == 'name'
+ assert new C().ic() == 'yes'
+ assert new D().ic() == 'no'
+ assert C.sc() == 'yes'
+ assert D.sc() == 'no'
+ assert C.sl() == 'yes'
+ assert D.sl() == 'no'
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12590
+ @CompileModesTest
+ void testTraitStaticAccessorWrittenAsProperty(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ static int set(int n) { cnt = n; count }
+ static int add(int n) { cnt += n; count }
+ static int post() { cnt++; count }
+ static int pre() { ++cnt; count }
+ int iset(int n) { cnt = n; count }
+ int iadd(int n) { cnt += n; count }
+ int ipost() { cnt++; count }
+ }
+ $mode
+ class C implements T {
+ }
+
+ $mode void m() {
+ assert C.set(10) == 10
+ assert C.add(5) == 15
+ assert C.post() == 16
+ assert C.pre() == 17
+ assert new C().iset(20) == 20
+ assert new C().iadd(5) == 25
+ assert new C().ipost() == 26
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12590
+ @CompileModesTest
+ void testSuperTraitStaticAccessorAsProperty(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ }
+ $mode
+ trait U extends T {
+ static int s() { cnt }
+ int i() { cnt = 5; cnt++; cnt }
+ }
+ $mode
+ class C implements U {
+ }
+
+ $mode void m() {
+ assert C.s() == 1
+ assert new C().i() == 6
+ assert C.s() == 6
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12614
+ @CompileModesTest
+ void testStaticAccessorReadAsPropertyIsCallOfTheAccessor(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static String getLabel() { 'trait' }
+ static boolean isReady() { false }
+ static String sm() { label }
+ static String sm2() { this.label }
+ static String sm3() { getLabel() }
+ static boolean sm4() { ready }
+ String im() { label }
+ String im2() { this.label }
+ String im3() { "\$label" }
+ }
+ class C implements T {
+ static String getLabel() { 'class' }
+ static boolean isReady() { true }
+ }
+ class D implements T {
+ }
+
+ assert [C.sm(), C.sm2(), C.sm3(), C.sm4()] == ['trait', 'trait',
'trait', false]
+ assert [D.sm(), D.sm2(), D.sm3(), D.sm4()] == ['trait', 'trait',
'trait', false]
+ assert [new C().im(), new C().im2(), new C().im3()] == ['trait',
'trait', 'trait']
+ assert C.label == 'class' && C.ready && D.label == 'trait'
+ """
+ }
+
+ // GROOVY-12614
+ @CompileModesTest
+ void testStaticAccessorWrittenAsPropertyIsCallOfTheAccessor(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ private static List<String> log = []
+ private static int count = 1
+ static int getCnt() { log << 'trait get'; count }
+ static void setCnt(int n) { log << 'trait set'; count = n }
+ static List<String> assign() { cnt = 5; log }
+ static List<String> assignThis() { this.cnt = 6; log }
+ static List<String> compound() { cnt += 2; log }
+ static List<String> compoundThis() { this.cnt *= 3; log }
+ List<String> instanceAssign() { cnt = 7; log }
+ static int value() { count }
+ }
+ class C implements T {
+ static List<String> classLog = []
+ static int getCnt() { classLog << 'class get'; 100 }
+ static void setCnt(int n) { classLog << 'class set' }
+ }
+
+ assert C.assign() == ['trait set'] && C.value() == 5
+ assert C.assignThis() == ['trait set'] * 2 && C.value() == 6
+ assert C.compound() == ['trait set', 'trait set', 'trait get',
'trait set'] && C.value() == 8
+ assert C.compoundThis().size() == 6 && C.value() == 24
+ assert new C().instanceAssign().size() == 7 && C.value() == 7
+ assert C.classLog == []
+ """
+ }
+
+ // GROOVY-12614
+ @CompileModesTest
+ void testSuperTraitStaticAccessorAsPropertyIsCallOfTheAccessor(String
mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ static String getLabel() { 'trait' }
+ @Virtual static String getKind() { 'trait' }
+ }
+ $mode
+ trait U extends T {
+ static String sm() { label }
+ static String sm2() { kind }
+ String im() { this.label }
+ String im2() { this.kind }
+ }
+ class C implements U {
+ static String getLabel() { 'class' }
+ static String getKind() { 'class' }
+ }
+ class D implements U {
+ }
+
+ assert [C.sm(), C.sm2(), new C().im(), new C().im2()] == ['trait',
'class', 'trait', 'class']
+ assert [D.sm(), D.sm2(), new D().im(), new D().im2()] == ['trait',
'trait', 'trait', 'trait']
+ """
+ }
+
+ @CompileModesTest
+ void testThisPropertyInClosureUsesTheAccessor(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ String name = 'trait'
+ String read() { def c = { -> this.name }; c() }
+ String readDirect() { this.name }
+ void write(String s) { def c = { -> this.name = s }; c() }
+ }
+ class C implements T {
+ List<String> log = []
+ String getName() { log << 'get'; 'class' }
+ void setName(String s) { log << "set \$s".toString() }
+ }
+
+ def c = new C()
+ assert c.read() == 'class'
+ assert c.readDirect() == 'trait'
+ c.write('x')
+ assert c.log == ['get', 'set x']
+ assert c.readDirect() == 'trait'
+ """
+ }
+
+ // GROOVY-12608
+ @CompileModesTest
+ void testSuperTraitStaticAccessorAsPropertyInClosure(String mode) {
+ assertScript shell, """
+ $mode
+ trait T {
+ private static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ static boolean isReady() { count > 0 }
+ }
+ $mode
+ trait U extends T {
+ int ic() { def c = { -> cnt }; c() }
+ String ir() { def c = { -> ready ? 'yes' : 'no' }; c() }
+ int inner() { def c = { -> def d = { -> cnt }; d() }; c() }
+ int iset(int n) { def c = { -> cnt = n }; c(); cnt }
+ int ipost() { def c = { -> cnt++ }; c(); cnt }
+ static int sc() { def c = { -> cnt }; c() }
+ static int sadd(int n) { def c = { -> cnt += n }; c(); cnt }
+ }
+ $mode
+ trait V extends U {
+ int vc() { def c = { -> cnt }; c() }
+ }
+ $mode
+ class C implements V {
+ }
+ $mode
+ class D implements V {
+ }
+
+ $mode void m() {
+ D.cnt = 0 // each implementing class has its own trait state
+ assert new D().ic() == 0
+ assert D.sc() == 0
+ assert new D().ir() == 'no'
+ assert new C().ic() == 1
+ assert new C().ir() == 'yes'
+ assert new C().inner() == 1
+ assert C.sc() == 1
+ assert new C().iset(5) == 5
+ assert new C().ipost() == 6
+ assert C.sadd(2) == 8
+ assert new C().vc() == 8
+ }
+ m()
+ """
+
+ assertScript shell, """
+ import java.util.function.Supplier
+
+ $mode
+ trait T {
+ static int count = 1
+ static String s = 'x'
+ }
+ $mode
+ trait U extends T {
+ int ic() { def c = { -> count }; c() }
+ static int sc() { def c = { -> count }; c() }
+ static String sw() { def c = { -> s = 'y' }; c(); s }
+ String iw() { def c = { -> s = 'z' }; c(); s }
+ int il() { Supplier<Integer> s = () -> count; s.get() }
+ static int sl() { Supplier<Integer> s = () -> count; s.get() }
+ static int sset(int n) { Runnable r = () -> { count = n };
r.run(); count }
+ }
+ $mode
+ class C implements U {
+ }
+ $mode
+ class D implements U {
+ }
+
+ $mode void m() {
+ D.count = 2 // each implementing class has its own trait state
+ assert new C().ic() == 1
+ assert new D().ic() == 2
+ assert C.sc() == 1
+ assert D.sc() == 2
+ assert C.sw() == 'y'
+ assert new C().iw() == 'z'
+ assert D.s == 'x'
+ assert new C().il() == 1
+ assert new D().il() == 2
+ assert C.sl() == 1
+ assert D.sl() == 2
+ assert C.sset(3) == 3
+ assert D.count == 2
+ }
+ m()
+ """
+
+ // the closure's delegate still comes first
+ assertScript shell, """
+ class P {
+ int cnt = 42
+ }
+ $mode
+ trait T {
+ private static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ }
+ $mode
+ trait U extends T {
+ int get(P p) { p.with { cnt } }
+ int set(P p, int n) { p.with { cnt = n }; cnt }
+ static int sget(P p) { p.with { cnt } }
+ }
+ $mode
+ class C implements U {
+ }
+
+ $mode void m() {
+ def p = new P()
+ assert new C().get(p) == 42
+ assert C.sget(p) == 42
+ assert new C().set(p, 7) == 1
+ assert p.cnt == 7
+ }
+ m()
+ """
+ }
+
+ // GROOVY-12608
+ @ParameterizedTest
+ @ValueSource(strings=['@TypeChecked','@CompileStatic'])
+ void testSuperTraitStaticSetterNotInheritedThroughOtherReceiver(String
mode) {
+ def err = shouldFail shell, """
+ $mode
+ trait T {
+ private static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ }
+ $mode
+ trait U extends T {
+ void copyTo(U other) { other.cnt = 5 }
+ }
+ """
+ assert err.message.contains('Cannot set read-only property: cnt')
+ }
+
+ // GROOVY-12608
+ @ParameterizedTest
+ @ValueSource(strings=['@CompileDynamic','@TypeChecked'])
+ void testSuperTraitStaticAccessorAsPropertyInLambdaWithDelegate(String
mode) {
+ assertScript shell, """
+ class P {
+ int cnt = 42
+ }
+ $mode
+ trait T {
+ private static int count = 1
+ static int getCnt() { count }
+ static void setCnt(int n) { count = n }
+ }
+ $mode
+ trait U extends T {
+ int get(P p) { p.with((x) -> cnt) }
+ }
+ $mode
+ class C implements U {
+ }
+
+ assert new C().get(new P()) == 42
Review Comment:
This official GROOVY-12608 case locks only `@CompileDynamic` and
`@TypeChecked`, where the delegate supplies `42`. The same script under
`@CompileStatic` returns `1` (the delegate is ignored). Could `@CompileStatic`
be locked as well, and the NOTE or an open cell record that difference?
##########
src/spec/doc/_traits.adoc:
##########
@@ -812,6 +823,173 @@ getters and setters, like in this last example:
include::../test/TraitsSpecificationTest.groovy[tags=intcouple_impl_override_directgetter,indent=0]
----
+[[traits-member-access]]
+== Member access in trait code
+
+This section states, as rules, which method, accessor or field a name in trait
code refers to. The rules are the
+same for dynamic, `@TypeChecked` and `@CompileStatic` code: the compilation
mode decides _when_ a name is resolved and
+what is reported for a name that cannot be resolved, but not _what_ a
resolvable name refers to.
+
+=== Terms
+
+Trait code::
+The body of a method declared in a trait, including the bodies of closures and
lambdas nested in it. In the rules
+below, a _method body_ means the code of the method outside any nested closure
or lambda.
+
+Implementing class::
+For an instance member, the class of the object the trait code is running for.
For a static member, the class that
+names the trait in its `implements` clause. A subclass of that class is not an
implementing class in its own right:
+trait code called through the subclass runs for the class that implements the
trait.
+
+Declared property::
+A property the trait declares with a property declaration, such as `String
name`. The trait supplies its storage
+(its _backing field_) and, unless the trait declares them itself, its accessor
methods.
+
+Accessor-only property::
+A property that exists only because the trait declares an accessor method,
such as `String getTitle()`. It has no
+backing field.
+
+Forms of reference::
+For a property `p`, the _simple name_ `p`, the _qualified name_ `this.p`, and
the _method form_ `getP()`, `isP()`
+or `setP(v)`, with or without `this.`. An assignment, compound assignment,
increment or decrement of `p` is a
+reference of the same form as the name it is applied to.
Review Comment:
As noted on the transformer, this synonymy does not currently hold for `++`
and `--` on a plain static accessor-only property. Could the Terms or static
rule 4 mention that these are not brought in line with the new rule, unless the
rewrite is completed?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]