You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2016/11/16 14:56:08 UTC
[1/7] groovy git commit: GROOVY-7970: Can't call private method from
outer class when using anonymous inner classes and @CS (closes #452)
Repository: groovy
Updated Branches:
refs/heads/parrot e058a848b -> a49e1d9d9
GROOVY-7970: Can't call private method from outer class when using anonymous inner classes and @CS (closes #452)
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/ad566692
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/ad566692
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/ad566692
Branch: refs/heads/parrot
Commit: ad566692dbc355e1962ba6b61a5b8fe1dad8b966
Parents: 6f39e27
Author: paulk <pa...@asert.com.au>
Authored: Tue Oct 25 14:30:08 2016 +1000
Committer: paulk <pa...@asert.com.au>
Committed: Fri Nov 11 06:06:10 2016 +1000
----------------------------------------------------------------------
.../classgen/asm/sc/StaticInvocationWriter.java | 62 +++++++--
.../stc/StaticTypeCheckingVisitor.java | 7 +-
src/test/groovy/bugs/Groovy7970Bug.groovy | 125 +++++++++++++++++++
3 files changed, 184 insertions(+), 10 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/ad566692/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
index 0541d20..09ca8ae 100644
--- a/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
+++ b/src/main/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
@@ -22,6 +22,7 @@ import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
+import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
@@ -186,7 +187,16 @@ public class StaticInvocationWriter extends InvocationWriter {
/**
* Attempts to make a direct method call on a bridge method, if it exists.
*/
+ @Deprecated
protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis, TupleExpression args) {
+ return tryBridgeMethod(target, receiver, implicitThis, args, null);
+ }
+
+ /**
+ * Attempts to make a direct method call on a bridge method, if it exists.
+ */
+ protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis,
+ TupleExpression args, ClassNode thisClass) {
ClassNode lookupClassNode;
if (target.isProtected()) {
lookupClassNode = controller.getClassNode();
@@ -203,8 +213,22 @@ public class StaticInvocationWriter extends InvocationWriter {
MethodNode bridge = bridges==null?null:bridges.get(target);
if (bridge != null) {
Expression fixedReceiver = receiver;
- if (implicitThis && !controller.isInClosure()) {
- fixedReceiver = new PropertyExpression(new ClassExpression(lookupClassNode), "this");
+ if (implicitThis) {
+ if (!controller.isInClosure()) {
+ fixedReceiver = new PropertyExpression(new ClassExpression(lookupClassNode), "this");
+ } else if (thisClass != null) {
+ ClassNode current = thisClass.getOuterClass();
+ fixedReceiver = new VariableExpression("thisObject", current);
+ // adjust for multiple levels of nesting if needed
+ while (current != null && current instanceof InnerClassNode && !lookupClassNode.equals(current)) {
+ FieldNode thisField = current.getField("this$0");
+ current = current.getOuterClass();
+ if (thisField != null) {
+ fixedReceiver = new PropertyExpression(fixedReceiver, "this$0");
+ fixedReceiver.setType(current);
+ }
+ }
+ }
}
ArgumentListExpression newArgs = new ArgumentListExpression(target.isStatic()?new ConstantExpression(null):fixedReceiver);
for (Expression expression : args.getExpressions()) {
@@ -261,7 +285,7 @@ public class StaticInvocationWriter extends InvocationWriter {
&& controller.isInClosure()
&& !target.isPublic()
&& target.getDeclaringClass() != classNode) {
- if (!tryBridgeMethod(target, receiver, implicitThis, args)) {
+ if (!tryBridgeMethod(target, receiver, implicitThis, args, classNode)) {
// replace call with an invoker helper call
ArrayExpression arr = new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions());
MethodCallExpression mce = new MethodCallExpression(
@@ -281,6 +305,8 @@ public class StaticInvocationWriter extends InvocationWriter {
}
return true;
}
+ Expression fixedReceiver = null;
+ boolean fixedImplicitThis = implicitThis;
if (target.isPrivate()) {
if (tryPrivateMethod(target, implicitThis, receiver, args, classNode)) return true;
} else if (target.isProtected()) {
@@ -295,16 +321,36 @@ public class StaticInvocationWriter extends InvocationWriter {
controller.getSourceUnit().addError(
new SyntaxException("Method " + target.getName() + " is protected in " + target.getDeclaringClass().toString(false),
src.getLineNumber(), src.getColumnNumber(), src.getLastLineNumber(), src.getLastColumnNumber()));
- } else if (!node.isDerivedFrom(target.getDeclaringClass()) && tryBridgeMethod(target, receiver, implicitThis, args)) {
+ } else if (!node.isDerivedFrom(target.getDeclaringClass()) && tryBridgeMethod(target, receiver, implicitThis, args, classNode)) {
return true;
}
+ } else if (target.isPublic() && receiver != null) {
+ if (implicitThis
+ && !classNode.isDerivedFrom(target.getDeclaringClass())
+ && !classNode.implementsInterface(target.getDeclaringClass())
+ && classNode instanceof InnerClassNode && controller.isInClosure()) {
+ ClassNode current = classNode.getOuterClass();
+ fixedReceiver = new VariableExpression("thisObject", current);
+ // adjust for multiple levels of nesting if needed
+ while (current != null && current instanceof InnerClassNode && !classNode.equals(current)) {
+ FieldNode thisField = current.getField("this$0");
+ current = current.getOuterClass();
+ if (thisField != null) {
+ fixedReceiver = new PropertyExpression(fixedReceiver, "this$0");
+ fixedReceiver.setType(current);
+ fixedImplicitThis = false;
+ }
+ }
+ }
}
if (receiver != null) {
- if (!(receiver instanceof VariableExpression) || !((VariableExpression) receiver).isSuperExpression()) {
+ boolean callToSuper = receiver instanceof VariableExpression && ((VariableExpression) receiver).isSuperExpression();
+ if (!callToSuper) {
+ fixedReceiver = fixedReceiver == null ? receiver : fixedReceiver;
// in order to avoid calls to castToType, which is the dynamic behaviour, we make sure that we call CHECKCAST instead
// then replace the top operand type
- Expression checkCastReceiver = new CheckcastReceiverExpression(receiver, target);
- return super.writeDirectMethodCall(target, implicitThis, checkCastReceiver, args);
+ Expression checkCastReceiver = new CheckcastReceiverExpression(fixedReceiver, target);
+ return super.writeDirectMethodCall(target, fixedImplicitThis, checkCastReceiver, args);
}
}
return super.writeDirectMethodCall(target, implicitThis, receiver, args);
@@ -316,7 +362,7 @@ public class StaticInvocationWriter extends InvocationWriter {
if ((isPrivateBridgeMethodsCallAllowed(declaringClass, classNode) || isPrivateBridgeMethodsCallAllowed(classNode, declaringClass))
&& declaringClass.getNodeMetaData(PRIVATE_BRIDGE_METHODS) != null
&& !declaringClass.equals(classNode)) {
- if (tryBridgeMethod(target, receiver, implicitThis, args)) {
+ if (tryBridgeMethod(target, receiver, implicitThis, args, classNode)) {
return true;
} else if (declaringClass != classNode) {
controller.getSourceUnit().addError(new SyntaxException("Cannot call private method " + (target.isStatic() ? "static " : "") +
http://git-wip-us.apache.org/repos/asf/groovy/blob/ad566692/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index c21166b..f16ff82 100644
--- a/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -3849,8 +3849,11 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
collectAllInterfaceMethodsByName(receiver, name, methods);
methods.addAll(OBJECT_TYPE.getMethods(name));
}
- if (typeCheckingContext.getEnclosingClosure() == null) {
- // not in a closure
+ // TODO: investigate the trait exclusion a bit further, needed otherwise
+ // CallMethodOfTraitInsideClosureAndClosureParamTypeInference fails saying
+ // not static method can't be called from a static context
+ if (typeCheckingContext.getEnclosingClosure() == null || (receiver instanceof InnerClassNode && !receiver.getName().endsWith("$Trait$Helper"))) {
+ // not in a closure or within an inner class
ClassNode parent = receiver;
while (parent instanceof InnerClassNode && !parent.isStaticClass()) {
parent = parent.getOuterClass();
http://git-wip-us.apache.org/repos/asf/groovy/blob/ad566692/src/test/groovy/bugs/Groovy7970Bug.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/bugs/Groovy7970Bug.groovy b/src/test/groovy/bugs/Groovy7970Bug.groovy
new file mode 100644
index 0000000..9bda2a3
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy7970Bug.groovy
@@ -0,0 +1,125 @@
+/*
+ * 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 groovy.bugs
+
+class Groovy7970Bug extends GroovyTestCase {
+
+ private static final String getScriptAIC(String visibility, boolean cs) {
+ """
+ ${ cs ? '@groovy.transform.CompileStatic' : ''}
+ class Bar {
+ $visibility String renderTemplate(String arg) { "dummy\$arg" }
+ def foo() {
+ new Object() {
+ String bar() {
+ 'A'.with{ renderTemplate(it) }
+ }
+ }
+ }
+ }
+ assert new Bar().foo().bar() == 'dummyA'
+ """
+ }
+
+ private static final String getScriptNestedAIC(String visibility, boolean cs) {
+ """
+ ${ cs ? '@groovy.transform.CompileStatic' : ''}
+ class Bar {
+ $visibility String renderTemplate(String arg) { "dummy\$arg" }
+ def foo() {
+ new Object() {
+ def bar() {
+ new Object() { String xxx() { 'B'.with{ renderTemplate(it) } }}
+ }
+ }
+ }
+ }
+ assert new Bar().foo().bar().xxx() == 'dummyB'
+ """
+ }
+
+ private static final String getScriptInner(String visibility, boolean cs) {
+ """
+ ${ cs ? '@groovy.transform.CompileStatic' : ''}
+ class Bar {
+ $visibility String renderTemplate(String arg) { "dummy\$arg" }
+ class Inner {
+ String baz() {
+ 'C'.with{ renderTemplate(it) }
+ }
+ }
+ }
+ def b = new Bar()
+ assert new Bar.Inner(b).baz() == 'dummyC'
+ """
+ }
+
+ private static final String getScriptNestedInner(String visibility, boolean cs) {
+ """
+ ${ cs ? '@groovy.transform.CompileStatic' : ''}
+ class Bar {
+ $visibility String renderTemplate(String arg) { "dummy\$arg" }
+ class Inner {
+ class InnerInner {
+ String xxx() { 'D'.with{ renderTemplate(it) } }
+ }
+ }
+ }
+ def b = new Bar()
+ def bi = new Bar.Inner(b)
+ assert new Bar.Inner.InnerInner(bi).xxx() == 'dummyD'
+ """
+ }
+
+ void testMethodAccessFromClosureWithinInnerClass() {
+ assertScript getScriptInner('public', false)
+ assertScript getScriptInner('protected', false)
+ assertScript getScriptInner('private', false)
+ assertScript getScriptNestedInner('public', false)
+ assertScript getScriptNestedInner('protected', false)
+ assertScript getScriptNestedInner('private', false)
+ }
+
+ void testMethodAccessFromClosureWithinInnerClass_CS() {
+ assertScript getScriptInner('public', true)
+ assertScript getScriptInner('protected', true)
+ assertScript getScriptInner('private', true)
+ assertScript getScriptNestedInner('public', true)
+ assertScript getScriptNestedInner('protected', true)
+ assertScript getScriptNestedInner('private', true)
+ }
+
+ void testMethodAccessFromClosureWithinAIC() {
+ assertScript getScriptAIC('public', false)
+ assertScript getScriptAIC('protected', false)
+ assertScript getScriptAIC('private', false)
+ assertScript getScriptNestedAIC('public', false)
+ assertScript getScriptNestedAIC('protected', false)
+ assertScript getScriptNestedAIC('private', false)
+ }
+
+ void testMethodAccessFromClosureWithinAIC_CS() {
+ assertScript getScriptAIC('public', true)
+ assertScript getScriptAIC('protected', true)
+ assertScript getScriptAIC('private', true)
+ assertScript getScriptNestedAIC('public', true)
+ assertScript getScriptNestedAIC('protected', true)
+ assertScript getScriptNestedAIC('private', true)
+ }
+}
[6/7] groovy git commit: GROOVY-3976: Improve "with" by ending with
implied "return delegate" (closes #174)
Posted by su...@apache.org.
GROOVY-3976: Improve "with" by ending with implied "return delegate" (closes #174)
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/bc90dd98
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/bc90dd98
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/bc90dd98
Branch: refs/heads/parrot
Commit: bc90dd981ff0f6b4853420f0604345375992333a
Parents: fc88b52
Author: paulk <pa...@asert.com.au>
Authored: Wed Nov 16 08:54:27 2016 +1000
Committer: paulk <pa...@asert.com.au>
Committed: Wed Nov 16 08:54:27 2016 +1000
----------------------------------------------------------------------
.../groovy/runtime/DefaultGroovyMethods.java | 71 +++++++++++++++++---
src/spec/doc/style-guide.adoc | 4 +-
src/test/groovy/lang/TapMethodTest.groovy | 26 +++----
src/test/groovy/lang/WithMethodTest.groovy | 51 +++++++++-----
4 files changed, 115 insertions(+), 37 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/bc90dd98/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index 5fdcc41..d23c1b5 100644
--- a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -197,12 +197,19 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* return it
* }
* </pre>
+ * The other typical usage, uses the self object while creating some value:
+ * <pre>
+ * def fullName = person.with{ "$firstName $lastName" }
+ * </pre>
*
* @param self the object to have a closure act upon
* @param closure the closure to call on the object
* @return result of calling the closure
+ * @see #with(Object, boolean, Closure)
+ * @see #tap(Object, Closure)
* @since 1.5.0
*/
+ @SuppressWarnings("unchecked")
public static <T,U> T with(
@DelegatesTo.Target("self") U self,
@DelegatesTo(value=DelegatesTo.Target.class,
@@ -210,11 +217,61 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
strategy=Closure.DELEGATE_FIRST)
@ClosureParams(FirstParam.class)
Closure<T> closure) {
+ return (T) with(self, false, (Closure<Object>)closure);
+ }
+
+ /**
+ * Allows the closure to be called for the object reference self.
+ * <p/>
+ * Any method invoked inside the closure will first be invoked on the
+ * self reference. For exampe, the following method calls to the append()
+ * method are invoked on the StringBuilder instance and then, because
+ * 'returning' is true, the self instance is returned:
+ * <pre class="groovyTestCase">
+ * def b = new StringBuilder().with(true) {
+ * append('foo')
+ * append('bar')
+ * }
+ * assert b.toString() == 'foobar'
+ * </pre>
+ * The returning parameter is commonly set to true when using with to simplify object
+ * creation, such as this example:
+ * <pre>
+ * def p = new Person().with(true) {
+ * firstName = 'John'
+ * lastName = 'Doe'
+ * }
+ * </pre>
+ * Alternatively, 'tap' is an alias for 'with(true)', so that method can be used instead.
+ *
+ * The other main use case for with is when returning a value calculated using self as shown here:
+ * <pre>
+ * def fullName = person.with(false){ "$firstName $lastName" }
+ * </pre>
+ * Alternatively, 'with' is an alias for 'with(false)', so the boolean parameter can be ommitted instead.
+ *
+ * @param self the object to have a closure act upon
+ * @param returning if true, return the self object; otherwise, the result of calling the closure
+ * @param closure the closure to call on the object
+ * @return the self object or the result of calling the closure depending on 'returning'
+ * @see #with(Object, Closure)
+ * @see #tap(Object, Closure)
+ * @since 2.5.0
+ */
+ public static <T,U extends T, V extends T> T with(
+ @DelegatesTo.Target("self") U self,
+ boolean returning,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
@SuppressWarnings("unchecked")
- final Closure<T> clonedClosure = (Closure<T>) closure.clone();
+ final Closure<V> clonedClosure = (Closure<V>) closure.clone();
clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
clonedClosure.setDelegate(self);
- return clonedClosure.call(self);
+ V result = clonedClosure.call(self);
+ return returning ? self : result;
}
/**
@@ -242,8 +299,11 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @param self the object to have a closure act upon
* @param closure the closure to call on the object
* @return self
+ * @see #with(Object, boolean, Closure)
+ * @see #with(Object, Closure)
* @since 2.5.0
*/
+ @SuppressWarnings("unchecked")
public static <T,U> U tap(
@DelegatesTo.Target("self") U self,
@DelegatesTo(value=DelegatesTo.Target.class,
@@ -251,12 +311,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
strategy=Closure.DELEGATE_FIRST)
@ClosureParams(FirstParam.class)
Closure<T> closure) {
- @SuppressWarnings("unchecked")
- final Closure<T> clonedClosure = (Closure<T>) closure.clone();
- clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
- clonedClosure.setDelegate(self);
- clonedClosure.call(self);
- return self;
+ return (U) with(self, true, (Closure<Object>)closure);
}
/**
http://git-wip-us.apache.org/repos/asf/groovy/blob/bc90dd98/src/spec/doc/style-guide.adoc
----------------------------------------------------------------------
diff --git a/src/spec/doc/style-guide.adoc b/src/spec/doc/style-guide.adoc
index a9e54f7..344632a 100644
--- a/src/spec/doc/style-guide.adoc
+++ b/src/spec/doc/style-guide.adoc
@@ -347,7 +347,7 @@ As with any closure in Groovy, the last statement is considered the return value
----
def person = new Person().with {
name = "Ada Lovelace"
- it // Note the explicit return
+ it // Note the explicit mention of it as the return value
}
----
@@ -360,6 +360,8 @@ def person = new Person().tap {
}
----
+Note: you can also use `with(true)` instead of `tap()` and `with(false)` instead of `with()`.
+
== Equals and `==`
Java's `==` is actually Groovy's `is()` method, and Groovy's `==` is a clever `equals()`!
http://git-wip-us.apache.org/repos/asf/groovy/blob/bc90dd98/src/test/groovy/lang/TapMethodTest.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/TapMethodTest.groovy b/src/test/groovy/lang/TapMethodTest.groovy
index db29150..95e4774 100644
--- a/src/test/groovy/lang/TapMethodTest.groovy
+++ b/src/test/groovy/lang/TapMethodTest.groovy
@@ -1,23 +1,25 @@
/*
- * Copyright 2003-2016 the original author or authors.
+ * 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
*
- * Licensed 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
*
- * 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.
+ * 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 groovy.lang
/**
* Tests the .tap method
- *
*/
class TapMethodTest extends GroovyTestCase {
http://git-wip-us.apache.org/repos/asf/groovy/blob/bc90dd98/src/test/groovy/lang/WithMethodTest.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/WithMethodTest.groovy b/src/test/groovy/lang/WithMethodTest.groovy
index 41f0460..d93ea48 100644
--- a/src/test/groovy/lang/WithMethodTest.groovy
+++ b/src/test/groovy/lang/WithMethodTest.groovy
@@ -20,10 +20,9 @@ package groovy.lang
/**
* Tests the .with method
- *
*/
- class WithMethodTest extends GroovyTestCase {
-
+class WithMethodTest extends GroovyTestCase {
+
void testDelegateGetsFirstOpportunity() {
def sb = new StringBuffer()
@@ -32,55 +31,75 @@ package groovy.lang
// delegate not, the owner
append 'some text'
}
-
+
assertEquals 'delegate had wrong value', 'some text', sb.toString()
}
-
+
void testOwnerGetsOpportunityIfDelegateCannotRespond() {
def sb = new StringBuffer()
-
+
def returnValue
-
+
sb.with {
// this should call ownerMethod() on the owner
returnValue = ownerMethod()
}
-
+
assertEquals 'owner should have responded to method call',
42,
returnValue
}
-
+
void testCallingNonExistentMethod() {
def sb = new StringBuffer()
-
+
shouldFail(MissingMethodException) {
sb.with {
someNoneExistentMethod()
}
}
}
-
+
void testClosureWithResolveStrategyExplicitlySet() {
def closure = {
append 'some text'
}
closure.resolveStrategy = Closure.OWNER_ONLY
-
+
def sb = new StringBuffer()
-
+
// .with should use DELEGATE_FIRST, even though
// the closure has another strategy set
sb.with closure
-
+
assertEquals 'delegate had wrong value', 'some text', sb.toString()
}
-
+
+ void testBooleanVariant() {
+ def p = new PersonWith(firstName: 'Johnny', lastName: 'Depp')
+ def result1 = p.with(false) {
+ "$firstName $lastName"
+ }
+ assert result1 instanceof GString
+ assert result1.toString() == 'Johnny Depp'
+ def result2 = p.with(true) {
+ lastName = 'Cash'
+ }
+ assert result2 instanceof PersonWith
+ assert result2.toString() == 'WithMethodTest$PersonWith(Johnny, Cash)'
+ }
+
def ownerMethod() {
42
}
-
+
void append(String s) {
fail 'this should never have been called'
}
+
+ @groovy.transform.ToString(includePackage = false)
+ class PersonWith {
+ String firstName
+ String lastName
+ }
}
\ No newline at end of file
[4/7] groovy git commit: GROOVY-7997: fix long and BigInteger to
BigDecimal conversion in method calls
Posted by su...@apache.org.
GROOVY-7997: fix long and BigInteger to BigDecimal conversion in method calls
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/04f1e863
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/04f1e863
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/04f1e863
Branch: refs/heads/parrot
Commit: 04f1e8636f98388dd04787b5b7028ea870aeef0b
Parents: baa86a3
Author: Jochen Theodorou <bl...@gmx.org>
Authored: Tue Nov 15 19:53:36 2016 +0100
Committer: Jochen Theodorou <bl...@gmx.org>
Committed: Tue Nov 15 19:53:36 2016 +0100
----------------------------------------------------------------------
.../stdclasses/BigDecimalCachedClass.java | 8 +++--
.../groovy/vmplugin/v7/TypeTransformers.java | 32 ++++++++++++++------
src/test/groovy/PrimitiveTypesTest.groovy | 17 ++++++++++-
3 files changed, 44 insertions(+), 13 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/04f1e863/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java b/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java
index 2a447c4..e98f6b9 100644
--- a/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java
+++ b/src/main/org/codehaus/groovy/reflection/stdclasses/BigDecimalCachedClass.java
@@ -18,9 +18,9 @@
*/
package org.codehaus.groovy.reflection.stdclasses;
-import org.codehaus.groovy.reflection.ClassInfo;
-
import java.math.BigDecimal;
+import java.math.BigInteger;
+import org.codehaus.groovy.reflection.ClassInfo;
/**
* @author Alex.Tkachman
@@ -37,6 +37,10 @@ public class BigDecimalCachedClass extends DoubleCachedClass {
public Object coerceArgument(Object argument) {
if (argument instanceof BigDecimal) {
return argument;
+ } else if (argument instanceof Long) {
+ return new BigDecimal((Long) argument);
+ } else if (argument instanceof BigInteger) {
+ return new BigDecimal((BigInteger) argument);
}
if (argument instanceof Number) {
http://git-wip-us.apache.org/repos/asf/groovy/blob/04f1e863/src/main/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java b/src/main/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java
index c64abe1..4764f52 100644
--- a/src/main/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java
+++ b/src/main/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java
@@ -22,7 +22,6 @@ import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.GroovyObject;
import groovy.util.ProxyGenerator;
-
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
@@ -34,7 +33,6 @@ import java.math.BigInteger;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.reflection.stdclasses.CachedSAMClass;
import org.codehaus.groovy.runtime.ConvertedClosure;
@@ -49,8 +47,9 @@ public class TypeTransformers {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodHandle
TO_STRING, TO_BYTE, TO_INT, TO_LONG, TO_SHORT,
- TO_FLOAT, TO_DOUBLE, TO_BIG_INT, TO_BIG_DEC, AS_ARRAY,
- TO_REFLECTIVE_PROXY, TO_GENERATED_PROXY, TO_SAMTRAIT_PROXY;
+ TO_FLOAT, TO_DOUBLE, TO_BIG_INT, AS_ARRAY,
+ TO_REFLECTIVE_PROXY, TO_GENERATED_PROXY, TO_SAMTRAIT_PROXY,
+ DOUBLE_TO_BIG_DEC, DOUBLE_TO_BIG_DEC_WITH_CONVERSION, LONG_TO_BIG_DEC, BIG_INT_TO_BIG_DEC;
static {
try {
TO_STRING = LOOKUP.findVirtual(Object.class, "toString", MethodType.methodType(String.class));
@@ -62,13 +61,18 @@ public class TypeTransformers {
TO_DOUBLE = LOOKUP.findVirtual(Number.class, "doubleValue", MethodType.methodType(Double.TYPE));
// BigDecimal conversion is done by using the double value
- // if the given number.
- MethodHandle tmp = LOOKUP.findConstructor(BigDecimal.class, MethodType.methodType(Void.TYPE, Double.TYPE));
- TO_BIG_DEC = MethodHandles.filterReturnValue(TO_DOUBLE, tmp);
+ DOUBLE_TO_BIG_DEC = LOOKUP.findConstructor(BigDecimal.class, MethodType.methodType(Void.TYPE, Double.TYPE));
+ DOUBLE_TO_BIG_DEC_WITH_CONVERSION = MethodHandles.filterReturnValue(TO_DOUBLE, DOUBLE_TO_BIG_DEC);
+
+ // BigDecimal conversion is done by using the double value
+ LONG_TO_BIG_DEC = LOOKUP.findConstructor(BigDecimal.class, MethodType.methodType(Void.TYPE, Long.TYPE));
+
+ // BigDecimal conversion is done by using the double value
+ BIG_INT_TO_BIG_DEC = LOOKUP.findConstructor(BigDecimal.class, MethodType.methodType(Void.TYPE, BigInteger.class));
+
// BigInteger conversion is done by using the string representation
- // if the given number
- tmp = LOOKUP.findConstructor(BigInteger.class, MethodType.methodType(Void.TYPE, String.class));
+ MethodHandle tmp = LOOKUP.findConstructor(BigInteger.class, MethodType.methodType(Void.TYPE, String.class));
TO_BIG_INT = MethodHandles.filterReturnValue(TO_STRING, tmp);
// generic array to array conversion
@@ -220,7 +224,15 @@ public class TypeTransformers {
} else if (param == BigInteger.class) {
return TO_BIG_INT;
} else if (param == BigDecimal.class) {
- return TO_BIG_DEC;
+ if (arg instanceof Double) {
+ return DOUBLE_TO_BIG_DEC;
+ } else if (arg instanceof Long) {
+ return LONG_TO_BIG_DEC;
+ } else if (arg instanceof BigInteger) {
+ return BIG_INT_TO_BIG_DEC;
+ } else {
+ return DOUBLE_TO_BIG_DEC_WITH_CONVERSION;
+ }
} else if (param == Short.class) {
return TO_SHORT;
} else {
http://git-wip-us.apache.org/repos/asf/groovy/blob/04f1e863/src/test/groovy/PrimitiveTypesTest.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/PrimitiveTypesTest.groovy b/src/test/groovy/PrimitiveTypesTest.groovy
index 66aadf7..bbc2f90 100644
--- a/src/test/groovy/PrimitiveTypesTest.groovy
+++ b/src/test/groovy/PrimitiveTypesTest.groovy
@@ -78,7 +78,22 @@ class PrimitiveTypesTest extends GroovyTestCase {
assert getNextShort((Short) 1) == 2
assert 3 == getNextShort((Short) 2)
}
-
+
+ void testLong2BigDecimal() {
+ long l = Long.MAX_VALUE
+ assert l == testMethod(l).longValueExact()
+ }
+
+ void testBigInteger2BigDecimal() {
+ BigInteger big = new BigInteger(Long.MAX_VALUE)
+ assert big.longValueExact() == testMethod(big).longValueExact()
+ }
+
+ private testMethod(BigDecimal bd) {
+ return bd;
+ }
+
+
static void main(args) {
new PrimitiveTypesTest().testPrimitiveTypes()
}
[2/7] groovy git commit: GROOVY-7994: Anonymous inner class believes
protected method in parent's superclass returns Object
Posted by su...@apache.org.
GROOVY-7994: Anonymous inner class believes protected method in parent's superclass returns Object
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/81b1cc7b
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/81b1cc7b
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/81b1cc7b
Branch: refs/heads/parrot
Commit: 81b1cc7b603659ba58d5f097b73d0f2f1095f8b1
Parents: ad56669
Author: paulk <pa...@asert.com.au>
Authored: Thu Nov 10 16:31:46 2016 +1000
Committer: paulk <pa...@asert.com.au>
Committed: Fri Nov 11 06:21:39 2016 +1000
----------------------------------------------------------------------
.../stc/StaticTypeCheckingVisitor.java | 12 +++-
src/test/groovy/bugs/Groovy7994Bug.groovy | 69 ++++++++++++++++++++
2 files changed, 79 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/81b1cc7b/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index f16ff82..f675526 100644
--- a/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1250,9 +1250,9 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
if (storeField(field, isThisExpression, pexp, receiver.getType(), visitor, receiver.getData(), !readMode))
return true;
- MethodNode getter = current.getGetterMethod("get" + capName);
+ MethodNode getter = findGetter(current, "get" + capName, pexp.isImplicitThis());
getter = allowStaticAccessToMember(getter, staticOnly);
- if (getter == null) getter = current.getGetterMethod("is" + capName);
+ if (getter == null) getter = findGetter(current, "is" + capName, pexp.isImplicitThis());
getter = allowStaticAccessToMember(getter, staticOnly);
final String setterName = "set" + capName;
List<MethodNode> setters = findSetters(current, setterName, false);
@@ -1362,6 +1362,14 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
return foundGetterOrSetter;
}
+ private MethodNode findGetter(ClassNode current, String name, boolean searchOuterClasses) {
+ MethodNode getterMethod = current.getGetterMethod(name);
+ if (getterMethod == null && searchOuterClasses && current instanceof InnerClassNode) {
+ return findGetter(current.getOuterClass(), name, true);
+ }
+ return getterMethod;
+ }
+
private ClassNode getTypeForSpreadExpression(ClassNode testClass, ClassNode objectExpressionType, PropertyExpression pexp) {
if (!pexp.isSpreadSafe()) return null;
MethodCallExpression mce = new MethodCallExpression(new VariableExpression("_", testClass), "iterator", ArgumentListExpression.EMPTY_ARGUMENTS);
http://git-wip-us.apache.org/repos/asf/groovy/blob/81b1cc7b/src/test/groovy/bugs/Groovy7994Bug.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/bugs/Groovy7994Bug.groovy b/src/test/groovy/bugs/Groovy7994Bug.groovy
new file mode 100644
index 0000000..4f4c84a
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy7994Bug.groovy
@@ -0,0 +1,69 @@
+/*
+ * 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 groovy.bugs
+
+class Groovy7994Bug extends GroovyTestCase {
+ void testJavaBeanPropertiesAvailableInInnerClasses() {
+ assertScript '''
+ import groovy.transform.CompileStatic
+
+ @CompileStatic
+ class Outer {
+ String prop = 'wally'
+ String getName() { "sally" }
+ class Inner {
+ String innerGo() { new Other(name).text + new Other(Outer.this.name).text + new Other(getName()).text }
+ }
+ String go() {
+ new Other(name).text + new Other(getName()).text
+ }
+ def makeAIC() {
+ new Object() {
+ String aicGo() { new Other(name).text + new Other(Outer.this.name).text + new Other(getName()).text }
+ String staticMethodGo() { Other.foo(name) + Other.foo(Outer.this.name) + Other.foo(getName()) }
+ String instanceMethodGo() { new Other().bar(name) + new Other().bar(getName()) }
+ String methodWithClosureGo() { new Other().with { bar(name) + bar(getName()) } }
+ String propGo() { new Other(prop).text + new Other(getProp()).text }
+ }
+ }
+ }
+
+ @CompileStatic
+ class Other {
+ public final String text
+ static String foo(Object object) { "Object|$object:" }
+ static String foo(String string) { "String|$string:" }
+ String bar(Object object) { "Object|$object:" }
+ String bar(String string) { "String|$string:" }
+ Other(Object object) { text = "Object:$object|" }
+ Other(String string) { text = "String:$string|" }
+ Other() {}
+ }
+
+ def o = new Outer()
+ assert o.go() == 'String:sally|String:sally|'
+ assert o.makeAIC().aicGo() == 'String:sally|String:sally|String:sally|'
+ assert o.makeAIC().propGo() == 'String:wally|String:wally|'
+ assert o.makeAIC().staticMethodGo() == 'String|sally:String|sally:String|sally:'
+ assert o.makeAIC().instanceMethodGo() == 'String|sally:String|sally:'
+ assert o.makeAIC().methodWithClosureGo() == 'String|sally:String|sally:'
+ assert new Outer.Inner(o).innerGo() == 'String:sally|String:sally|String:sally|'
+ '''
+ }
+}
[3/7] groovy git commit: GROOVY-7089: Base64 URL Safe encoder (closes
#450)
Posted by su...@apache.org.
GROOVY-7089: Base64 URL Safe encoder (closes #450)
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/baa86a3b
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/baa86a3b
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/baa86a3b
Branch: refs/heads/parrot
Commit: baa86a3b3eacd165cb85b9531ded9983a23e3c41
Parents: 81b1cc7
Author: John Wagenleitner <jw...@apache.org>
Authored: Sun Nov 13 09:21:56 2016 -0800
Committer: John Wagenleitner <jw...@apache.org>
Committed: Sun Nov 13 11:23:59 2016 -0800
----------------------------------------------------------------------
.../groovy/runtime/EncodingGroovyMethods.java | 120 +++++++++++++--
.../runtime/EncodingGroovyMethodsSupport.java | 33 +++++
src/test/groovy/Base64Test.groovy | 147 +++++++++++++++++++
3 files changed, 289 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/baa86a3b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java
index cd141cc..f8aeb49 100644
--- a/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java
+++ b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java
@@ -27,6 +27,9 @@ import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
+import static org.codehaus.groovy.runtime.EncodingGroovyMethodsSupport.TRANSLATE_TABLE;
+import static org.codehaus.groovy.runtime.EncodingGroovyMethodsSupport.TRANSLATE_TABLE_URLSAFE;
+
/**
* This class defines all the encoding/decoding groovy methods which enhance
* the normal JDK classes when inside the Groovy environment.
@@ -36,6 +39,8 @@ public class EncodingGroovyMethods {
private static final char[] T_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
+ private static final char[] T_TABLE_URLSAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=".toCharArray();
+
private static final String CHUNK_SEPARATOR = "\r\n";
/**
@@ -76,18 +81,22 @@ public class EncodingGroovyMethods {
* @since 1.5.7
*/
public static Writable encodeBase64(final byte[] data, final boolean chunked) {
+ return encodeBase64(data, chunked, false, true);
+ }
+
+ private static Writable encodeBase64(final byte[] data, final boolean chunked, final boolean urlSafe, final boolean pad) {
return new Writable() {
public Writer writeTo(final Writer writer) throws IOException {
int charCount = 0;
final int dLimit = (data.length / 3) * 3;
-
+ final char[] table = urlSafe ? T_TABLE_URLSAFE : T_TABLE;
for (int dIndex = 0; dIndex != dLimit; dIndex += 3) {
int d = ((data[dIndex] & 0XFF) << 16) | ((data[dIndex + 1] & 0XFF) << 8) | (data[dIndex + 2] & 0XFF);
- writer.write(T_TABLE[d >> 18]);
- writer.write(T_TABLE[(d >> 12) & 0X3F]);
- writer.write(T_TABLE[(d >> 6) & 0X3F]);
- writer.write(T_TABLE[d & 0X3F]);
+ writer.write(table[d >> 18]);
+ writer.write(table[(d >> 12) & 0X3F]);
+ writer.write(table[(d >> 6) & 0X3F]);
+ writer.write(table[d & 0X3F]);
if (chunked && ++charCount == 19) {
writer.write(CHUNK_SEPARATOR);
@@ -102,10 +111,16 @@ public class EncodingGroovyMethods {
d |= (data[dLimit + 1] & 0XFF) << 8;
}
- writer.write(T_TABLE[d >> 18]);
- writer.write(T_TABLE[(d >> 12) & 0X3F]);
- writer.write((dLimit + 1 < data.length) ? T_TABLE[(d >> 6) & 0X3F] : '=');
- writer.write('=');
+ writer.write(table[d >> 18]);
+ writer.write(table[(d >> 12) & 0X3F]);
+ if (pad) {
+ writer.write((dLimit + 1 < data.length) ? table[(d >> 6) & 0X3F] : '=');
+ writer.write('=');
+ } else {
+ if (dLimit + 1 < data.length) {
+ writer.write(table[(d >> 6) & 0X3F]);
+ }
+ }
if (chunked && charCount != 0) {
writer.write(CHUNK_SEPARATOR);
}
@@ -142,6 +157,74 @@ public class EncodingGroovyMethods {
}
/**
+ * Produce a Writable object which writes the Base64 URL and Filename Safe encoding of the byte array.
+ * Calling toString() on the result returns the encoding as a String. For more
+ * information on Base64 URL and Filename Safe encoding see <code>RFC 4648 - Section 5
+ * Base 64 Encoding with URL and Filename Safe Alphabet</code>.
+ * <p>
+ * The method omits padding and is equivalent to calling
+ * {@link org.codehaus.groovy.runtime.EncodingGroovyMethods#encodeBase64Url(Byte[], boolean)} with a
+ * value of {@code false}.
+ *
+ * @param data Byte array to be encoded
+ * @return object which will write the Base64 URL and Filename Safe encoding of the byte array
+ * @see org.codehaus.groovy.runtime.EncodingGroovyMethods#encodeBase64Url(Byte[], boolean)
+ * @since 2.5
+ */
+ public static Writable encodeBase64Url(Byte[] data) {
+ return encodeBase64Url(data, false);
+ }
+
+ /**
+ * Produce a Writable object which writes the Base64 URL and Filename Safe encoding of the byte array.
+ * Calling toString() on the result returns the encoding as a String. For more
+ * information on Base64 URL and Filename Safe encoding see <code>RFC 4648 - Section 5
+ * Base 64 Encoding with URL and Filename Safe Alphabet</code>.
+ *
+ * @param data Byte array to be encoded
+ * @param pad whether or not the encoded data should be padded
+ * @return object which will write the Base64 URL and Filename Safe encoding of the byte array
+ * @since 2.5
+ */
+ public static Writable encodeBase64Url(Byte[] data, boolean pad) {
+ return encodeBase64Url(DefaultTypeTransformation.convertToByteArray(data), pad);
+ }
+
+ /**
+ * Produce a Writable object which writes the Base64 URL and Filename Safe encoding of the byte array.
+ * Calling toString() on the result returns the encoding as a String. For more
+ * information on Base64 URL and Filename Safe encoding see <code>RFC 4648 - Section 5
+ * Base 64 Encoding with URL and Filename Safe Alphabet</code>.
+ * <p>
+ * The method omits padding and is equivalent to calling
+ * {@link org.codehaus.groovy.runtime.EncodingGroovyMethods#encodeBase64Url(byte[], boolean)} with a
+ * value of {@code false}.
+ *
+ * @param data Byte array to be encoded
+ * @return object which will write the Base64 URL and Filename Safe encoding of the byte array
+ * @see org.codehaus.groovy.runtime.EncodingGroovyMethods#encodeBase64Url(byte[], boolean)
+ * @since 2.5
+ */
+ public static Writable encodeBase64Url(final byte[] data) {
+ return encodeBase64Url(data, false);
+ }
+
+ /**
+ * Produce a Writable object which writes the Base64 URL and Filename Safe encoding of the byte array.
+ * Calling toString() on the result returns the encoding as a String. For more
+ * information on Base64 URL and Filename Safe encoding see <code>RFC 4648 - Section 5
+ * Base 64 Encoding with URL and Filename Safe Alphabet</code>.
+ *
+ * @param data Byte array to be encoded
+ * @param pad whether or not the encoded data should be padded
+ * @return object which will write the Base64 URL and Filename Safe encoding of the byte array
+ * @since 2.5
+ */
+ public static Writable encodeBase64Url(final byte[] data, final boolean pad) {
+ return encodeBase64(data, false, true, pad);
+ }
+
+ /**
* Decode the String from Base64 into a byte array.
*
* @param value the string to be decoded
@@ -149,14 +232,29 @@ public class EncodingGroovyMethods {
* @since 1.0
*/
public static byte[] decodeBase64(String value) {
+ return decodeBase64(value, false);
+ }
+
+ /**
+ * Decodes a Base64 URL and Filename Safe encoded String into a byte array.
+ *
+ * @param value the string to be decoded
+ * @return the decoded bytes as an array
+ * @since 2.5
+ */
+ public static byte[] decodeBase64Url(String value) {
+ return decodeBase64(value, true);
+ }
+
+ private static byte[] decodeBase64(String value, boolean urlSafe) {
int byteShift = 4;
int tmp = 0;
boolean done = false;
final StringBuilder buffer = new StringBuilder();
-
+ final byte[] table = urlSafe ? TRANSLATE_TABLE_URLSAFE : TRANSLATE_TABLE;
for (int i = 0; i != value.length(); i++) {
final char c = value.charAt(i);
- final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;
+ final int sixBit = (c < 123) ? table[c] : 66;
if (sixBit < 64) {
if (done)
http://git-wip-us.apache.org/repos/asf/groovy/blob/baa86a3b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java
index a019dad..ef134bd 100644
--- a/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java
+++ b/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethodsSupport.java
@@ -54,4 +54,37 @@ public class EncodingGroovyMethodsSupport {
+ "\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030"
// x y z
+ "\u0031\u0032\u0033").getBytes();
+
+ static final byte[] TRANSLATE_TABLE_URLSAFE = (
+ "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ // \t \n \r
+ + "\u0042\u0042\u0041\u0041\u0042\u0042\u0041\u0042"
+ //
+ + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ //
+ + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ // sp ! " # $ % & '
+ + "\u0041\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ // ( ) * + , - . /
+ + "\u0042\u0042\u0042\u0042\u0042\u003E\u0042\u0042"
+ // 0 1 2 3 4 5 6 7
+ + "\u0034\u0035\u0036\u0037\u0038\u0039\u003A\u003B"
+ // 8 9 : ; < = > ?
+ + "\u003C\u003D\u0042\u0042\u0042\u0040\u0042\u0042"
+ // @ A B C D E F G
+ + "\u0042\u0000\u0001\u0002\u0003\u0004\u0005\u0006"
+ // H I J K L M N O
+ + "\u0007\u0008\t\n\u000B\u000C\r\u000E"
+ // P Q R S T U V W
+ + "\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016"
+ // X Y Z [ \ ] ^ _
+ + "\u0017\u0018\u0019\u0042\u0042\u0042\u0042\u003F"
+ // ' a b c d e f g
+ + "\u0042\u001A\u001B\u001C\u001D\u001E\u001F\u0020"
+ // h i j k l m n o p
+ + "\u0021\"\u0023\u0024\u0025\u0026\u0027\u0028"
+ // p q r s t u v w
+ + "\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030"
+ // x y z
+ + "\u0031\u0032\u0033").getBytes();
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/groovy/blob/baa86a3b/src/test/groovy/Base64Test.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/Base64Test.groovy b/src/test/groovy/Base64Test.groovy
index 42d49b6..2f23bba 100644
--- a/src/test/groovy/Base64Test.groovy
+++ b/src/test/groovy/Base64Test.groovy
@@ -18,10 +18,15 @@
*/
package groovy
+import java.nio.charset.StandardCharsets
+
class Base64Test extends GroovyTestCase {
String testString = '\u00A71234567890-=\u00B1!@\u00A3\$%^&*()_+qwertyuiop[]QWERTYUIOP{}asdfghjkl;\'\\ASDFGHJKL:"|`zxcvbnm,./~ZXCVBNM<>?\u0003\u00ff\u00f0\u000f'
byte[] testBytes = testString.getBytes("ISO-8859-1")
+ // Test bytes that have both the 62nd and 63rd base64 alphabet in the encoded string
+ static final byte[] testBytesChar62And63 = new BigInteger('4bf7ce5201fe239ab42ebead5acd8fa3', 16).toByteArray()
+
void testCodec() {
// turn the bytes back into a string for later comparison
def savedString = new String(testBytes, "ISO-8859-1")
@@ -62,4 +67,146 @@ class Base64Test extends GroovyTestCase {
def encodedBytes = testBytes.encodeBase64().toString()
assert encodedBytes == 'pzEyMzQ1Njc4OTAtPbEhQKMkJV4mKigpXytxd2VydHl1aW9wW11RV0VSVFlVSU9Qe31hc2RmZ2hqa2w7J1xBU0RGR0hKS0w6InxgenhjdmJubSwuL35aWENWQk5NPD4/A//wDw=='
}
+
+ void testRfc4648Section10Encoding() {
+ assert b64('') == ''
+ assert b64('f') == 'Zg=='
+ assert b64('fo') == 'Zm8='
+ assert b64('foo') == 'Zm9v'
+ assert b64('foob') == 'Zm9vYg=='
+ assert b64('fooba') == 'Zm9vYmE='
+ assert b64('foobar') == 'Zm9vYmFy'
+ }
+
+ void testRfc4648Section10Decoding() {
+ assert decodeB64('') == ''
+
+ assert decodeB64('Zg') == 'f'
+ assert decodeB64('Zg==') == 'f'
+
+ assert decodeB64('Zm8') == 'fo'
+ assert decodeB64('Zm8=') == 'fo'
+
+ assert decodeB64('Zm9v') == 'foo'
+
+ assert decodeB64('Zm9vYg') == 'foob'
+ assert decodeB64('Zm9vYg==') == 'foob'
+
+ assert decodeB64('Zm9vYmE') == 'fooba'
+ assert decodeB64('Zm9vYmE=') == 'fooba'
+
+ assert decodeB64('Zm9vYmFy') == 'foobar'
+ }
+
+ void testRfc4648Section10EncodingUrlSafe() {
+ assert b64url('') == ''
+ assert b64url('f') == 'Zg'
+ assert b64url('fo') == 'Zm8'
+ assert b64url('foo') == 'Zm9v'
+ assert b64url('foob') == 'Zm9vYg'
+ assert b64url('fooba') == 'Zm9vYmE'
+ assert b64url('foobar') == 'Zm9vYmFy'
+ }
+
+ void testRfc4648Section10EncodingUrlSafeWithPadding() {
+ assert b64url('', true) == ''
+ assert b64url('f', true) == 'Zg=='
+ assert b64url('fo', true) == 'Zm8='
+ assert b64url('foo', true) == 'Zm9v'
+ assert b64url('foob', true) == 'Zm9vYg=='
+ assert b64url('fooba', true) == 'Zm9vYmE='
+ assert b64url('foobar', true) == 'Zm9vYmFy'
+ }
+
+ void testRfc4648Section10DecodingUrlSafe() {
+ assert decodeB64url('') == ''
+
+ assert decodeB64url('Zg') == 'f'
+ assert decodeB64url('Zg==') == 'f'
+
+ assert decodeB64url('Zm8') == 'fo'
+ assert decodeB64url('Zm8=') == 'fo'
+
+ assert decodeB64url('Zm9v') == 'foo'
+
+ assert decodeB64url('Zm9vYg') == 'foob'
+ assert decodeB64url('Zm9vYg==') == 'foob'
+
+ assert decodeB64url('Zm9vYmE') == 'fooba'
+ assert decodeB64url('Zm9vYmE=') == 'fooba'
+
+ assert decodeB64url('Zm9vYmFy') == 'foobar'
+ }
+
+ void testEncodingWithChar62And63() {
+ assert testBytesChar62And63.encodeBase64().toString() == 'S/fOUgH+I5q0Lr6tWs2Pow=='
+ }
+
+ void testUrlSafeEncodingWithChar62And63() {
+ assert testBytesChar62And63.encodeBase64Url().toString() == 'S_fOUgH-I5q0Lr6tWs2Pow'
+ assert testBytesChar62And63.encodeBase64Url(true).toString() == 'S_fOUgH-I5q0Lr6tWs2Pow=='
+ }
+
+ void testDecodingWithChar62And63() {
+ assert 'S/fOUgH+I5q0Lr6tWs2Pow=='.decodeBase64() == testBytesChar62And63
+ assert 'S/fOUgH+I5q0Lr6tWs2Pow'.decodeBase64() == testBytesChar62And63
+ }
+
+ void testUrlSafeDecodingWithChar62And63() {
+ assert 'S_fOUgH-I5q0Lr6tWs2Pow=='.decodeBase64Url() == testBytesChar62And63
+ assert 'S_fOUgH-I5q0Lr6tWs2Pow'.decodeBase64Url() == testBytesChar62And63
+ }
+
+ void testUrlSafeEncodingByDefaultOmitsPadding() {
+ assert testBytes.encodeBase64Url().toString() ==
+ 'pzEyMzQ1Njc4OTAtPbEhQKMkJV4mKigpXytxd2VydHl1aW9wW11RV0VSVFlVSU9Qe31h' +
+ 'c2RmZ2hqa2w7J1xBU0RGR0hKS0w6InxgenhjdmJubSwuL35aWENWQk5NPD4_A__wDw'
+ }
+
+ void testUrlSafeEncodingWithPadding() {
+ assert testBytes.encodeBase64Url(true).toString() ==
+ 'pzEyMzQ1Njc4OTAtPbEhQKMkJV4mKigpXytxd2VydHl1aW9wW11RV0VSVFlVSU9Qe31h' +
+ 'c2RmZ2hqa2w7J1xBU0RGR0hKS0w6InxgenhjdmJubSwuL35aWENWQk5NPD4_A__wDw=='
+ }
+
+ void testDecodingNonBase64Alphabet() {
+ shouldFail {
+ decodeB64('S_fOUgH-I5q0Lr6tWs2Pow==')
+ }
+ }
+
+ void testUrlSafeDecodingNonUrlSafeAlphabet() {
+ shouldFail {
+ decodeB64url('S/fOUgH+I5q0Lr6tWs2Pow==')
+ }
+ }
+
+ void testDecodingWithInnerPad() {
+ shouldFail {
+ decodeB64('Zm9v=YmE=')
+ }
+ }
+
+ void testUrlSafeDecodingWithInnerPad() {
+ shouldFail {
+ decodeB64url('Zm9v=YmE=')
+ }
+ }
+
+ // Test helper methods
+ private static String b64(String s) {
+ s.getBytes(StandardCharsets.UTF_8).encodeBase64().toString()
+ }
+
+ private static String b64url(String s, boolean pad=false) {
+ s.getBytes(StandardCharsets.UTF_8).encodeBase64Url(pad).toString()
+ }
+
+ private static String decodeB64(String s) {
+ new String(s.decodeBase64(), StandardCharsets.UTF_8)
+ }
+
+ private static String decodeB64url(String s) {
+ new String(s.decodeBase64Url(), StandardCharsets.UTF_8)
+ }
}
[5/7] groovy git commit: Add `tap`: same as `with`,
but returns the incoming object
Posted by su...@apache.org.
Add `tap`: same as `with`, but returns the incoming object
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/fc88b526
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/fc88b526
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/fc88b526
Branch: refs/heads/parrot
Commit: fc88b52637996f25c424a90842a59d360e5b081f
Parents: 04f1e86
Author: Christoph Frick <cf...@ofnir.net>
Authored: Tue Nov 8 13:04:40 2016 +0100
Committer: paulk <pa...@asert.com.au>
Committed: Wed Nov 16 07:16:49 2016 +1000
----------------------------------------------------------------------
.../groovy/runtime/DefaultGroovyMethods.java | 42 +++++++++
src/spec/doc/style-guide.adoc | 23 ++++-
src/test/groovy/lang/TapMethodTest.groovy | 92 ++++++++++++++++++++
3 files changed, 155 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/fc88b526/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index 81bb35e..5fdcc41 100644
--- a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -218,6 +218,48 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
/**
+ * Allows the closure to be called for the object reference self (similar
+ * to <code>with</code> and always returns self.
+ * <p>
+ * Any method invoked inside the closure will first be invoked on the
+ * self reference. For instance, the following method calls to the append()
+ * method are invoked on the StringBuilder instance:
+ * <pre>
+ * def b = new StringBuilder().tap {
+ * append('foo')
+ * append('bar')
+ * }
+ * assert b.toString() == 'foobar'
+ * </pre>
+ * This is commonly used to simplify object creation, such as this example:
+ * <pre>
+ * def p = new Person().tap {
+ * firstName = 'John'
+ * lastName = 'Doe'
+ * }
+ * </pre>
+ *
+ * @param self the object to have a closure act upon
+ * @param closure the closure to call on the object
+ * @return self
+ * @since 2.5.0
+ */
+ public static <T,U> U tap(
+ @DelegatesTo.Target("self") U self,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
+ @SuppressWarnings("unchecked")
+ final Closure<T> clonedClosure = (Closure<T>) closure.clone();
+ clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
+ clonedClosure.setDelegate(self);
+ clonedClosure.call(self);
+ return self;
+ }
+
+ /**
* Allows the subscript operator to be used to lookup dynamic property values.
* <code>bean[somePropertyNameExpression]</code>. The normal property notation
* of groovy is neater and more concise but only works with compile-time known
http://git-wip-us.apache.org/repos/asf/groovy/blob/fc88b526/src/spec/doc/style-guide.adoc
----------------------------------------------------------------------
diff --git a/src/spec/doc/style-guide.adoc b/src/spec/doc/style-guide.adoc
index 5458d0d..a9e54f7 100644
--- a/src/spec/doc/style-guide.adoc
+++ b/src/spec/doc/style-guide.adoc
@@ -313,11 +313,11 @@ You can use named parameters with the default constructor (first the constructor
def server = new Server(name: "Obelix", cluster: aCluster)
----
-== Using with() for repeated operations on the same bean
+== Using `with()` and `tap()` for repeated operations on the same bean
Named-parameters with the default constructor is interesting when creating new instances,
but what if you are updating an instance that was given to you, do you have to repeat the 'server' prefix again and again?
-No, thanks to the with() method that Groovy adds on all objects of any kind:
+No, thanks to the `with()` and `tap()` methods that Groovy adds on all objects of any kind:
[source,groovy]
----
@@ -341,6 +341,25 @@ server.with {
}
----
+As with any closure in Groovy, the last statement is considered the return value. In the example above this is the result of `stop()`. To use this as a builder, that just returns the incoming object, there is also `tap()`:
+
+[source,groovy]
+----
+def person = new Person().with {
+ name = "Ada Lovelace"
+ it // Note the explicit return
+}
+----
+
+vs:
+
+[source,groovy]
+----
+def person = new Person().tap {
+ name = "Ada Lovelace"
+}
+----
+
== Equals and `==`
Java's `==` is actually Groovy's `is()` method, and Groovy's `==` is a clever `equals()`!
http://git-wip-us.apache.org/repos/asf/groovy/blob/fc88b526/src/test/groovy/lang/TapMethodTest.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/TapMethodTest.groovy b/src/test/groovy/lang/TapMethodTest.groovy
new file mode 100644
index 0000000..db29150
--- /dev/null
+++ b/src/test/groovy/lang/TapMethodTest.groovy
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2003-2016 the original author or authors.
+ *
+ * Licensed 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 groovy.lang
+
+/**
+ * Tests the .tap method
+ *
+ */
+class TapMethodTest extends GroovyTestCase {
+
+ void testTapReturnsSelf() {
+ def m1 = [:]
+ def m2 = m1.tap{
+ put("a",1)
+ }
+ assertSame("Outgoing object of tap is not the same as the ingoing", m1, m2)
+ assertEquals("Outgoing object of tap is changed", m2, [a: 1])
+ }
+
+ void testDelegateGetsFirstOpportunity() {
+ def sb = new StringBuffer()
+
+ sb.tap {
+ // this should call append() on the
+ // delegate not, the owner
+ append 'some text'
+ }
+
+ assertEquals 'delegate had wrong value', 'some text', sb.toString()
+ }
+
+ void testOwnerGetsOpportunityIfDelegateCannotRespond() {
+ def sb = new StringBuffer()
+
+ def returnValue
+
+ sb.tap {
+ // this should call ownerMethod() on the owner
+ returnValue = ownerMethod()
+ }
+
+ assertEquals 'owner should have responded to method call',
+ 42,
+ returnValue
+ }
+
+ void testCallingNonExistentMethod() {
+ def sb = new StringBuffer()
+
+ shouldFail(MissingMethodException) {
+ sb.tap {
+ someNoneExistentMethod()
+ }
+ }
+ }
+
+ void testClosureWithResolveStrategyExplicitlySet() {
+ def closure = {
+ append 'some text'
+ }
+ closure.resolveStrategy = Closure.OWNER_ONLY
+
+ def sb = new StringBuffer()
+
+ // .tap should use DELEGATE_FIRST, even though
+ // the closure has another strategy set
+ sb.tap closure
+
+ assertEquals 'delegate had wrong value', 'some text', sb.toString()
+ }
+
+ def ownerMethod() {
+ 42
+ }
+
+ void append(String s) {
+ fail 'this should never have been called'
+ }
+}
[7/7] groovy git commit: Merge branch 'master' of
https://git-wip-us.apache.org/repos/asf/groovy into parrot
Posted by su...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/groovy into parrot
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/a49e1d9d
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/a49e1d9d
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/a49e1d9d
Branch: refs/heads/parrot
Commit: a49e1d9d9821324d9d666a32f620e326b1d7bee4
Parents: e058a84 bc90dd9
Author: Daniel Sun <su...@apache.org>
Authored: Wed Nov 16 22:10:16 2016 +0800
Committer: Daniel Sun <su...@apache.org>
Committed: Wed Nov 16 22:10:16 2016 +0800
----------------------------------------------------------------------
.../classgen/asm/sc/StaticInvocationWriter.java | 62 +++++++-
.../stdclasses/BigDecimalCachedClass.java | 8 +-
.../groovy/runtime/DefaultGroovyMethods.java | 101 ++++++++++++-
.../groovy/runtime/EncodingGroovyMethods.java | 120 +++++++++++++--
.../runtime/EncodingGroovyMethodsSupport.java | 33 +++++
.../stc/StaticTypeCheckingVisitor.java | 19 ++-
.../groovy/vmplugin/v7/TypeTransformers.java | 32 ++--
src/spec/doc/style-guide.adoc | 25 +++-
src/test/groovy/Base64Test.groovy | 147 +++++++++++++++++++
src/test/groovy/PrimitiveTypesTest.groovy | 17 ++-
src/test/groovy/bugs/Groovy7970Bug.groovy | 125 ++++++++++++++++
src/test/groovy/bugs/Groovy7994Bug.groovy | 69 +++++++++
src/test/groovy/lang/TapMethodTest.groovy | 94 ++++++++++++
src/test/groovy/lang/WithMethodTest.groovy | 51 +++++--
14 files changed, 847 insertions(+), 56 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/a49e1d9d/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
----------------------------------------------------------------------